diff --git a/README.md b/README.md index 9e2659b..f9b72ff 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ tools/cad-building-showcase/SKILL.md 并遵守其中 One-Shot Definition of Done ```bash python3 scripts/cad_showcase.py inspect --input --work work/ --output outputs//read_report -python3 scripts/cad_showcase.py run --dxf-dir --config --source-report --out-dir outputs/ --name --backend trimesh --web --offline --resume +python3 scripts/cad_showcase.py run --dxf-dir --config --source-report --scope-manifest work//scope_manifest.json --out-dir outputs/ --name --backend trimesh --web --offline --resume ``` 核心链路: @@ -60,7 +60,7 @@ detect_sheet_frames.py 图框检测(图签块定框、网格投票/墙剖面 derive_showcase_spec.py 按 config 提取 building_spec.json(分簇 footprint/楼板/顶盖) audit_showcase_extraction.py 硬门禁审计(楼层对齐+跨层基准、幕墙、框收支表、 面积/层数互证…),FAIL 即退出码 3 -spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer +spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer(使用 raw GLB) register_site_outlines.py / massing_from_outline.py / assemble_campus.py 总平面配准(点-边ICP)、无图纸楼体量、厂区装配 ``` @@ -71,7 +71,7 @@ register_site_outlines.py / massing_from_outline.py / assemble_campus.py - `schemas/` extraction config、building spec、variants manifest 的版本化 JSON Schema - `tests/` 契约/交付测试 + 合成 DXF 全链路回归 - `references/` 当前运行规范;历史复盘移到 `docs/history/`,不再作为 Agent 运行上下文 -- `assets/` Web 模板与离线 viewer 内联库 +- `assets/` Web 模板与离线 viewer 内联库;离线交付必须通过真实 `file://` 浏览器 smoke `work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。 diff --git a/SKILL.md b/SKILL.md index 0f7a6cc..f49484c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -57,16 +57,19 @@ Read only the branches needed for the current task: 4. Extract, audit, and review overlays. - Prefer the resumable entry point after the config is approved: - `python3 scripts/cad_showcase.py run --dxf-dir --config --source-report --out-dir --name --frames --backend trimesh`. + `python3 scripts/cad_showcase.py run --dxf-dir --config --source-report --scope-manifest --out-dir --name --frames --backend trimesh`. - Use `--backend blender` when `.blend` and Blender preview are required. - Never pass `--no-strict-gates` to proceed toward delivery. - Treat audit `WARN` and `SKIP` as `BLOCKED`, not success. Continue only with an explicit `--waiver 'audit:='`; retain it in final evidence. + - A waiver must be explicitly approved by the user. The Agent must not invent one, and must never use one when the user says “no waivers/不要豁免”. + - Search all source sheets for economic-index tables, storey labels, and elevation ladders before declaring area/storey evidence absent. If a typical plan represents repeated floors, instantiate the source-supported repetitions; a final full-building model may not jump from F2 directly to F16. - Open the SVG overlays. Iterate if red/unclassified geometry forms walls, glazing, columns, beams, grids, stairs, slabs, roofs, or whole building wings. 5. Verify actual deliverables. - Require `verify_showcase.py --strict` and `verify_delivery.py` to pass. - Inspect at least one iso/front/side/plan render personally. - For served Web output, use `cad_showcase.py run --web`; it Draco-compresses Trimesh GLBs, starts a temporary local server, runs `web_smoke_test.mjs` at real 1440×900 and 390×844 viewports, and feeds the report to final verification automatically. + - For `--offline`, the pipeline embeds the retained uncompressed `standard.raw.glb`, opens `viewer.html` through a real `file://` Chromium page, and records `offline_browser_smoke_report.json`. Never embed a Draco GLB in the r147 offline viewer unless a matching offline decoder is bundled and tested. - Confirm idle `window.__renders` does not grow, GLBs decode, variants exist, controls work, and console errors are zero. 6. Report confidence and limits. @@ -81,13 +84,16 @@ Do not hand over a model unless every applicable item has evidence: 2. Config and spec pass their versioned JSON Schemas. 3. Every configured source exists, every floor key is unique, every floor is nonempty, and `floor_order` has no gaps/ghosts. 4. Multi-frame projects pass `frame_ledger`; every detected plan frame is used or appears in `discarded_frames` with a reason. -5. Audit exits 0 and every gate is `PASS`; `WARN`/`SKIP` block delivery unless a named, reasoned waiver is recorded in evidence. -6. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`. -7. Campus output has a `scope_manifest.json` containing every requested building. Every building and the site is `PASS`, with existing artifacts; a `BLOCKED` entry means the campus request is not complete. -8. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image. -9. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render. -10. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template. -11. After any script/schema/template change, run: +5. A required single-building/campus `scope_manifest.json` matches the requested scope and its artifacts exist. +6. Numbered floors are vertically continuous; representative typical-floor drawings are repeated into source-supported storeys instead of leaving large empty gaps. +7. Audit exits 0 and every gate is `PASS`; `WARN`/`SKIP` block delivery unless a named, user-approved waiver is recorded in evidence. +8. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`. +9. Campus output contains every requested building and the site as `PASS`, with existing artifacts; a `BLOCKED` entry means the campus request is not complete. +10. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image. +11. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render. +12. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template. +13. Offline delivery includes a passing `file://` browser smoke report proving the readiness marker, canvas, and first render; an embedded payload check alone is insufficient. +14. After any script/schema/template change, run: - `pytest tests/test_contracts.py tests/test_delivery.py` - `python3 tests/test_extraction_pipeline.py` - `ruff format --check scripts tests && ruff check scripts tests` diff --git a/package.json b/package.json index ea8ea2d..5756bac 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,8 @@ { "scripts": { - "check:js": "node --check assets/web-showcase-template/app.js && node --check scripts/dwg_dump_json.mjs && node --check scripts/web_smoke_test.mjs && node --check tools/compress.mjs", - "smoke:web": "node scripts/web_smoke_test.mjs" + "check:js": "node --check assets/web-showcase-template/app.js && node --check scripts/dwg_dump_json.mjs && node --check scripts/web_smoke_test.mjs && node --check scripts/offline_viewer_smoke.mjs && node --check tools/compress.mjs", + "smoke:web": "node scripts/web_smoke_test.mjs", + "smoke:offline": "node scripts/offline_viewer_smoke.mjs" }, "devDependencies": { "playwright": "^1.52.0" diff --git a/references/web_delivery.md b/references/web_delivery.md index d12ddbd..aeb60cb 100644 --- a/references/web_delivery.md +++ b/references/web_delivery.md @@ -18,7 +18,7 @@ Deliver three variants for Web/digital-twin presentation: Generate them with `build_showcase_variants.py` or `cad_showcase.py run`. Validate `variants_manifest.json` and every variant spec. Keep `source_file==site` floors intact across variants. -The Trimesh branch of `cad_showcase.py run` writes a retained `.raw.glb` and then runs `tools/compress.mjs` (weld, dedup, prune, Draco) to produce each delivered `.glb`. The Blender branch uses Blender's Draco export. `verify_showcase.py --strict` must see `draco=True` and every delivered variant within the size budget. +Both backends retain a decoder-free `.raw.glb` for offline embedding. The Trimesh branch then runs `tools/compress.mjs` (weld, dedup, prune, Draco), while the Blender branch performs a second Blender Draco export for each delivered `.glb`. `verify_showcase.py --strict` must see `draco=True` and every delivered variant within the size budget. Both GLB backends consume versioned `building_spec.json`. They must preserve `__` names and glTF Y-up. `floor.caps` is canonical; exporters must not independently infer different cap groups. @@ -32,7 +32,9 @@ Require idle `window.__renders` growth of zero after damping stops. ## Offline Viewer -Use `write_offline_viewer.py` only for double-click/no-server delivery. It embeds vendored Three r147, pako, and a gzip-compressed GLB. Run `verify_delivery.py --offline-viewer` to decode and verify the embedded payload. +Use `write_offline_viewer.py` only for double-click/no-server delivery. It embeds vendored Three r147, pako, and a gzip-compressed **uncompressed** GLB. The Trimesh pipeline therefore uses retained `standard.raw.glb`; passing a Draco GLB is a hard error because this offline bundle intentionally has no Draco decoder. + +`cad_showcase.py run --offline` automatically opens the result via `file://` in Chromium and writes `offline_browser_smoke_report.json` plus a screenshot. For a manual/custom delivery, run `offline_viewer_smoke.mjs` and pass its report to `verify_delivery.py --offline-browser-report`. Decoding the base64 payload is not proof that GLTFLoader can render it. The offline viewer intentionally follows an older Three API. Keep its vendored library versions/checksums documented when updating them; do not copy modern template code blindly into r147. @@ -62,10 +64,11 @@ python3 scripts/verify_delivery.py \ --variants-manifest outputs//delivery/variants_manifest.json \ --web-dir outputs//web \ --offline-viewer outputs//viewer.html \ + --offline-browser-report outputs//offline_browser_smoke_report.json \ --render outputs//verify_previews.png outputs//iso.png \ --browser-report outputs//browser_smoke_report.json \ --require-browser-report \ --evidence-out outputs//evidence_manifest.json ``` -The verifier checks schema versions, audit gates, optional campus scope, GLB headers/mesh structure/naming/budgets, render dimensions/nonblank variance, Web assets/placeholders/features/variants, offline payload, and browser report. Only overall `PASS` is complete. `WARN`/`SKIP` produce overall `BLOCKED` unless the exact check has an explicit `--waiver 'CHECK=REASON'`; `FAIL` cannot be waived. +The verifier checks schema versions, audit gates, optional campus scope, GLB headers/mesh structure/naming/budgets, render dimensions/nonblank variance, Web assets/placeholders/features/variants, offline payload, offline `file://` browser load, and served-Web browser report. Only overall `PASS` is complete. `WARN`/`SKIP` produce overall `BLOCKED` unless the exact check has an explicit `--waiver 'CHECK=REASON'`; `FAIL` cannot be waived. diff --git a/scripts/audit_showcase_extraction.py b/scripts/audit_showcase_extraction.py index 1ec98c3..95a77f5 100755 --- a/scripts/audit_showcase_extraction.py +++ b/scripts/audit_showcase_extraction.py @@ -568,6 +568,7 @@ def evaluate_gates( } ) gates.append(frame_ledger_gate(config, frames)) + gates.append(vertical_storey_continuity_gate(spec)) gates.append(declared_area_gate(spec, config)) gates.append(storey_count_gate(spec, config)) return gates @@ -681,6 +682,60 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str } +def vertical_storey_continuity_gate(spec: dict[str, Any]) -> dict[str, Any]: + """A final full-building model may not jump from F2 directly to F16. + + Representative typical-floor drawings are source evidence, not permission + to leave the repeated storeys absent from the delivered building. The + repeated floors must be instantiated and labelled as derived repetitions. + """ + import re as _re + + numbered: list[tuple[int, str, dict[str, Any]]] = [] + for key, floor in spec.get("floors", {}).items(): + match = _re.fullmatch(r"F(\d+)", str(key)) + if match: + numbered.append((int(match.group(1)), str(key), floor)) + numbered.sort() + if len(numbered) < 2: + return { + "name": "vertical_storey_continuity", + "status": "PASS", + "detail": f"{len(numbered)} numbered storey; no internal continuity gap to test.", + } + + missing: list[str] = [] + z_gaps: list[str] = [] + for (left_no, left_key, left), (right_no, right_key, right) in zip(numbered, numbered[1:]): + if right_no != left_no + 1: + missing.append(f"{left_key}->{right_key}") + continue + left_z = float(left.get("z", 0.0)) + right_z = float(right.get("z", 0.0)) + nominal = max(float(left.get("height", 0.0)), float(right.get("height", 0.0)), 1.0) + if right_z - left_z > max(8.0, nominal * 2.0): + z_gaps.append(f"{left_key}->{right_key}={round(right_z - left_z, 2)}m") + if missing or z_gaps: + parts = [] + if missing: + parts.append("missing numbered ranges " + ", ".join(missing)) + if z_gaps: + parts.append("unexplained elevation gaps " + ", ".join(z_gaps)) + return { + "name": "vertical_storey_continuity", + "status": "FAIL", + "detail": ( + "; ".join(parts) + + ". Instantiate source-supported repeated typical floors; do not deliver separated floor islands." + ), + } + return { + "name": "vertical_storey_continuity", + "status": "PASS", + "detail": f"Numbered storeys are contiguous from {numbered[0][1]} to {numbered[-1][1]}.", + } + + def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]: """Above-ground storey count must match the declared count (总图 22F 标签 / 标高梯级数). diff --git a/scripts/build_blender_showcase.py b/scripts/build_blender_showcase.py index 422896d..7c19cc8 100755 --- a/scripts/build_blender_showcase.py +++ b/scripts/build_blender_showcase.py @@ -914,9 +914,12 @@ def main() -> int: blend_path = out_dir / f"{args.name}.blend" glb_path = out_dir / f"{args.name}.glb" + raw_glb_path = out_dir / f"{args.name}.raw.glb" png_path = out_dir / f"{args.name}.png" metadata_path = out_dir / "model_metadata.json" bpy.ops.wm.save_as_mainfile(filepath=str(blend_path)) + # Retain a decoder-free GLB for the self-contained r147 offline viewer. + bpy.ops.export_scene.gltf(filepath=str(raw_glb_path), export_format="GLB") # Draco compression keeps the Web GLB lightweight (typically -85~92% size). # The Web template registers a DRACOLoader to decode it; keep both in sync. bpy.ops.export_scene.gltf( @@ -939,6 +942,7 @@ def main() -> int: { "blend": str(blend_path), "glb": str(glb_path), + "raw_glb": str(raw_glb_path), "png": str(png_path), "metadata": str(metadata_path), "objects": len(bpy.data.objects), diff --git a/scripts/cad_showcase.py b/scripts/cad_showcase.py index 72c7700..90a72c0 100644 --- a/scripts/cad_showcase.py +++ b/scripts/cad_showcase.py @@ -254,6 +254,24 @@ def run_browser_smoke(pipeline: Pipeline, web_dir: Path, report: Path, screensho server.wait(timeout=5) +def run_offline_browser_smoke(pipeline: Pipeline, viewer: Path, report: Path, screenshot: Path) -> None: + """Open the single-file viewer through file:// and prove that its model renders.""" + pipeline.run( + "offline_browser_smoke", + [ + "node", + str(SCRIPTS / "offline_viewer_smoke.mjs"), + "--viewer", + str(viewer), + "--out", + str(report), + "--screenshot", + str(screenshot), + ], + [report, screenshot], + ) + + def doctor() -> int: modules = ["ezdxf", "jsonschema", "numpy", "scipy", "shapely", "trimesh", "matplotlib", "PIL", "pygltflib"] checks = [] @@ -457,7 +475,11 @@ def run_pipeline(args: argparse.Namespace) -> int: standard = bundle / "variants" / "standard" / "standard.glb" offline = out_dir / "viewer.html" + offline_browser_report = out_dir / "offline_browser_smoke_report.json" if args.offline: + offline_source = standard.with_name("standard.raw.glb") + if not offline_source.exists(): + offline_source = standard pipeline.run( "offline", python_script( @@ -465,7 +487,7 @@ def run_pipeline(args: argparse.Namespace) -> int: "--spec", str(spec), "--glb", - str(standard), + str(offline_source), "--out", str(offline), "--title", @@ -473,6 +495,23 @@ def run_pipeline(args: argparse.Namespace) -> int: ), [offline], ) + if not args.web: + pipeline.run( + "offline_node_dependencies", + ["npm", "install", "--prefix", str(ROOT), "--ignore-scripts"], + [ROOT / "node_modules" / "playwright" / "package.json"], + ) + pipeline.run( + "offline_browser_runtime", + [str(ROOT / "node_modules" / ".bin" / "playwright"), "install", "chromium"], + [], + ) + run_offline_browser_smoke( + pipeline, + offline, + offline_browser_report, + out_dir / "offline_browser_smoke.png", + ) preview = out_dir / "verify_previews.png" pipeline.run( @@ -514,7 +553,14 @@ def run_pipeline(args: argparse.Namespace) -> int: ["--web-dir", str(web_dir), "--browser-report", str(browser_report), "--require-browser-report"] ) if args.offline: - verify_cmd.extend(["--offline-viewer", str(offline)]) + verify_cmd.extend( + [ + "--offline-viewer", + str(offline), + "--offline-browser-report", + str(offline_browser_report), + ] + ) if args.require_browser_report and not args.web: verify_cmd.append("--require-browser-report") if args.scope_manifest: @@ -560,7 +606,11 @@ def parser() -> argparse.ArgumentParser: run.add_argument("--offline", action="store_true") run.add_argument("--browser-report") run.add_argument("--require-browser-report", action="store_true") - run.add_argument("--scope-manifest", help="Single-building/campus scope ledger included in final verification") + run.add_argument( + "--scope-manifest", + required=True, + help="Required single-building/campus scope ledger included in final verification", + ) run.add_argument( "--waiver", action="append", diff --git a/scripts/offline_viewer_smoke.mjs b/scripts/offline_viewer_smoke.mjs new file mode 100644 index 0000000..f806a9b --- /dev/null +++ b/scripts/offline_viewer_smoke.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +/** Prove that the self-contained offline viewer loads from file:// in Chromium. */ + +import fs from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +function arg(name, fallback = null) { + const index = process.argv.indexOf(name); + return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback; +} + +const viewer = arg("--viewer"); +const out = arg("--out", "offline_browser_smoke_report.json"); +const screenshot = arg("--screenshot", "offline_browser_smoke.png"); +if (!viewer) { + throw new Error("Usage: offline_viewer_smoke.mjs --viewer viewer.html --out report.json --screenshot smoke.png"); +} + +let chromium; +try { + ({ chromium } = await import("playwright")); +} catch (error) { + throw new Error("Missing Playwright. Install dependencies and Chromium before running this smoke test.", { + cause: error, + }); +} + +await fs.mkdir(path.dirname(out), { recursive: true }); +await fs.mkdir(path.dirname(screenshot), { recursive: true }); +const browser = await chromium.launch({ headless: true }); +const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); +const consoleErrors = []; +const pageErrors = []; +const failedRequests = []; +const checks = []; +page.on("console", (message) => { + if (message.type() === "error") consoleErrors.push(message.text()); +}); +page.on("pageerror", (error) => pageErrors.push(error.message)); +page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText || "failed"}`)); + +try { + const url = pathToFileURL(path.resolve(viewer)).href; + await page.goto(url, { waitUntil: "load", timeout: 60000 }); + await page.waitForFunction( + () => window.__offlineReady || document.getElementById("load")?.textContent?.includes("加载失败"), + null, + { timeout: 60000 }, + ); + const state = await page.evaluate(() => ({ + viewport: { width: window.innerWidth, height: window.innerHeight }, + ready: window.__offlineReady || null, + loadText: document.getElementById("load")?.textContent || "", + canvas: Boolean(document.querySelector("canvas")), + renders: window.__renders || 0, + })); + const viewportPass = state.viewport.width === 1440 && state.viewport.height === 900; + checks.push({ + name: "offline:viewport", + status: viewportPass ? "PASS" : "FAIL", + detail: `${state.viewport.width}x${state.viewport.height} expected 1440x900`, + }); + checks.push({ + name: "offline:model-ready", + status: state.ready?.meshes > 0 && !state.loadText ? "PASS" : "FAIL", + detail: state.ready ? `${state.ready.meshes} mesh(es)` : state.loadText || "readiness marker missing", + }); + checks.push({ name: "offline:canvas", status: state.canvas ? "PASS" : "FAIL" }); + checks.push({ + name: "offline:render", + status: state.renders > 0 ? "PASS" : "FAIL", + detail: `${state.renders} render(s)`, + }); + await page.screenshot({ path: screenshot, fullPage: true }); +} catch (error) { + checks.push({ name: "offline:load", status: "FAIL", detail: error.message }); + await page.screenshot({ path: screenshot, fullPage: true }).catch(() => {}); +} finally { + await page.close(); + await browser.close(); +} + +const failedChecks = checks.filter((item) => item.status === "FAIL"); +const status = failedChecks.length || consoleErrors.length || pageErrors.length || failedRequests.length ? "FAIL" : "PASS"; +const report = { + status, + detail: `${checks.length - failedChecks.length}/${checks.length} checks passed`, + viewer: path.resolve(viewer), + checks, + console_errors: consoleErrors, + page_errors: pageErrors, + failed_requests: failedRequests, +}; +await fs.writeFile(out, JSON.stringify(report, null, 2)); +process.stdout.write(`${JSON.stringify({ status, report: out })}\n`); +if (status === "FAIL") process.exitCode = 3; diff --git a/scripts/verify_delivery.py b/scripts/verify_delivery.py index a441234..e660583 100644 --- a/scripts/verify_delivery.py +++ b/scripts/verify_delivery.py @@ -201,7 +201,7 @@ def inspect_offline(path: Path, checks: list[dict[str, Any]]) -> None: add_check(checks, "offline:payload", "FAIL", f"Embedded payload decode failed: {exc}") -def inspect_browser_report(path: Path, checks: list[dict[str, Any]]) -> None: +def inspect_browser_report(path: Path, checks: list[dict[str, Any]], name: str = "browser:smoke") -> None: try: report = json.loads(path.read_text(encoding="utf-8")) passed = ( @@ -211,9 +211,9 @@ def inspect_browser_report(path: Path, checks: list[dict[str, Any]]) -> None: and not report.get("failed_requests") ) detail = report.get("detail") or json.dumps(report, ensure_ascii=False)[:500] - add_check(checks, "browser:smoke", "PASS" if passed else "FAIL", detail) + add_check(checks, name, "PASS" if passed else "FAIL", detail) except Exception as exc: - add_check(checks, "browser:smoke", "FAIL", f"Browser report invalid: {exc}") + add_check(checks, name, "FAIL", f"Browser report invalid: {exc}") def inspect_audit(path: Path, checks: list[dict[str, Any]]) -> None: @@ -350,6 +350,7 @@ def main() -> int: parser.add_argument("--variants-manifest") parser.add_argument("--web-dir") parser.add_argument("--offline-viewer") + parser.add_argument("--offline-browser-report") parser.add_argument("--render", nargs="*", default=[]) parser.add_argument("--audit") parser.add_argument("--scope-manifest") @@ -443,6 +444,15 @@ def main() -> int: inspect_scope(Path(args.scope_manifest), checks) if args.offline_viewer: inspect_offline(Path(args.offline_viewer), checks) + if args.offline_browser_report: + inspect_browser_report(Path(args.offline_browser_report), checks, "offline:browser-smoke") + else: + add_check( + checks, + "offline:browser-smoke", + "SKIP", + "Offline viewer has no real file:// browser smoke report", + ) if args.browser_report: inspect_browser_report(Path(args.browser_report), checks) elif args.web_dir or args.require_browser_report: @@ -460,6 +470,7 @@ def main() -> int: "evidence_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "status": status, + "waivers": [{"check": name, "reason": reason} for name, reason in sorted(waivers.items())], "checks": checks, "artifacts": artifacts, } diff --git a/scripts/write_offline_viewer.py b/scripts/write_offline_viewer.py index 49f852c..40c0413 100644 --- a/scripts/write_offline_viewer.py +++ b/scripts/write_offline_viewer.py @@ -27,6 +27,7 @@ import argparse import base64 import gzip import json +import struct from pathlib import Path import showcase_schema @@ -53,6 +54,18 @@ def group_of(key: str) -> str: return "主体" +def glb_extensions(path: Path) -> set[str]: + """Return extensionsUsed from the GLB JSON chunk without extra dependencies.""" + data = path.read_bytes() + if len(data) < 20 or data[:4] != b"glTF": + raise SystemExit(f"Not a valid GLB: {path}") + chunk_length, chunk_type = struct.unpack_from(" len(data): + raise SystemExit(f"GLB JSON chunk is missing or truncated: {path}") + document = json.loads(data[20 : 20 + chunk_length].decode("utf-8").rstrip("\x00 \t\r\n")) + return set(document.get("extensionsUsed", [])) + + MAIN_JS = r""" (async function(){ const $load = document.getElementById('load'); @@ -119,6 +132,7 @@ MAIN_JS = r""" } if (cat === 'trees') o.visible = false; }); + window.__offlineReady = {meshes:nodes.length}; if (TREES.length) { const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6), new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length); @@ -212,6 +226,12 @@ def main() -> int: glb_path = Path(args.glb) if not glb_path.exists() or glb_path.stat().st_size == 0: raise SystemExit(f"GLB not found or empty: {glb_path}") + extensions = glb_extensions(glb_path) + if "KHR_draco_mesh_compression" in extensions: + raise SystemExit( + "Offline single-file viewer requires an uncompressed GLB; " + f"KHR_draco_mesh_compression found in {glb_path}. Pass the matching *.raw.glb instead." + ) spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8"))) try: showcase_schema.validate_spec(spec) diff --git a/tests/test_browser_smoke.py b/tests/test_browser_smoke.py index f618074..e86bcd5 100644 --- a/tests/test_browser_smoke.py +++ b/tests/test_browser_smoke.py @@ -83,6 +83,41 @@ def test_served_viewer_in_desktop_and_mobile(tmp_path: Path) -> None: checks = {item["name"]: item for item in result["checks"]} assert checks["desktop:viewport"]["detail"] == "1440x900 expected 1440x900" assert checks["mobile:viewport"]["detail"] == "390x844 expected 390x844" + + offline = tmp_path / "viewer.html" + subprocess.run( + [ + sys.executable, + str(ROOT / "scripts" / "write_offline_viewer.py"), + "--spec", + str(spec), + "--glb", + str(glb), + "--out", + str(offline), + ], + check=True, + ) + offline_report = tmp_path / "offline_browser_report.json" + offline_screenshot = tmp_path / "offline_browser.png" + proc = subprocess.run( + [ + "node", + str(ROOT / "scripts" / "offline_viewer_smoke.mjs"), + "--viewer", + str(offline), + "--out", + str(offline_report), + "--screenshot", + str(offline_screenshot), + ], + text=True, + capture_output=True, + ) + assert proc.returncode == 0, proc.stderr + offline_result = json.loads(offline_report.read_text(encoding="utf-8")) + assert offline_result["status"] == "PASS" + assert offline_screenshot.exists() finally: server.terminate() server.wait(timeout=10) diff --git a/tests/test_contracts.py b/tests/test_contracts.py index e2c7880..9c63e49 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -12,6 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import build_blender_showcase # noqa: E402 +import audit_showcase_extraction # noqa: E402 import cad_showcase # noqa: E402 import showcase_schema # noqa: E402 import spec_to_glb # noqa: E402 @@ -54,6 +55,23 @@ def test_config_rejects_unknown_keys() -> None: showcase_schema.validate_config({"config_version": 1, "unexpected_typo": True}) +def test_vertical_storey_continuity_rejects_representative_floor_islands() -> None: + spec = minimal_spec() + spec["floors"]["F2"] = {**spec["floors"]["F1"], "name": "二层", "z": 5.0} + spec["floors"]["F16"] = {**spec["floors"]["F1"], "name": "十六层", "z": 59.6} + gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec) + assert gate["status"] == "FAIL" + assert "F2->F16" in gate["detail"] + + +def test_vertical_storey_continuity_accepts_instantiated_typical_floors() -> None: + spec = minimal_spec() + base = spec["floors"]["F1"] + spec["floors"] = {f"F{number}": {**base, "name": f"{number}层", "z": (number - 1) * 3.9} for number in range(1, 17)} + gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec) + assert gate["status"] == "PASS" + + def test_config_requires_at_least_one_drawing() -> None: with pytest.raises(showcase_schema.ValidationFailure, match="contains no drawings"): showcase_schema.validate_config({"config_version": 1}) @@ -279,6 +297,24 @@ def test_orchestrator_runs_resumable_trimesh_pipeline(tmp_path: Path) -> None: config_path = tmp_path / "config.json" config_path.write_text(json.dumps(config), encoding="utf-8") out = tmp_path / "out" + scope_manifest = tmp_path / "scope_manifest.json" + scope_manifest.write_text( + json.dumps( + { + "scope_version": 1, + "mode": "single", + "requested": ["orchestrator-test"], + "buildings": [ + { + "id": "orchestrator-test", + "status": "PASS", + "artifacts": [str(out / "building_spec.json")], + } + ], + } + ), + encoding="utf-8", + ) command = [ sys.executable, str(ROOT / "scripts" / "cad_showcase.py"), @@ -289,6 +325,8 @@ def test_orchestrator_runs_resumable_trimesh_pipeline(tmp_path: Path) -> None: str(config_path), "--source-report", str(source_report), + "--scope-manifest", + str(scope_manifest), "--out-dir", str(out), "--name", diff --git a/tests/test_delivery.py b/tests/test_delivery.py index eca29b9..4c14572 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -76,8 +76,64 @@ def test_strict_delivery_passes_for_glb_render_and_offline_viewer(tmp_path: Path str(offline), ) assert proc.returncode == 0, proc.stderr + offline_browser_report = tmp_path / "offline_browser_smoke_report.json" + offline_browser_report.write_text( + json.dumps( + { + "status": "PASS", + "detail": "4/4 checks passed", + "console_errors": [], + "page_errors": [], + "failed_requests": [], + } + ), + encoding="utf-8", + ) evidence = tmp_path / "evidence.json" source_report = source_report_fixture(tmp_path) + proc = run( + sys.executable, + "scripts/verify_delivery.py", + "--spec", + str(spec), + "--source-report", + str(source_report), + "--glb", + str(glb), + "--render", + str(render), + "--offline-viewer", + str(offline), + "--offline-browser-report", + str(offline_browser_report), + "--evidence-out", + str(evidence), + ) + assert proc.returncode == 0, proc.stderr + report = json.loads(evidence.read_text(encoding="utf-8")) + assert report["status"] == "PASS" + assert any(item["name"] == "offline:payload" and item["status"] == "PASS" for item in report["checks"]) + assert any(item["name"] == "offline:browser-smoke" and item["status"] == "PASS" for item in report["checks"]) + + +def test_offline_viewer_without_real_browser_report_is_blocked(tmp_path: Path) -> None: + spec, glb, _metadata = build_fixture(tmp_path) + render = tmp_path / "render.png" + render_fixture(render) + offline = tmp_path / "viewer.html" + proc = run( + sys.executable, + "scripts/write_offline_viewer.py", + "--spec", + str(spec), + "--glb", + str(glb), + "--out", + str(offline), + ) + assert proc.returncode == 0, proc.stderr + source_report = source_report_fixture(tmp_path) + evidence = tmp_path / "evidence.json" proc = run( sys.executable, "scripts/verify_delivery.py", @@ -94,10 +150,10 @@ def test_strict_delivery_passes_for_glb_render_and_offline_viewer(tmp_path: Path "--evidence-out", str(evidence), ) - assert proc.returncode == 0, proc.stderr + assert proc.returncode == 3 report = json.loads(evidence.read_text(encoding="utf-8")) - assert report["status"] == "PASS" - assert any(item["name"] == "offline:payload" and item["status"] == "PASS" for item in report["checks"]) + assert report["status"] == "BLOCKED" + assert any(item["name"] == "offline:browser-smoke" and item["status"] == "SKIP" for item in report["checks"]) def test_strict_delivery_requires_a_render(tmp_path: Path) -> None: