detached.py 21 KB

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