| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581 |
- """Detached-derived validation for board-viewer compact-package assets.
- Validates the packaged derived assets (hashes, geometry/counts, SVG safety)
- without requiring the original Allegro BRD on disk and without claiming BRD
- regeneration. Compact packages keep these assets as derived evidence only;
- `reference_regeneration_replay` remains `not_packaged_by_policy`.
- """
- from __future__ import annotations
- import hashlib
- import json
- import re
- from dataclasses import asdict, dataclass, field
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- from jsonschema import Draft202012Validator
- from jsonschema.exceptions import ValidationError
- ROOT = Path(__file__).resolve().parents[3]
- BUILD_INFO_SCHEMA = ROOT / "schemas" / "board_viewer_build_info.schema.json"
- DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
- DERIVED_ASSETS: tuple[str, ...] = (
- "board-data.json",
- "build-info.json",
- "import-report.json",
- "board-copper.svg",
- "board-silkscreen.svg",
- "board-mask-edge.svg",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- )
- # Backward-compatible alias (name kept; list now includes front+back SVGs).
- SIX_DERIVED_ASSETS: tuple[str, ...] = DERIVED_ASSETS
- HASHED_ASSET_NAMES: tuple[str, ...] = (
- "board-data.json",
- "import-report.json",
- "board-copper.svg",
- "board-silkscreen.svg",
- "board-mask-edge.svg",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- )
- SVG_NAMES: tuple[str, ...] = (
- "board-copper.svg",
- "board-silkscreen.svg",
- "board-mask-edge.svg",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- )
- CANONICAL_GENERATED_DIR = "tools/board-viewer/generated"
- # Compact packages relocate the derived assets under evidence/.
- COMPACT_EVIDENCE_GENERATED_DIRS = (
- "evidence/board-viewer",
- "evidence/board-viewer/generated",
- "CPLD/evidence/board-viewer",
- "CPLD/evidence/board-viewer/generated",
- )
- EVIDENCE_CLASS = "derived_evidence"
- def resolve_generated_dir(root: Path | str) -> Path:
- """Resolve board-viewer derived assets for live repo or compact extract."""
- base = Path(root)
- candidates = [
- base / CANONICAL_GENERATED_DIR,
- *[base / rel for rel in COMPACT_EVIDENCE_GENERATED_DIRS],
- # Some extracts nest under source/
- base / "source" / CANONICAL_GENERATED_DIR,
- base / "CPLD" / "source" / CANONICAL_GENERATED_DIR,
- ]
- for candidate in candidates:
- if (candidate / "board-data.json").is_file() and (
- candidate / "build-info.json"
- ).is_file():
- return candidate
- return base / CANONICAL_GENERATED_DIR
- AUTHORITY = "analysis_evidence_not_source_closure"
- REGENERATION_STATUS = "not_packaged_by_policy"
- VIEWBOX_TOLERANCE_MM = 0.1
- _SCRIPT_RE = re.compile(r"<\s*script\b", re.I)
- _EXTERNAL_HTTP_RE = re.compile(r"https?://(?!www\.w3\.org/)", re.I)
- _FILE_URL_RE = re.compile(r"file://", re.I)
- _ABS_WIN_RE = re.compile(r"[A-Za-z]:\\")
- _ABS_UNIX_RE = re.compile(r"/(?:home|Users|tmp|var/tmp)/")
- _HREF_EXT_RE = re.compile(r"(?:xlink:)?href\s*=\s*[\"'](?!#)", re.I)
- _URL_FUNC_RE = re.compile(r"url\(\s*[\"']?(?!#)", re.I)
- _RANDOM_RE = re.compile(
- r"Math\.random|Date\.now|uuid|randomUUID|crypto\.getRandomValues",
- re.I,
- )
- _VIEWBOX_RE = re.compile(r'viewBox\s*=\s*"([^"]+)"')
- @dataclass
- class Finding:
- check: str
- status: str
- detail: str
- @dataclass
- class DetachedDerivedReport:
- schema: str = "board-viewer-detached-derived-report-v1"
- generated_at_utc: str = ""
- status: str = "fail"
- evidence_class: str = EVIDENCE_CLASS
- authority: str = AUTHORITY
- canonical_relative_dir: str = CANONICAL_GENERATED_DIR
- reference_regeneration_replay: str = REGENERATION_STATUS
- regeneration_claim: str = "none"
- brd_file_present: bool = False
- packaging_policy: dict[str, Any] = field(default_factory=dict)
- assets: dict[str, Any] = field(default_factory=dict)
- provenance: dict[str, Any] = field(default_factory=dict)
- geometry: dict[str, Any] = field(default_factory=dict)
- counts: dict[str, Any] = field(default_factory=dict)
- svg_safety: dict[str, Any] = field(default_factory=dict)
- findings: list[Finding] = field(default_factory=list)
- summary: dict[str, int] = field(default_factory=dict)
- def add(self, check: str, status: str, detail: str) -> None:
- self.findings.append(Finding(check=check, status=status, detail=detail))
- def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- while chunk := stream.read(chunk_size):
- digest.update(chunk)
- return digest.hexdigest()
- def packaging_policy() -> dict[str, Any]:
- """Policy descriptor for packagers: keep derived assets once, as evidence."""
- return {
- "assets": list(DERIVED_ASSETS),
- "canonical_relative_dir": CANONICAL_GENERATED_DIR,
- "evidence_class": EVIDENCE_CLASS,
- "authority": AUTHORITY,
- "physical_inclusion": "single_copy_only",
- "duplicate_guidance": (
- "Ship exactly one physical copy under "
- f"{CANONICAL_GENERATED_DIR}/; do not also materialize the same "
- "bytes via a second external-source copy or reference mirror."
- ),
- "keep_svgs": True,
- "keep_reason": (
- "When compact packages exclude the Allegro BRD, the front+back SVGs plus "
- "board-data.json are the primary remote geometry/touchpoint evidence; "
- "ZIP cost is low relative to analysis value. Back SVGs are KiCad-mirrored "
- "about the vertical/Y axis (physical left-right flip)."
- ),
- "build_info_must_retain": [
- "sources.brd.sha256",
- "sources.generator_*.sha256",
- "generator_version",
- "toolchain",
- "assets.*.sha256",
- "counts",
- ],
- "reference_regeneration_replay": REGENERATION_STATUS,
- "detached_validation": (
- "Hashes, geometry/counts, and SVG safety only; never claim BRD "
- "regeneration when the BRD is absent."
- ),
- }
- def describe_derived_assets(generated_dir: Path | str) -> list[dict[str, Any]]:
- """Size/provenance rows packagers can attach to HANDOFF-INDEX / size-budget."""
- generated = Path(generated_dir)
- rows: list[dict[str, Any]] = []
- for name in DERIVED_ASSETS:
- path = generated / name
- role = (
- "derived_from_brd_visual"
- if name.endswith(".svg")
- else "derived_from_brd_parsed"
- )
- row: dict[str, Any] = {
- "asset": name,
- "path": f"{CANONICAL_GENERATED_DIR}/{name}",
- "exists": path.is_file(),
- "role": role,
- "evidence_class": EVIDENCE_CLASS,
- "authority": AUTHORITY,
- "note": (
- "Derived from the original Allegro BRD for remote analysis; "
- "not RTL/TD source closure. Regeneration is local-only / "
- f"{REGENERATION_STATUS} for compact packages."
- ),
- }
- if path.is_file():
- row["bytes"] = path.stat().st_size
- row["sha256"] = sha256_file(path)
- rows.append(row)
- return rows
- def _parse_viewbox(text: str) -> tuple[float, float, float, float] | None:
- match = _VIEWBOX_RE.search(text)
- if not match:
- return None
- parts = match.group(1).replace(",", " ").split()
- if len(parts) != 4:
- return None
- try:
- return float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3])
- except ValueError:
- return None
- def _scan_svg_safety(name: str, text: str, report: DetachedDerivedReport) -> list[str]:
- issues: list[str] = []
- for label, pattern in (
- ("script", _SCRIPT_RE),
- ("external_http", _EXTERNAL_HTTP_RE),
- ("file_url", _FILE_URL_RE),
- ("absolute_windows_path", _ABS_WIN_RE),
- ("absolute_local_unix_path", _ABS_UNIX_RE),
- ("external_href", _HREF_EXT_RE),
- ("external_url_func", _URL_FUNC_RE),
- ("non_reproducible_randomness", _RANDOM_RE),
- ):
- hits = pattern.findall(text)
- if hits:
- issues.append(f"{label}:{len(hits)}")
- report.add(f"svg_safety.{name}.{label}", "fail", f"{len(hits)} hit(s)")
- else:
- report.add(f"svg_safety.{name}.{label}", "pass", "clean")
- return issues
- def _resolve_source_path(
- metadata_path: str, *, repository_root: Path, generated: Path
- ) -> Path:
- path = Path(metadata_path)
- if path.is_absolute():
- return path
- candidate = repository_root / path
- if candidate.is_file():
- return candidate
- return generated.parent.parent.parent / path
- def validate_detached_derived(
- generated_dir: Path | str,
- *,
- repository_root: Path | str = ROOT,
- require_brd_present: bool = False,
- ) -> DetachedDerivedReport:
- """Validate derived assets without claiming BRD regeneration."""
- generated = Path(generated_dir).resolve()
- repository = Path(repository_root).resolve()
- report = DetachedDerivedReport(
- generated_at_utc=datetime.now(timezone.utc).isoformat(),
- packaging_policy=packaging_policy(),
- )
- asset_rows: dict[str, Any] = {}
- missing: list[str] = []
- for name in DERIVED_ASSETS:
- path = generated / name
- entry: dict[str, Any] = {
- "path": str(path),
- "exists": path.is_file(),
- "evidence_class": EVIDENCE_CLASS,
- }
- if path.is_file():
- entry["bytes"] = path.stat().st_size
- entry["sha256"] = sha256_file(path)
- report.add(f"asset.exists.{name}", "pass", "present")
- else:
- missing.append(name)
- report.add(f"asset.exists.{name}", "fail", "missing")
- asset_rows[name] = entry
- report.assets = asset_rows
- if missing:
- report.add("assets.complete_set", "fail", f"missing:{','.join(missing)}")
- else:
- report.add(
- "assets.complete_set",
- "pass",
- f"{len(DERIVED_ASSETS)} derived assets present (front+back SVGs)",
- )
- build_info_path = generated / "build-info.json"
- board_data_path = generated / "board-data.json"
- import_report_path = generated / "import-report.json"
- build_info: dict[str, Any] | None = None
- board_data: dict[str, Any] | None = None
- if build_info_path.is_file():
- try:
- build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
- schema = json.loads(BUILD_INFO_SCHEMA.read_text(encoding="utf-8"))
- Draft202012Validator(schema).validate(build_info)
- report.add("build_info.schema", "pass", "board-viewer-build-info-v1")
- except (OSError, json.JSONDecodeError, ValidationError, ValueError) as exc:
- build_info = None
- report.add("build_info.schema", "fail", str(exc))
- if build_info is not None:
- sources = build_info.get("sources") or {}
- brd_meta = sources.get("brd") or {}
- brd_sha = str(brd_meta.get("sha256") or "")
- brd_path_meta = str(brd_meta.get("path") or "")
- report.provenance["build_info_brd"] = brd_meta
- report.provenance["generator_version"] = build_info.get("generator_version")
- report.provenance["toolchain"] = build_info.get("toolchain")
- report.add(
- "provenance.brd_sha256_recorded",
- "pass" if re.fullmatch(r"[0-9a-f]{64}", brd_sha) else "fail",
- brd_sha or "missing",
- )
- generator_hashes = {
- key: value
- for key, value in sources.items()
- if str(key).startswith("generator_")
- }
- report.provenance["generator_source_hashes"] = {
- key: (value or {}).get("sha256") for key, value in generator_hashes.items()
- }
- report.add(
- "provenance.generator_hashes_recorded",
- "pass" if generator_hashes else "fail",
- f"{len(generator_hashes)} generator_* source entries",
- )
- brd_on_disk: Path | None = None
- if brd_path_meta:
- brd_on_disk = _resolve_source_path(
- brd_path_meta, repository_root=repository, generated=generated
- )
- report.brd_file_present = bool(brd_on_disk and brd_on_disk.is_file())
- if report.brd_file_present and brd_on_disk is not None:
- actual = sha256_file(brd_on_disk)
- match = actual == brd_sha
- report.provenance["brd_on_disk"] = {
- "path": str(brd_on_disk),
- "sha256": actual,
- "matches_build_info": match,
- }
- report.add(
- "provenance.brd_on_disk_optional",
- "pass" if match else "fail",
- actual if match else f"actual={actual} build-info={brd_sha}",
- )
- else:
- report.provenance["brd_on_disk"] = {
- "present": False,
- "note": (
- "BRD absence is expected for compact/detached packages; "
- "validation uses recorded build-info hashes only."
- ),
- }
- report.add(
- "provenance.brd_on_disk_optional",
- "fail" if require_brd_present else "pass",
- "missing (detached/compact expected)"
- if not require_brd_present
- else "missing but require_brd_present=True",
- )
- assets_meta = build_info.get("assets") or {}
- for name in HASHED_ASSET_NAMES:
- path = generated / name
- meta = assets_meta.get(name) or {}
- expected_sha = meta.get("sha256")
- expected_bytes = meta.get("bytes")
- if not path.is_file():
- continue
- actual_sha = asset_rows[name]["sha256"]
- actual_bytes = asset_rows[name]["bytes"]
- sha_ok = expected_sha == actual_sha
- bytes_ok = expected_bytes == actual_bytes
- asset_rows[name]["build_info_sha256"] = expected_sha
- asset_rows[name]["matches_build_info"] = sha_ok and bytes_ok
- report.add(
- f"asset.hash.{name}",
- "pass" if sha_ok and bytes_ok else "fail",
- actual_sha
- if sha_ok and bytes_ok
- else (
- f"sha={actual_sha} expected={expected_sha} "
- f"bytes={actual_bytes} expected_bytes={expected_bytes}"
- ),
- )
- # build-info.json is the manifest; it is not self-hashed in assets{}.
- report.add(
- "asset.hash.build-info.json",
- "pass",
- "manifest retained; digests cover sibling assets",
- )
- report.provenance["note"] = (
- "Detached validation never asserts BRD regeneration. "
- f"reference_regeneration_replay={REGENERATION_STATUS}."
- )
- report.add(
- "regeneration.claim",
- "pass",
- "none; not claiming BRD regeneration",
- )
- else:
- report.add("provenance.brd_sha256_recorded", "fail", "build-info unavailable")
- if import_report_path.is_file():
- try:
- import_report = json.loads(import_report_path.read_text(encoding="utf-8"))
- errors = import_report.get("errors") or []
- source_file = str(import_report.get("source_file") or "")
- report.provenance["import_report"] = {
- "source_file": source_file,
- "source_format": import_report.get("source_format"),
- "errors": errors,
- }
- report.add(
- "import_report.errors",
- "pass" if not errors else "fail",
- "none" if not errors else str(errors),
- )
- report.add(
- "import_report.source_file",
- "pass" if source_file.endswith(".brd") else "fail",
- source_file or "missing",
- )
- except (OSError, json.JSONDecodeError) as exc:
- report.add("import_report.parse", "fail", str(exc))
- board_view_box: dict[str, float] | None = None
- if board_data_path.is_file():
- try:
- board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
- data_schema = json.loads(DATA_SCHEMA.read_text(encoding="utf-8"))
- Draft202012Validator(data_schema).validate(board_data)
- report.add("board_data.schema", "pass", str(board_data.get("schema")))
- except (OSError, json.JSONDecodeError, ValidationError, ValueError) as exc:
- board_data = None
- report.add("board_data.schema", "fail", str(exc))
- if board_data is not None and build_info is not None:
- board = board_data.get("board") or {}
- view_box = board.get("view_box") or {}
- board_view_box = {
- "x": float(view_box.get("x", 0.0)),
- "y": float(view_box.get("y", 0.0)),
- "width": float(view_box.get("width", 0.0)),
- "height": float(view_box.get("height", 0.0)),
- }
- bi_counts = build_info.get("counts") or {}
- bd_counts = board_data.get("counts") or {}
- touchpoints = board_data.get("touchpoints") or []
- resistors = board_data.get("resistors") or []
- count_checks = {
- "footprints": (bi_counts.get("footprints"), bd_counts.get("footprints")),
- "touchpoints": (bi_counts.get("touchpoints"), bd_counts.get("touchpoints")),
- "pads": (bi_counts.get("pads"), bd_counts.get("pads")),
- "resistors": (bi_counts.get("resistors"), bd_counts.get("resistors")),
- "resistor_pads": (bi_counts.get("resistor_pads"), bd_counts.get("resistor_pads")),
- "touchpoints_list_len": (
- bi_counts.get("touchpoints"),
- len(touchpoints) if isinstance(touchpoints, list) else None,
- ),
- "resistors_list_len": (
- bi_counts.get("resistors"),
- len(resistors) if isinstance(resistors, list) else None,
- ),
- }
- report.counts = {
- "build_info": bi_counts,
- "board_data": bd_counts,
- "touchpoints_list_len": len(touchpoints) if isinstance(touchpoints, list) else None,
- "resistors_list_len": len(resistors) if isinstance(resistors, list) else None,
- "checks": {},
- }
- all_counts_ok = True
- for key, (expected, actual) in count_checks.items():
- ok = expected == actual and expected is not None
- all_counts_ok = all_counts_ok and ok
- report.counts["checks"][key] = {
- "expected": expected,
- "actual": actual,
- "ok": ok,
- }
- report.add(
- f"counts.{key}",
- "pass" if ok else "fail",
- f"expected={expected} actual={actual}",
- )
- report.geometry["board_data_view_box"] = board_view_box
- report.add(
- "geometry.board_data_view_box",
- "pass"
- if board_view_box["width"] > 0 and board_view_box["height"] > 0
- else "fail",
- json.dumps(board_view_box),
- )
- if not all_counts_ok:
- report.add("counts.consistent", "fail", "mismatch between build-info and board-data")
- else:
- report.add("counts.consistent", "pass", "footprints/touchpoints/pads/resistors aligned")
- try:
- from .data import validate_resistor_index
- validate_resistor_index(board_data)
- report.add("resistors.index", "pass", "resistor index structure and annotation ⊆ index")
- except ValueError as exc:
- report.add("resistors.index", "fail", str(exc))
- svg_safety: dict[str, Any] = {}
- viewboxes: list[tuple[float, float, float, float]] = []
- for name in SVG_NAMES:
- path = generated / name
- entry: dict[str, Any] = {"exists": path.is_file()}
- if not path.is_file():
- svg_safety[name] = entry
- continue
- text = path.read_text(encoding="utf-8", errors="replace")
- issues = _scan_svg_safety(name, text, report)
- viewbox = _parse_viewbox(text)
- entry["safety_issues"] = issues
- entry["viewBox"] = None if viewbox is None else list(viewbox)
- if viewbox is not None:
- viewboxes.append(viewbox)
- if board_view_box is not None:
- dw = abs(viewbox[2] - board_view_box["width"])
- dh = abs(viewbox[3] - board_view_box["height"])
- dx = abs(viewbox[0] - board_view_box["x"])
- dy = abs(viewbox[1] - board_view_box["y"])
- ok = max(dw, dh, dx, dy) <= VIEWBOX_TOLERANCE_MM
- entry["coord_delta_vs_board_data_mm"] = {
- "dx": dx,
- "dy": dy,
- "dw": dw,
- "dh": dh,
- }
- report.add(
- f"geometry.svg.{name}",
- "pass" if ok else "fail",
- f"delta_mm dx={dx:.6f} dy={dy:.6f} dw={dw:.6f} dh={dh:.6f}",
- )
- else:
- report.add(f"geometry.svg.{name}", "fail", "missing/invalid viewBox")
- svg_safety[name] = entry
- if len(viewboxes) == len(SVG_NAMES) and len(set(viewboxes)) == 1:
- report.add("geometry.svg.consistent_across_layers", "pass", str(viewboxes[0]))
- elif viewboxes:
- report.add(
- "geometry.svg.consistent_across_layers",
- "fail",
- f"divergent viewBoxes: {viewboxes}",
- )
- report.svg_safety = svg_safety
- report.geometry["svg_viewboxes"] = [list(v) for v in viewboxes]
- summary = {"pass": 0, "fail": 0, "other": 0}
- for finding in report.findings:
- if finding.status in summary:
- summary[finding.status] += 1
- else:
- summary["other"] += 1
- report.summary = summary
- report.status = "pass" if summary["fail"] == 0 else "fail"
- report.reference_regeneration_replay = REGENERATION_STATUS
- report.regeneration_claim = "none"
- return report
- def report_to_dict(report: DetachedDerivedReport) -> dict[str, Any]:
- return asdict(report)
|