fix: close remaining CAD delivery review gaps

This commit is contained in:
2026-07-11 15:26:43 +08:00
parent 6c1336fa59
commit c12d1d57cb
11 changed files with 464 additions and 93 deletions

View File

@@ -21,6 +21,7 @@ from typing import Any
import showcase_schema
from build_showcase_variants import default_blender
from cad_dxf_report import oda_converter
from delivery_waivers import apply_waivers, parse_waivers
ROOT = Path(__file__).resolve().parent.parent
@@ -192,33 +193,28 @@ def node_script(path: Path, *args: str) -> list[str]:
return [resolve_executable("node"), str(path), *args]
def parse_waivers(values: list[str]) -> dict[str, str]:
waivers: dict[str, str] = {}
for value in values:
name, separator, reason = value.partition("=")
name = name.strip()
reason = reason.strip()
if not separator or not name or not reason:
raise ValueError(f"Invalid waiver {value!r}; expected CHECK=REASON")
if name in waivers:
raise ValueError(f"Duplicate waiver for {name!r}")
waivers[name] = reason
return waivers
def enforce_audit_gates(pipeline: Pipeline, audit_path: Path, waivers: dict[str, str]) -> bool:
report = json.loads(audit_path.read_text(encoding="utf-8"))
blocked = []
waived = []
for gate in report.get("gates", []):
status = str(gate.get("status", "FAIL"))
if status in {"PASS", "NOT_APPLICABLE"}:
continue
name = f"audit:{gate.get('name', 'unnamed')}"
if status in {"WARN", "SKIP"} and name in waivers:
waived.append({"name": name, "original_status": status, "reason": waivers[name]})
else:
blocked.append({"name": name, "status": status, "detail": gate.get("detail", "")})
checks = [
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in report.get("gates", [])
]
audit_waivers = {name: reason for name, reason in waivers.items() if name.startswith("audit:")}
apply_waivers(checks, audit_waivers)
waived = [
{
"name": check["name"],
"original_status": check["original_status"],
"reason": check["waiver_reason"],
}
for check in checks
if "waiver_reason" in check
]
blocked = [check for check in checks if check.get("status") not in {"PASS", "NOT_APPLICABLE"}]
pipeline.state["audit_waivers"] = waived
if blocked:
pipeline.state["status"] = "BLOCKED"
@@ -231,6 +227,95 @@ def enforce_audit_gates(pipeline: Pipeline, audit_path: Path, waivers: dict[str,
return True
def preflight_waiver_targets(
args: argparse.Namespace,
source_report: dict[str, Any],
audit_report: dict[str, Any],
scope_manifest: Path,
waivers: dict[str, str],
) -> list[dict[str, Any]]:
"""Return invalid waiver checks before overlays/model builds begin.
The orchestrator knows every check that can legitimately be WARN/SKIP by
this point. Browser/offline checks generated by this pipeline are expected
to PASS; the only future SKIP is an explicitly required browser report when
no served Web delivery was requested.
"""
source_gate = source_report.get("gate") or {}
checks = [
{
"name": "cad_source_report",
"status": str(source_gate.get("status", "FAIL")),
"detail": str(source_gate.get("detail", "")),
}
]
checks.extend(
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in audit_report.get("gates", [])
)
try:
scope = json.loads(scope_manifest.read_text(encoding="utf-8"))
requested = scope.get("requested", [])
raw_buildings = scope.get("buildings", [])
if not isinstance(raw_buildings, list):
raw_buildings = []
buildings = {str(item.get("id", "")): item for item in raw_buildings if isinstance(item, dict)}
for building_id in requested if isinstance(requested, list) else []:
item = buildings.get(str(building_id), {})
status = str(item.get("status", "FAIL"))
reason = str(item.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": f"scope:building:{building_id}",
"status": check_status,
"detail": reason or f"Scope building status is {status}",
}
)
if scope.get("mode") == "campus":
site = scope.get("site", {}) if isinstance(scope.get("site"), dict) else {}
status = str(site.get("status", "FAIL"))
reason = str(site.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": "scope:site",
"status": check_status,
"detail": reason or f"Campus site status is {status}",
}
)
except (OSError, json.JSONDecodeError):
# Final scope verification reports the malformed manifest. With no
# trustworthy target inventory, every scope waiver remains unused.
pass
if args.web:
checks.append({"name": "browser:smoke", "status": "PASS", "detail": "Generated browser smoke required"})
elif args.require_browser_report:
checks.append(
{
"name": "browser:smoke",
"status": "SKIP",
"detail": "Required browser report without a served Web delivery",
}
)
if args.offline:
checks.append(
{
"name": "offline:browser-smoke",
"status": "PASS",
"detail": "Generated offline browser smoke required",
}
)
apply_waivers(checks, waivers)
return [
check for check in checks if check.get("status") == "FAIL" and str(check.get("name", "")).startswith("waiver:")
]
def available_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as stream:
stream.bind(("127.0.0.1", 0))
@@ -426,13 +511,29 @@ def run_pipeline(args: argparse.Namespace) -> int:
print(f"GATE FAIL [source_report]: {exc}", file=sys.stderr)
return 3
source_status = str((report.get("gate") or {}).get("status", "FAIL"))
if source_status == "WARN" and "cad_source_report" not in waivers:
source_checks = [
{
"name": "cad_source_report",
"status": source_status,
"detail": str((report.get("gate") or {}).get("detail", "")),
}
]
source_waivers = {name: reason for name, reason in waivers.items() if name == "cad_source_report"}
apply_waivers(source_checks, source_waivers)
if source_checks[0]["status"] == "WARN":
print(
"GATE BLOCKED [cad_source_report]: partial source report requires "
"--waiver 'cad_source_report=<user-approved reason>'",
file=sys.stderr,
)
return 3
invalid_source_waiver = next((check for check in source_checks if check["status"] == "FAIL"), None)
if invalid_source_waiver:
print(
f"GATE FAIL [{invalid_source_waiver['name']}]: {invalid_source_waiver['detail']}",
file=sys.stderr,
)
return 3
out_dir = Path(args.out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
pipeline = Pipeline(
@@ -482,6 +583,15 @@ def run_pipeline(args: argparse.Namespace) -> int:
if args.frames:
audit_cmd.extend(["--frames", *args.frames])
pipeline.run("audit", audit_cmd, [audit, audit_md])
audit_report = json.loads(audit.read_text(encoding="utf-8"))
invalid_waivers = preflight_waiver_targets(args, report, audit_report, scope_manifest, waivers)
if invalid_waivers:
pipeline.state["status"] = "BLOCKED"
pipeline.state["invalid_waivers"] = invalid_waivers
pipeline.save()
for check in invalid_waivers:
print(f"GATE FAIL [{check['name']}]: {check['detail']}", file=sys.stderr)
return 3
if not enforce_audit_gates(pipeline, audit, waivers):
return 3
pipeline.run(

View File

@@ -0,0 +1,59 @@
"""Shared parsing and application rules for explicit delivery waivers."""
from __future__ import annotations
from typing import Any
WAIVABLE_STATUSES = frozenset({"WARN", "SKIP"})
def parse_waivers(values: list[str]) -> dict[str, str]:
"""Parse CHECK=REASON values and reject malformed or duplicate entries."""
waivers: dict[str, str] = {}
for value in values:
name, separator, reason = value.partition("=")
name = name.strip()
reason = reason.strip()
if not separator or not name or not reason:
raise ValueError(f"Invalid waiver {value!r}; expected CHECK=REASON")
if name in waivers:
raise ValueError(f"Duplicate waiver for {name!r}")
waivers[name] = reason
return waivers
def apply_waivers(checks: list[dict[str, Any]], waivers: dict[str, str]) -> None:
"""Apply waivers to WARN/SKIP checks and add FAIL checks for invalid targets.
Passing a namespace-specific subset lets an earlier pipeline stage reject
misspelled, unused, PASS, FAIL, or NOT_APPLICABLE targets before expensive
downstream work begins. Final verification calls the same function with the
complete waiver map, so both stages have identical semantics.
"""
by_name = {str(check.get("name", "")): check for check in checks}
for name, reason in waivers.items():
check = by_name.get(name)
if check is None:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Unused or misspelled waiver: {name}",
}
)
continue
status = str(check.get("status", "FAIL"))
if status not in WAIVABLE_STATUSES:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Waivers may only acknowledge WARN/SKIP checks; {name} is {status}",
}
)
continue
check["original_status"] = status
check["status"] = "PASS"
check["waiver_reason"] = reason
check["detail"] = f"WAIVED ({reason}): {check.get('detail', '')}"

View File

@@ -832,7 +832,9 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
"""
if not config.get("generate_caps", True):
return
buf = float(config.get("cap_buffer", 1.3))
# Ordinary facade-aligned floors need only a small tolerance. Colonnade or
# broad-overhang projects such as A208 must opt into a larger value.
buf = float(config.get("cap_buffer", 0.1))
for fk, fl in floors.items():
own_polys = fl.get("footprint", {}).get("polygons", [])
if not own_polys:
@@ -856,7 +858,14 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
polys = [] # roof_specs handles above-ground tops
else:
up_u = _shapely_union(upper)
polys = _shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05))) if up_u is not None else []
# A 0.1 m facade tolerance creates a thin evidence ring whose area
# can be below the generic 3 m² polygon-noise threshold on small
# buildings. Caps are already footprint-derived, so retain them.
polys = (
_shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05)), min_area=0.25)
if up_u is not None
else []
)
if polys:
fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys})

View File

@@ -18,6 +18,20 @@ REPORT_VERSION = 1
ROOT = Path(__file__).resolve().parent.parent
SCHEMA_DIR = ROOT / "schemas"
LEGACY_CATEGORY_STYLES = {
"walls": {"label": "墙体", "color": "#d4cbb8"},
"glazing": {"label": "玻璃/幕墙", "color": "#79b8c9"},
"roof": {"label": "屋顶/屋盖", "color": "#b8ae98"},
"columns": {"label": "柱", "color": "#f58a1f"},
"beams": {"label": "梁/结构", "color": "#1f66c2"},
"railings": {"label": "栏杆/扶手", "color": "#6f746d"},
"doors": {"label": "门/开启线", "color": "#8a6a45"},
"detail_lines": {"label": "平面细节", "color": "#8c9088"},
"floor_lines": {"label": "楼面线", "color": "#18a058"},
"grid": {"label": "轴网", "color": "#20242a"},
"slab": {"label": "楼板", "color": "#c8ccc2"},
}
class ValidationFailure(ValueError):
"""Raised when a config or generated artifact violates the contract."""
@@ -87,6 +101,26 @@ def normalize_spec(spec: dict[str, Any]) -> dict[str, Any]:
units.setdefault("scale_to_meters", scale)
units.setdefault("origin_source", [0.0, 0.0])
normalized["units"] = units
raw_categories = normalized.get("categories", {})
categories = copy.deepcopy(raw_categories) if isinstance(raw_categories, dict) else {}
configured_categories = source["config"].get("categories", {})
used_categories = {
category
for floor in normalized.get("floors", {}).values()
for category, segments in floor.get("segments", {}).items()
if segments
}
if source["config"].get("use_footprint_slabs"):
used_categories.add("slab")
for category in sorted(used_categories):
if category in categories:
continue
style = dict(LEGACY_CATEGORY_STYLES.get(category, {"label": category, "color": "#8c9088"}))
override = configured_categories.get(category, {}) if isinstance(configured_categories, dict) else {}
if isinstance(override, dict):
style.update({key: override[key] for key in ("label", "color") if key in override})
categories[category] = style
normalized["categories"] = categories
for floor in normalized.get("floors", {}).values():
floor.setdefault("source_file", "unknown")
for category, segments in floor.get("segments", {}).items():

View File

@@ -406,9 +406,9 @@ def setback_cap_polys(spec, fk, fl, own_polys):
continue
upper.extend(ot.get("footprint", {}).get("polygons", []))
own_u = _shapely_union(own_polys)
# 1.3 suits colonnade buildings (A208); ordinary facades want ~0.1 or the
# cap ring reads as a slab overhanging every floor. Config: cap_buffer.
buf = float(cfg.get("cap_buffer", 1.3))
# Ordinary facades default to a small tolerance. Colonnade buildings such
# as A208 must explicitly set cap_buffer around 1.3 m.
buf = float(cfg.get("cap_buffer", 0.1))
if not upper:
# top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking)
if grp == "BASE" and own_u is not None:
@@ -421,7 +421,9 @@ def setback_cap_polys(spec, fk, fl, own_polys):
ring = own_u.buffer(buf).difference(up_u.buffer(0.05))
except Exception:
return []
return _shapely_to_polys(ring, min_area=3.0)
# Keep thin 0.1 m default cap rings on small buildings; this geometry is
# already constrained by validated floor footprints, not raw CAD noise.
return _shapely_to_polys(ring, min_area=0.25)
def floor_group(fk, cfg=None):

View File

@@ -16,6 +16,7 @@ from pathlib import Path
from typing import Any
import showcase_schema
from delivery_waivers import apply_waivers, parse_waivers
def sha256(path: Path) -> str:
@@ -30,48 +31,6 @@ def add_check(checks: list[dict[str, Any]], name: str, status: str, detail: str,
checks.append({"name": name, "status": status, "detail": detail, **data})
def parse_waivers(values: list[str]) -> dict[str, str]:
"""Parse explicit CHECK=REASON waivers.
Waivers are deliberately verbose: an Agent cannot silently turn WARN/SKIP
into PASS, and a misspelled or unused waiver becomes a hard failure.
"""
waivers: dict[str, str] = {}
for value in values:
name, separator, reason = value.partition("=")
name = name.strip()
reason = reason.strip()
if not separator or not name or not reason:
raise ValueError(f"Invalid waiver {value!r}; expected CHECK=REASON")
if name in waivers:
raise ValueError(f"Duplicate waiver for {name!r}")
waivers[name] = reason
return waivers
def apply_waivers(checks: list[dict[str, Any]], waivers: dict[str, str]) -> None:
used: set[str] = set()
for check in checks:
name = str(check["name"])
if name not in waivers:
continue
used.add(name)
if check["status"] not in {"WARN", "SKIP"}:
add_check(
checks,
f"waiver:{name}",
"FAIL",
f"Waivers may only acknowledge WARN/SKIP checks; {name} is {check['status']}",
)
continue
check["original_status"] = check["status"]
check["status"] = "PASS"
check["waiver_reason"] = waivers[name]
check["detail"] = f"WAIVED ({waivers[name]}): {check['detail']}"
for name in sorted(set(waivers) - used):
add_check(checks, f"waiver:{name}", "FAIL", f"Unused or misspelled waiver: {name}")
def inspect_glb(path: Path, budget_mb: float, checks: list[dict[str, Any]]) -> dict[str, Any] | None:
if not path.exists() or path.stat().st_size == 0:
add_check(checks, f"glb:{path.name}", "FAIL", f"Missing or empty GLB: {path}")
@@ -210,11 +169,11 @@ def inspect_web(web_dir: Path, checks: list[dict[str, Any]]) -> None:
)
try:
metadata = json.loads((web_dir / "model_metadata.json").read_text(encoding="utf-8"))
missing_variants = [
item.get("file", "?")
for item in metadata.get("model_variants", [])
if not (web_dir / item.get("file", "")).exists()
]
missing_variants = []
for item in metadata.get("model_variants", []):
file_name = item.get("file")
if not isinstance(file_name, str) or not file_name or not (web_dir / file_name).is_file():
missing_variants.append(file_name or "<missing file>")
add_check(
checks,
"web:variants",

View File

@@ -26,6 +26,7 @@ from __future__ import annotations
import argparse
import base64
import gzip
import html as html_lib
import json
import struct
from pathlib import Path
@@ -66,10 +67,15 @@ def glb_extensions(path: Path) -> set[str]:
return set(document.get("extensionsUsed", []))
def script_json(value) -> str:
"""Serialize JSON for an inline script without allowing an early script close."""
return json.dumps(value, ensure_ascii=False).replace("</", "<\\/")
MAIN_JS = r"""
(async function(){
const $load = document.getElementById('load');
const fail = m => { $load.style.display='flex'; $load.innerHTML = '<div style="max-width:520px;text-align:center">加载失败:'+m+'</div>'; };
const fail = m => { $load.style.display='flex'; $load.textContent = '加载失败:'+m; };
window.addEventListener('error', e => fail(e.message));
window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason));
try {
@@ -161,8 +167,9 @@ MAIN_JS = r"""
head.appendChild(document.createTextNode(gname)); head.appendChild(btn); tg.appendChild(head);
GROUPS[gname].forEach(f => {
const l = document.createElement('label');
l.innerHTML = '<input id="cb_'+f[0]+'" type="checkbox" checked> '+f[0]+' '+f[1];
l.querySelector('input').onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
const input = document.createElement('input'); input.id='cb_'+f[0]; input.type='checkbox'; input.checked=true;
input.onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+f[0]+' '+f[1]));
tg.appendChild(l);
});
}
@@ -173,8 +180,9 @@ MAIN_JS = r"""
for (const k in CATS) {
if (!used[k] || k==='trees') continue;
const l = document.createElement('label');
l.innerHTML = '<input type="checkbox" checked> '+CATS[k];
l.querySelector('input').onchange = e => { state.ct[k]=e.target.checked; apply(); };
const input = document.createElement('input'); input.type='checkbox'; input.checked=true;
input.onchange = e => { state.ct[k]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+CATS[k]));
tg.appendChild(l);
}
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info');
@@ -191,7 +199,10 @@ MAIN_JS = r"""
hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55;
const p = (hi.name||'').split('__');
let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; });
info.innerHTML = '<b>'+p[0]+'</b> '+fname+'<br>构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name;
info.replaceChildren();
const strong=document.createElement('b'); strong.textContent=p[0]; info.appendChild(strong);
info.appendChild(document.createTextNode(' '+fname)); info.appendChild(document.createElement('br'));
info.appendChild(document.createTextNode('构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name));
info.style.display = 'block';
invalidate();
});
@@ -261,21 +272,23 @@ def main() -> int:
for s in spec.get("floors", {}).get("TREES", {}).get("segments", {}).get("trees", [])
]
cats = {k: v.get("label", k) for k, v in spec.get("categories", {}).items()}
title = args.title or spec.get("project", {}).get("name", "CAD 建筑模型")
title = str(args.title or spec.get("project", {}).get("name", "CAD 建筑模型"))
escaped_title = html_lib.escape(title, quote=True)
escaped_subtitle = html_lib.escape(str(args.subtitle), quote=True)
main_js = (
MAIN_JS.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False))
.replace("__CATS__", json.dumps(cats, ensure_ascii=False))
.replace("__TREES__", json.dumps(trees))
MAIN_JS.replace("__GROUPS__", script_json(groups))
.replace("__CATS__", script_json(cats))
.replace("__TREES__", script_json(trees))
)
sc_close = "</scr" + "ipt>"
html = (
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
f"<title>{title} · 3D 查看器(离线版)</title>"
f"<title>{escaped_title} · 3D 查看器(离线版)</title>"
'<meta name="viewport" content="width=device-width, initial-scale=1">'
f"<style>{CSS}</style></head><body>"
'<div id="load">正在初始化…</div>'
f'<div id="panel"><h1>{title}</h1><div class="sub">{args.subtitle}</div><div id="tg"></div></div>'
f'<div id="panel"><h1>{escaped_title}</h1><div class="sub">{escaped_subtitle}</div><div id="tg"></div></div>'
'<div id="info"></div>'
'<div id="hint">拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性</div>'
+ "".join(