detached.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. """Detached-derived validation for board-viewer compact-package assets.
  2. Validates the six packaged derived assets (hashes, geometry/counts, SVG safety)
  3. without requiring the original Allegro BRD on disk and without claiming BRD
  4. regeneration. Compact packages keep these assets as derived evidence only;
  5. `reference_regeneration_replay` remains `not_packaged_by_policy`.
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import json
  10. import re
  11. from dataclasses import asdict, dataclass, field
  12. from datetime import datetime, timezone
  13. from pathlib import Path
  14. from typing import Any
  15. from jsonschema import Draft202012Validator
  16. from jsonschema.exceptions import ValidationError
  17. ROOT = Path(__file__).resolve().parents[3]
  18. BUILD_INFO_SCHEMA = ROOT / "schemas" / "board_viewer_build_info.schema.json"
  19. DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
  20. SIX_DERIVED_ASSETS: tuple[str, ...] = (
  21. "board-data.json",
  22. "build-info.json",
  23. "import-report.json",
  24. "board-copper.svg",
  25. "board-silkscreen.svg",
  26. "board-mask-edge.svg",
  27. )
  28. HASHED_ASSET_NAMES: tuple[str, ...] = (
  29. "board-data.json",
  30. "import-report.json",
  31. "board-copper.svg",
  32. "board-silkscreen.svg",
  33. "board-mask-edge.svg",
  34. )
  35. SVG_NAMES: tuple[str, ...] = (
  36. "board-copper.svg",
  37. "board-silkscreen.svg",
  38. "board-mask-edge.svg",
  39. )
  40. CANONICAL_GENERATED_DIR = "tools/board-viewer/generated"
  41. EVIDENCE_CLASS = "derived_evidence"
  42. AUTHORITY = "analysis_evidence_not_source_closure"
  43. REGENERATION_STATUS = "not_packaged_by_policy"
  44. VIEWBOX_TOLERANCE_MM = 0.1
  45. _SCRIPT_RE = re.compile(r"<\s*script\b", re.I)
  46. _EXTERNAL_HTTP_RE = re.compile(r"https?://(?!www\.w3\.org/)", re.I)
  47. _FILE_URL_RE = re.compile(r"file://", re.I)
  48. _ABS_WIN_RE = re.compile(r"[A-Za-z]:\\")
  49. _ABS_UNIX_RE = re.compile(r"/(?:home|Users|tmp|var/tmp)/")
  50. _HREF_EXT_RE = re.compile(r"(?:xlink:)?href\s*=\s*[\"'](?!#)", re.I)
  51. _URL_FUNC_RE = re.compile(r"url\(\s*[\"']?(?!#)", re.I)
  52. _RANDOM_RE = re.compile(
  53. r"Math\.random|Date\.now|uuid|randomUUID|crypto\.getRandomValues",
  54. re.I,
  55. )
  56. _VIEWBOX_RE = re.compile(r'viewBox\s*=\s*"([^"]+)"')
  57. @dataclass
  58. class Finding:
  59. check: str
  60. status: str
  61. detail: str
  62. @dataclass
  63. class DetachedDerivedReport:
  64. schema: str = "board-viewer-detached-derived-report-v1"
  65. generated_at_utc: str = ""
  66. status: str = "fail"
  67. evidence_class: str = EVIDENCE_CLASS
  68. authority: str = AUTHORITY
  69. canonical_relative_dir: str = CANONICAL_GENERATED_DIR
  70. reference_regeneration_replay: str = REGENERATION_STATUS
  71. regeneration_claim: str = "none"
  72. brd_file_present: bool = False
  73. packaging_policy: dict[str, Any] = field(default_factory=dict)
  74. assets: dict[str, Any] = field(default_factory=dict)
  75. provenance: dict[str, Any] = field(default_factory=dict)
  76. geometry: dict[str, Any] = field(default_factory=dict)
  77. counts: dict[str, Any] = field(default_factory=dict)
  78. svg_safety: dict[str, Any] = field(default_factory=dict)
  79. findings: list[Finding] = field(default_factory=list)
  80. summary: dict[str, int] = field(default_factory=dict)
  81. def add(self, check: str, status: str, detail: str) -> None:
  82. self.findings.append(Finding(check=check, status=status, detail=detail))
  83. def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
  84. digest = hashlib.sha256()
  85. with path.open("rb") as stream:
  86. while chunk := stream.read(chunk_size):
  87. digest.update(chunk)
  88. return digest.hexdigest()
  89. def packaging_policy() -> dict[str, Any]:
  90. """Policy descriptor for packagers: keep six assets once, as derived evidence."""
  91. return {
  92. "assets": list(SIX_DERIVED_ASSETS),
  93. "canonical_relative_dir": CANONICAL_GENERATED_DIR,
  94. "evidence_class": EVIDENCE_CLASS,
  95. "authority": AUTHORITY,
  96. "physical_inclusion": "single_copy_only",
  97. "duplicate_guidance": (
  98. "Ship exactly one physical copy under "
  99. f"{CANONICAL_GENERATED_DIR}/; do not also materialize the same "
  100. "bytes via a second external-source copy or reference mirror."
  101. ),
  102. "keep_svgs": True,
  103. "keep_reason": (
  104. "When compact packages exclude the Allegro BRD, the three SVGs plus "
  105. "board-data.json are the primary remote geometry/touchpoint evidence; "
  106. "ZIP cost is low relative to analysis value."
  107. ),
  108. "build_info_must_retain": [
  109. "sources.brd.sha256",
  110. "sources.generator_*.sha256",
  111. "generator_version",
  112. "toolchain",
  113. "assets.*.sha256",
  114. "counts",
  115. ],
  116. "reference_regeneration_replay": REGENERATION_STATUS,
  117. "detached_validation": (
  118. "Hashes, geometry/counts, and SVG safety only; never claim BRD "
  119. "regeneration when the BRD is absent."
  120. ),
  121. }
  122. def describe_derived_assets(generated_dir: Path | str) -> list[dict[str, Any]]:
  123. """Size/provenance rows packagers can attach to HANDOFF-INDEX / size-budget."""
  124. generated = Path(generated_dir)
  125. rows: list[dict[str, Any]] = []
  126. for name in SIX_DERIVED_ASSETS:
  127. path = generated / name
  128. role = (
  129. "derived_from_brd_visual"
  130. if name.endswith(".svg")
  131. else "derived_from_brd_parsed"
  132. )
  133. row: dict[str, Any] = {
  134. "asset": name,
  135. "path": f"{CANONICAL_GENERATED_DIR}/{name}",
  136. "exists": path.is_file(),
  137. "role": role,
  138. "evidence_class": EVIDENCE_CLASS,
  139. "authority": AUTHORITY,
  140. "note": (
  141. "Derived from the original Allegro BRD for remote analysis; "
  142. "not RTL/TD source closure. Regeneration is local-only / "
  143. f"{REGENERATION_STATUS} for compact packages."
  144. ),
  145. }
  146. if path.is_file():
  147. row["bytes"] = path.stat().st_size
  148. row["sha256"] = sha256_file(path)
  149. rows.append(row)
  150. return rows
  151. def _parse_viewbox(text: str) -> tuple[float, float, float, float] | None:
  152. match = _VIEWBOX_RE.search(text)
  153. if not match:
  154. return None
  155. parts = match.group(1).replace(",", " ").split()
  156. if len(parts) != 4:
  157. return None
  158. try:
  159. return float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3])
  160. except ValueError:
  161. return None
  162. def _scan_svg_safety(name: str, text: str, report: DetachedDerivedReport) -> list[str]:
  163. issues: list[str] = []
  164. for label, pattern in (
  165. ("script", _SCRIPT_RE),
  166. ("external_http", _EXTERNAL_HTTP_RE),
  167. ("file_url", _FILE_URL_RE),
  168. ("absolute_windows_path", _ABS_WIN_RE),
  169. ("absolute_local_unix_path", _ABS_UNIX_RE),
  170. ("external_href", _HREF_EXT_RE),
  171. ("external_url_func", _URL_FUNC_RE),
  172. ("non_reproducible_randomness", _RANDOM_RE),
  173. ):
  174. hits = pattern.findall(text)
  175. if hits:
  176. issues.append(f"{label}:{len(hits)}")
  177. report.add(f"svg_safety.{name}.{label}", "fail", f"{len(hits)} hit(s)")
  178. else:
  179. report.add(f"svg_safety.{name}.{label}", "pass", "clean")
  180. return issues
  181. def _resolve_source_path(
  182. metadata_path: str, *, repository_root: Path, generated: Path
  183. ) -> Path:
  184. path = Path(metadata_path)
  185. if path.is_absolute():
  186. return path
  187. candidate = repository_root / path
  188. if candidate.is_file():
  189. return candidate
  190. return generated.parent.parent.parent / path
  191. def validate_detached_derived(
  192. generated_dir: Path | str,
  193. *,
  194. repository_root: Path | str = ROOT,
  195. require_brd_present: bool = False,
  196. ) -> DetachedDerivedReport:
  197. """Validate six derived assets without claiming BRD regeneration."""
  198. generated = Path(generated_dir).resolve()
  199. repository = Path(repository_root).resolve()
  200. report = DetachedDerivedReport(
  201. generated_at_utc=datetime.now(timezone.utc).isoformat(),
  202. packaging_policy=packaging_policy(),
  203. )
  204. asset_rows: dict[str, Any] = {}
  205. missing: list[str] = []
  206. for name in SIX_DERIVED_ASSETS:
  207. path = generated / name
  208. entry: dict[str, Any] = {
  209. "path": str(path),
  210. "exists": path.is_file(),
  211. "evidence_class": EVIDENCE_CLASS,
  212. }
  213. if path.is_file():
  214. entry["bytes"] = path.stat().st_size
  215. entry["sha256"] = sha256_file(path)
  216. report.add(f"asset.exists.{name}", "pass", "present")
  217. else:
  218. missing.append(name)
  219. report.add(f"asset.exists.{name}", "fail", "missing")
  220. asset_rows[name] = entry
  221. report.assets = asset_rows
  222. if missing:
  223. report.add("assets.complete_set", "fail", f"missing:{','.join(missing)}")
  224. else:
  225. report.add("assets.complete_set", "pass", "six derived assets present")
  226. build_info_path = generated / "build-info.json"
  227. board_data_path = generated / "board-data.json"
  228. import_report_path = generated / "import-report.json"
  229. build_info: dict[str, Any] | None = None
  230. board_data: dict[str, Any] | None = None
  231. if build_info_path.is_file():
  232. try:
  233. build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
  234. schema = json.loads(BUILD_INFO_SCHEMA.read_text(encoding="utf-8"))
  235. Draft202012Validator(schema).validate(build_info)
  236. report.add("build_info.schema", "pass", "board-viewer-build-info-v1")
  237. except (OSError, json.JSONDecodeError, ValidationError, ValueError) as exc:
  238. build_info = None
  239. report.add("build_info.schema", "fail", str(exc))
  240. if build_info is not None:
  241. sources = build_info.get("sources") or {}
  242. brd_meta = sources.get("brd") or {}
  243. brd_sha = str(brd_meta.get("sha256") or "")
  244. brd_path_meta = str(brd_meta.get("path") or "")
  245. report.provenance["build_info_brd"] = brd_meta
  246. report.provenance["generator_version"] = build_info.get("generator_version")
  247. report.provenance["toolchain"] = build_info.get("toolchain")
  248. report.add(
  249. "provenance.brd_sha256_recorded",
  250. "pass" if re.fullmatch(r"[0-9a-f]{64}", brd_sha) else "fail",
  251. brd_sha or "missing",
  252. )
  253. generator_hashes = {
  254. key: value
  255. for key, value in sources.items()
  256. if str(key).startswith("generator_")
  257. }
  258. report.provenance["generator_source_hashes"] = {
  259. key: (value or {}).get("sha256") for key, value in generator_hashes.items()
  260. }
  261. report.add(
  262. "provenance.generator_hashes_recorded",
  263. "pass" if generator_hashes else "fail",
  264. f"{len(generator_hashes)} generator_* source entries",
  265. )
  266. brd_on_disk: Path | None = None
  267. if brd_path_meta:
  268. brd_on_disk = _resolve_source_path(
  269. brd_path_meta, repository_root=repository, generated=generated
  270. )
  271. report.brd_file_present = bool(brd_on_disk and brd_on_disk.is_file())
  272. if report.brd_file_present and brd_on_disk is not None:
  273. actual = sha256_file(brd_on_disk)
  274. match = actual == brd_sha
  275. report.provenance["brd_on_disk"] = {
  276. "path": str(brd_on_disk),
  277. "sha256": actual,
  278. "matches_build_info": match,
  279. }
  280. report.add(
  281. "provenance.brd_on_disk_optional",
  282. "pass" if match else "fail",
  283. actual if match else f"actual={actual} build-info={brd_sha}",
  284. )
  285. else:
  286. report.provenance["brd_on_disk"] = {
  287. "present": False,
  288. "note": (
  289. "BRD absence is expected for compact/detached packages; "
  290. "validation uses recorded build-info hashes only."
  291. ),
  292. }
  293. report.add(
  294. "provenance.brd_on_disk_optional",
  295. "fail" if require_brd_present else "pass",
  296. "missing (detached/compact expected)"
  297. if not require_brd_present
  298. else "missing but require_brd_present=True",
  299. )
  300. assets_meta = build_info.get("assets") or {}
  301. for name in HASHED_ASSET_NAMES:
  302. path = generated / name
  303. meta = assets_meta.get(name) or {}
  304. expected_sha = meta.get("sha256")
  305. expected_bytes = meta.get("bytes")
  306. if not path.is_file():
  307. continue
  308. actual_sha = asset_rows[name]["sha256"]
  309. actual_bytes = asset_rows[name]["bytes"]
  310. sha_ok = expected_sha == actual_sha
  311. bytes_ok = expected_bytes == actual_bytes
  312. asset_rows[name]["build_info_sha256"] = expected_sha
  313. asset_rows[name]["matches_build_info"] = sha_ok and bytes_ok
  314. report.add(
  315. f"asset.hash.{name}",
  316. "pass" if sha_ok and bytes_ok else "fail",
  317. actual_sha
  318. if sha_ok and bytes_ok
  319. else (
  320. f"sha={actual_sha} expected={expected_sha} "
  321. f"bytes={actual_bytes} expected_bytes={expected_bytes}"
  322. ),
  323. )
  324. # build-info.json is the manifest; it is not self-hashed in assets{}.
  325. report.add(
  326. "asset.hash.build-info.json",
  327. "pass",
  328. "manifest retained; digests cover sibling assets",
  329. )
  330. report.provenance["note"] = (
  331. "Detached validation never asserts BRD regeneration. "
  332. f"reference_regeneration_replay={REGENERATION_STATUS}."
  333. )
  334. report.add(
  335. "regeneration.claim",
  336. "pass",
  337. "none; not claiming BRD regeneration",
  338. )
  339. else:
  340. report.add("provenance.brd_sha256_recorded", "fail", "build-info unavailable")
  341. if import_report_path.is_file():
  342. try:
  343. import_report = json.loads(import_report_path.read_text(encoding="utf-8"))
  344. errors = import_report.get("errors") or []
  345. source_file = str(import_report.get("source_file") or "")
  346. report.provenance["import_report"] = {
  347. "source_file": source_file,
  348. "source_format": import_report.get("source_format"),
  349. "errors": errors,
  350. }
  351. report.add(
  352. "import_report.errors",
  353. "pass" if not errors else "fail",
  354. "none" if not errors else str(errors),
  355. )
  356. report.add(
  357. "import_report.source_file",
  358. "pass" if source_file.endswith(".brd") else "fail",
  359. source_file or "missing",
  360. )
  361. except (OSError, json.JSONDecodeError) as exc:
  362. report.add("import_report.parse", "fail", str(exc))
  363. board_view_box: dict[str, float] | None = None
  364. if board_data_path.is_file():
  365. try:
  366. board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
  367. data_schema = json.loads(DATA_SCHEMA.read_text(encoding="utf-8"))
  368. Draft202012Validator(data_schema).validate(board_data)
  369. report.add("board_data.schema", "pass", str(board_data.get("schema")))
  370. except (OSError, json.JSONDecodeError, ValidationError, ValueError) as exc:
  371. board_data = None
  372. report.add("board_data.schema", "fail", str(exc))
  373. if board_data is not None and build_info is not None:
  374. board = board_data.get("board") or {}
  375. view_box = board.get("view_box") or {}
  376. board_view_box = {
  377. "x": float(view_box.get("x", 0.0)),
  378. "y": float(view_box.get("y", 0.0)),
  379. "width": float(view_box.get("width", 0.0)),
  380. "height": float(view_box.get("height", 0.0)),
  381. }
  382. bi_counts = build_info.get("counts") or {}
  383. bd_counts = board_data.get("counts") or {}
  384. touchpoints = board_data.get("touchpoints") or []
  385. count_checks = {
  386. "footprints": (bi_counts.get("footprints"), bd_counts.get("footprints")),
  387. "touchpoints": (bi_counts.get("touchpoints"), bd_counts.get("touchpoints")),
  388. "pads": (bi_counts.get("pads"), bd_counts.get("pads")),
  389. "touchpoints_list_len": (
  390. bi_counts.get("touchpoints"),
  391. len(touchpoints) if isinstance(touchpoints, list) else None,
  392. ),
  393. }
  394. report.counts = {
  395. "build_info": bi_counts,
  396. "board_data": bd_counts,
  397. "touchpoints_list_len": len(touchpoints) if isinstance(touchpoints, list) else None,
  398. "checks": {},
  399. }
  400. all_counts_ok = True
  401. for key, (expected, actual) in count_checks.items():
  402. ok = expected == actual and expected is not None
  403. all_counts_ok = all_counts_ok and ok
  404. report.counts["checks"][key] = {
  405. "expected": expected,
  406. "actual": actual,
  407. "ok": ok,
  408. }
  409. report.add(
  410. f"counts.{key}",
  411. "pass" if ok else "fail",
  412. f"expected={expected} actual={actual}",
  413. )
  414. report.geometry["board_data_view_box"] = board_view_box
  415. report.add(
  416. "geometry.board_data_view_box",
  417. "pass"
  418. if board_view_box["width"] > 0 and board_view_box["height"] > 0
  419. else "fail",
  420. json.dumps(board_view_box),
  421. )
  422. if not all_counts_ok:
  423. report.add("counts.consistent", "fail", "mismatch between build-info and board-data")
  424. else:
  425. report.add("counts.consistent", "pass", "footprints/touchpoints/pads aligned")
  426. svg_safety: dict[str, Any] = {}
  427. viewboxes: list[tuple[float, float, float, float]] = []
  428. for name in SVG_NAMES:
  429. path = generated / name
  430. entry: dict[str, Any] = {"exists": path.is_file()}
  431. if not path.is_file():
  432. svg_safety[name] = entry
  433. continue
  434. text = path.read_text(encoding="utf-8", errors="replace")
  435. issues = _scan_svg_safety(name, text, report)
  436. viewbox = _parse_viewbox(text)
  437. entry["safety_issues"] = issues
  438. entry["viewBox"] = None if viewbox is None else list(viewbox)
  439. if viewbox is not None:
  440. viewboxes.append(viewbox)
  441. if board_view_box is not None:
  442. dw = abs(viewbox[2] - board_view_box["width"])
  443. dh = abs(viewbox[3] - board_view_box["height"])
  444. dx = abs(viewbox[0] - board_view_box["x"])
  445. dy = abs(viewbox[1] - board_view_box["y"])
  446. ok = max(dw, dh, dx, dy) <= VIEWBOX_TOLERANCE_MM
  447. entry["coord_delta_vs_board_data_mm"] = {
  448. "dx": dx,
  449. "dy": dy,
  450. "dw": dw,
  451. "dh": dh,
  452. }
  453. report.add(
  454. f"geometry.svg.{name}",
  455. "pass" if ok else "fail",
  456. f"delta_mm dx={dx:.6f} dy={dy:.6f} dw={dw:.6f} dh={dh:.6f}",
  457. )
  458. else:
  459. report.add(f"geometry.svg.{name}", "fail", "missing/invalid viewBox")
  460. svg_safety[name] = entry
  461. if len(viewboxes) == len(SVG_NAMES) and len(set(viewboxes)) == 1:
  462. report.add("geometry.svg.consistent_across_layers", "pass", str(viewboxes[0]))
  463. elif viewboxes:
  464. report.add(
  465. "geometry.svg.consistent_across_layers",
  466. "fail",
  467. f"divergent viewBoxes: {viewboxes}",
  468. )
  469. report.svg_safety = svg_safety
  470. report.geometry["svg_viewboxes"] = [list(v) for v in viewboxes]
  471. summary = {"pass": 0, "fail": 0, "other": 0}
  472. for finding in report.findings:
  473. if finding.status in summary:
  474. summary[finding.status] += 1
  475. else:
  476. summary["other"] += 1
  477. report.summary = summary
  478. report.status = "pass" if summary["fail"] == 0 else "fail"
  479. report.reference_regeneration_replay = REGENERATION_STATUS
  480. report.regeneration_claim = "none"
  481. return report
  482. def report_to_dict(report: DetachedDerivedReport) -> dict[str, Any]:
  483. return asdict(report)