From c12d1d57cb74f529bd2b689e6f2e65b814feeae5 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Sat, 11 Jul 2026 15:26:43 +0800 Subject: [PATCH] fix: close remaining CAD delivery review gaps --- references/optimization_notes.md | 2 +- references/pipeline.md | 2 +- scripts/cad_showcase.py | 162 ++++++++++++++++++++++++++----- scripts/delivery_waivers.py | 59 +++++++++++ scripts/derive_showcase_spec.py | 13 ++- scripts/showcase_schema.py | 34 +++++++ scripts/spec_to_glb.py | 10 +- scripts/verify_delivery.py | 53 ++-------- scripts/write_offline_viewer.py | 37 ++++--- tests/test_contracts.py | 132 +++++++++++++++++++++++++ tests/test_delivery.py | 53 ++++++++++ 11 files changed, 464 insertions(+), 93 deletions(-) create mode 100644 scripts/delivery_waivers.py diff --git a/references/optimization_notes.md b/references/optimization_notes.md index 16c53d4..bce8254 100644 --- a/references/optimization_notes.md +++ b/references/optimization_notes.md @@ -78,7 +78,7 @@ CAD 把幕墙画成稀疏分格板(实测 8F:1.42m 板 / 每 4.5m 一块 / ### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好) 现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**: -- 地上退台层:`cap = 本层footprint(外扩~1.3m) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。外扩是为了盖住凹包络切掉的外圈柱廊柱。 +- 地上退台层:`cap = 本层footprint(外扩cap_buffer) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。普通立面默认 `0.1m`;A208 的外圈柱廊有图纸佐证,才显式使用约 `1.3m`。 - **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。 - 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。 diff --git a/references/pipeline.md b/references/pipeline.md index df508af..fec77fc 100644 --- a/references/pipeline.md +++ b/references/pipeline.md @@ -211,7 +211,7 @@ Review `building_spec.json` before rendering: - Segment counts are not dominated by dimensions/hatches/annotations. - Footprint polygons exist when slabs/roofs are meant to follow CAD floor plates. - `default_disabled_categories` does not hide `slab` for presentation/digital-twin views. -- Generated cap edges do not protrude as slab fins. The historical `cap_buffer=1.3m` value fits colonnade/overhang cases; use about `0.1m` for ordinary facade-aligned floors, then confirm front/side views. +- Generated cap edges do not protrude as slab fins. `cap_buffer` defaults to `0.1m` for ordinary facade-aligned floors. Set it explicitly around `1.3m` only for evidenced colonnade/overhang cases such as A208, then confirm front/side views. ## 6. Agent Audit and Overlay Review diff --git a/scripts/cad_showcase.py b/scripts/cad_showcase.py index ffa1eba..6d66883 100644 --- a/scripts/cad_showcase.py +++ b/scripts/cad_showcase.py @@ -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='", 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( diff --git a/scripts/delivery_waivers.py b/scripts/delivery_waivers.py new file mode 100644 index 0000000..aba6ed0 --- /dev/null +++ b/scripts/delivery_waivers.py @@ -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', '')}" diff --git a/scripts/derive_showcase_spec.py b/scripts/derive_showcase_spec.py index ed19141..97d06e7 100755 --- a/scripts/derive_showcase_spec.py +++ b/scripts/derive_showcase_spec.py @@ -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}) diff --git a/scripts/showcase_schema.py b/scripts/showcase_schema.py index dd9f2fd..99fbfd9 100644 --- a/scripts/showcase_schema.py +++ b/scripts/showcase_schema.py @@ -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(): diff --git a/scripts/spec_to_glb.py b/scripts/spec_to_glb.py index 3adc2d1..18e3557 100644 --- a/scripts/spec_to_glb.py +++ b/scripts/spec_to_glb.py @@ -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): diff --git a/scripts/verify_delivery.py b/scripts/verify_delivery.py index 7c73ff4..1bd7c95 100644 --- a/scripts/verify_delivery.py +++ b/scripts/verify_delivery.py @@ -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 "") add_check( checks, "web:variants", diff --git a/scripts/write_offline_viewer.py b/scripts/write_offline_viewer.py index 40c0413..1c81ba9 100644 --- a/scripts/write_offline_viewer.py +++ b/scripts/write_offline_viewer.py @@ -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(" { $load.style.display='flex'; $load.innerHTML = '
加载失败:'+m+'
'; }; + 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 = ' '+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 = ' '+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 = ''+p[0]+' '+fname+'
构件:'+(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 = "" html = ( '' - f"{title} · 3D 查看器(离线版)" + f"{escaped_title} · 3D 查看器(离线版)" '' f"" '
正在初始化…
' - f'

{title}

{args.subtitle}
' + f'

{escaped_title}

{escaped_subtitle}
' '
' '
拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性
' + "".join( diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 60218cd..8276f7c 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -14,6 +14,8 @@ sys.path.insert(0, str(ROOT / "scripts")) import audit_showcase_extraction # noqa: E402 import build_blender_showcase # noqa: E402 import cad_showcase # noqa: E402 +import delivery_waivers # noqa: E402 +import derive_showcase_spec # noqa: E402 import showcase_schema # noqa: E402 import spec_to_glb # noqa: E402 @@ -165,6 +167,122 @@ def test_all_derive_geometry_loss_warnings_are_forbidden() -> None: } +def test_waivers_share_one_implementation_and_reject_not_applicable_targets(tmp_path: Path) -> None: + import verify_delivery + + assert cad_showcase.parse_waivers is delivery_waivers.parse_waivers + assert verify_delivery.parse_waivers is delivery_waivers.parse_waivers + audit = tmp_path / "audit.json" + audit.write_text( + json.dumps( + { + "gates": [ + { + "name": "frame_ledger", + "status": "NOT_APPLICABLE", + "detail": "No frame report supplied", + } + ] + } + ), + encoding="utf-8", + ) + pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False) + assert not cad_showcase.enforce_audit_gates( + pipeline, + audit, + {"audit:frame_ledger": "pre-approved in case this gate becomes armed"}, + ) + state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8")) + blocked = state["blocked_gates"] + assert blocked[0]["name"] == "waiver:audit:frame_ledger" + assert "NOT_APPLICABLE" in blocked[0]["detail"] + + +def test_audit_waiver_typo_fails_before_downstream_work(tmp_path: Path) -> None: + audit = tmp_path / "audit.json" + audit.write_text( + json.dumps({"gates": [{"name": "floors_aligned", "status": "PASS", "detail": "aligned"}]}), + encoding="utf-8", + ) + pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False) + assert not cad_showcase.enforce_audit_gates( + pipeline, + audit, + {"audit:floors_aligend": "typo must not survive to final verification"}, + ) + state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8")) + assert state["blocked_gates"][0]["name"] == "waiver:audit:floors_aligend" + + +def test_waiver_preflight_rejects_misspelled_namespace_and_extra_future_waiver(tmp_path: Path) -> None: + scope = tmp_path / "scope.json" + scope.write_text( + json.dumps( + { + "scope_version": 1, + "mode": "single", + "requested": ["main"], + "buildings": [{"id": "main", "status": "PASS", "artifacts": ["future.glb"]}], + } + ), + encoding="utf-8", + ) + args = cad_showcase.parser().parse_args( + [ + "run", + "--dxf-dir", + str(tmp_path), + "--config", + str(tmp_path / "config.json"), + "--source-report", + str(tmp_path / "source.json"), + "--out-dir", + str(tmp_path / "out"), + "--scope-manifest", + str(scope), + "--web", + ] + ) + invalid = cad_showcase.preflight_waiver_targets( + args, + {"gate": {"status": "PASS"}}, + {"gates": [{"name": "floors_aligned", "status": "WARN", "detail": "needs evidence"}]}, + scope, + { + "audti:floors_aligned": "misspelled namespace", + "browser:smoke": "cannot pre-waive a generated PASS check", + }, + ) + assert {check["name"] for check in invalid} == { + "waiver:audti:floors_aligned", + "waiver:browser:smoke", + } + + +def test_default_cap_buffer_is_small_and_large_overhang_is_explicit() -> None: + pytest.importorskip("shapely") + base_floor = { + "name": "一层", + "z": 0.0, + "height": 3.0, + "bounds": [0.0, 0.0, 10.0, 10.0], + "source_file": "fixture.dxf", + "segments": {}, + "footprint": {"polygons": [[[0, 0], [10, 0], [10, 10], [0, 10]]]}, + } + upper_floor = {**base_floor, "name": "二层", "z": 3.0} + floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))} + derive_showcase_spec.compute_caps(floors, {}) + default_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon) + assert default_max_x == pytest.approx(10.1) + + floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))} + derive_showcase_spec.compute_caps(floors, {"cap_buffer": 1.3}) + colonnade_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon) + assert colonnade_max_x == pytest.approx(11.3) + + def test_pipeline_fails_on_derive_geometry_loss_warning(tmp_path: Path) -> None: pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False) command = [ @@ -265,6 +383,20 @@ def test_spec_schema_and_backend_group_contract() -> None: assert build_blender_showcase.floor_group("TOWER_A_F3", config) == "A" +def test_normalize_spec_backfills_categories_used_by_legacy_segments() -> None: + legacy = minimal_spec() + legacy.pop("schema_version") + legacy.pop("categories") + legacy["floors"]["F1"]["segments"]["legacy_custom"] = [ + {"start": [0, 0], "end": [0, 1], "width": 0.1, "layer": "OLD", "source_type": "LINE"} + ] + normalized = showcase_schema.normalize_spec(legacy) + assert normalized["categories"]["walls"] == {"label": "墙体", "color": "#d4cbb8"} + assert normalized["categories"]["slab"] == {"label": "楼板", "color": "#c8ccc2"} + assert normalized["categories"]["legacy_custom"] == {"label": "legacy_custom", "color": "#8c9088"} + showcase_schema.validate_spec(normalized) + + def test_spec_rejects_segment_category_without_metadata() -> None: spec = minimal_spec() spec["floors"]["F1"]["segments"]["unregistered"] = [ diff --git a/tests/test_delivery.py b/tests/test_delivery.py index 4ddad27..c9957ee 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -213,6 +213,59 @@ def test_offline_viewer_without_real_browser_report_is_blocked(tmp_path: Path) - assert any(item["name"] == "offline:browser-smoke" and item["status"] == "SKIP" for item in report["checks"]) +def test_offline_viewer_escapes_html_and_inline_script_data(tmp_path: Path) -> None: + spec, glb, _metadata = build_fixture(tmp_path) + document = json.loads(spec.read_text(encoding="utf-8")) + document["project"]["name"] = '' + document["floors"]["F1"]["name"] = '首层' + document["categories"]["walls"]["label"] = "墙<&>" + spec.write_text(json.dumps(document), encoding="utf-8") + offline = tmp_path / "viewer.html" + proc = run( + sys.executable, + "scripts/write_offline_viewer.py", + "--spec", + str(spec), + "--glb", + str(glb), + "--out", + str(offline), + "--subtitle", + "", + ) + assert proc.returncode == 0, proc.stderr + text = offline.read_text(encoding="utf-8") + assert "<Tower & Co></script>" in text + assert "<unsafe & subtitle>" in text + assert '首层<\\/script>' not in text + + +def test_web_variant_entry_requires_a_nonempty_file(tmp_path: Path) -> None: + import verify_delivery + + web = tmp_path / "web" + for relative in ( + "index.html", + "app.js", + "styles.css", + "model.glb", + "node_modules/three/build/three.module.js", + "node_modules/lucide/dist/umd/lucide.js", + ): + target = web / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text( + "window.__renders; invalidate(); DRACOLoader; restoreStateFromHash; switchVariant", encoding="utf-8" + ) + (web / "model_metadata.json").write_text(json.dumps({"model_variants": [{"key": "standard", "file": ""}]})) + checks: list[dict] = [] + verify_delivery.inspect_web(web, checks) + variant_check = next(item for item in checks if item["name"] == "web:variants") + assert variant_check["status"] == "FAIL" + assert "" in variant_check["detail"] + + def test_strict_delivery_requires_a_render(tmp_path: Path) -> None: spec, glb, _metadata = build_fixture(tmp_path) source_report = source_report_fixture(tmp_path)