#!/usr/bin/env python3 """Refresh docs/REFERENCE-INVENTORY.{json,md} from live reference + board-viewer assets.""" from __future__ import annotations import argparse import hashlib import json import sys from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[2] EXPECTED_BRD_SHA256 = "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb" EXPECTED_PDF_SHA256 = "7ebd0dced194338ceb97ff5a0abcee2d9790e7f6e7a90d9d4be7de593dca7eb5" CANONICAL_BRD = ( "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/" "FCB_FPGA+MCU_V1.2_20260717.brd" ) ARCHIVE_BRD = "reference/original/local_archives/board/FCB_FPGA+MCU_V1.2_20260717.brd" HISTORICAL_0611_PDF = "reference/original/schematics/FCB_FPGA+MCU0611.pdf" # Policy placeholder: there is no V1.2 schematic PDF; do not invent a real filename claim. V12_SCHEMATIC_PDF_POLICY_PATH = ( "reference/original/schematics/FCB_FPGA_MCU_V1.2_schematic.pdf" ) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while chunk := stream.read(1024 * 1024): digest.update(chunk) return digest.hexdigest() def item_for( root: Path, relative: str, *, expected_sha256: str | None = None, confidence: str | None = None, notes: dict[str, Any] | None = None, require_file: bool = True, ) -> dict[str, Any]: path = root / relative payload: dict[str, Any] = { "path": relative, "exists": path.is_file(), "size": path.stat().st_size if path.is_file() else 0, } if path.is_file(): payload["sha256"] = sha256_file(path) if expected_sha256 is not None: payload["expected_sha256"] = expected_sha256 payload["hash_match"] = bool( path.is_file() and payload.get("sha256") == expected_sha256 ) if confidence is not None: payload["confidence"] = confidence else: payload["confidence"] = ( "confirmed" if payload.get("hash_match") else ("missing" if not path.is_file() else "hash_fail") ) elif confidence is not None: payload["confidence"] = confidence else: payload["confidence"] = ( "present" if path.is_file() else ("missing" if require_file else "not_provided") ) if notes: payload.update(notes) return payload def policy_missing_item( relative: str, *, role: str, evidence_class: str, notes: dict[str, Any] | None = None, ) -> dict[str, Any]: """Inventory row for an asset that is intentionally absent (policy / not provided).""" payload: dict[str, Any] = { "path": relative, "exists": False, "size": 0, "confidence": "missing_by_policy", "status": "not_provided", "role": role, "evidence_class": evidence_class, } if notes: payload.update(notes) return payload def build_inventory(root: Path) -> dict[str, Any]: generated = root / "tools/board-viewer/generated" build_info: dict[str, Any] = {} if (generated / "build-info.json").is_file(): build_info = json.loads((generated / "build-info.json").read_text(encoding="utf-8")) items = [ item_for(root, "reference/original/MANIFEST.zh-CN.md"), item_for( root, CANONICAL_BRD, expected_sha256=EXPECTED_BRD_SHA256, notes={ "role": "canonical_brd", "evidence_class": "authoritative_physical_board_database", "authority": "v1_2_physical_path", "packaging_note": ( "Canonical physical BRD for analysis packages; " "prefer this path over local_archives duplicate" ), }, ), item_for( root, ARCHIVE_BRD, expected_sha256=EXPECTED_BRD_SHA256, notes={ "role": "duplicate_archive_mirror", "evidence_class": "authoritative_physical_board_database_mirror", "byte_identical_to_canonical": True, "packaging_recommendation": ( "Keep one physical copy in analysis packages: include " f"{CANONICAL_BRD} and omit {ARCHIVE_BRD} (or replace the " "archive entry with a provenance pointer to the canonical path)." ), }, ), item_for( root, "reference/original/schematics/8000高温罩电气图V2.0.pdf", expected_sha256=EXPECTED_PDF_SHA256, notes={ "role": "system_electrical_boundary_pdf", "evidence_class": "system_schematic_reference", }, ), item_for( root, HISTORICAL_0611_PDF, notes={ "role": "historical_schematic_side_evidence", "evidence_class": "historical_schematic_side_evidence", "authority": "non_authoritative_for_v1_2_product_io", "must_not_override": [ "CON104", "CON105", "CON106", "CON120", "CON12", "CON129", ], "notes": ( "Earlier FCB FPGA+MCU schematic PDF (not the 20260717 V1.2 board " "revision). May help with legacy net names / old sheets only; " "must not override V1.2 BRD activity mapping for motor/limit/EN." ), }, ), policy_missing_item( V12_SCHEMATIC_PDF_POLICY_PATH, role="v1_2_schematic_pdf", evidence_class="missing_by_policy", notes={ "status": "not_provided", "authority": "none", "notes": ( "No V1.2 schematic PDF was provided. Do not invent one and do not " "treat FCB_FPGA+MCU0611.pdf as a V1.2 schematic substitute." ), }, ), item_for(root, "reference/original/diagrams/上位机逻辑.svg"), item_for(root, "reference/original/diagrams/接长鑫水滴系统.svg"), item_for( root, "config/board_viewer_annotations.fcb_fpga_mcu_v1_2.json", notes={ "role": "v1_2_curated_annotations", "evidence_class": "curated_annotation_for_v1_2_brd", }, ), item_for( root, "config/pin_inventory.fcb_fpga_mcu0611.json", notes={ "role": "historical_schematic_side_evidence", "evidence_class": "historical_schematic_side_evidence", "authority": "non_authoritative_for_v1_2_product_io", "must_not_override": [ "CON104", "CON105", "CON106", "CON120", "CON12", "CON129", ], }, ), item_for( root, "config/pin_inventory.prod2u_door_temp_v1_2.json", notes={ "role": "v1_2_product_interface_evidence", "evidence_class": "product_io_evidence_summary", }, ), item_for( root, "docs/IO_EVIDENCE_MATRIX.zh-CN.md", notes={ "role": "io_evidence_matrix", "evidence_class": "split_evidence_grades_physical_polarity_measurement", }, ), item_for( root, "tools/board-viewer/generated/board-data.json", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", }, ), item_for( root, "tools/board-viewer/generated/build-info.json", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", }, ), item_for( root, "tools/board-viewer/generated/import-report.json", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", }, ), item_for( root, "tools/board-viewer/generated/board-copper.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "F.Cu,Edge.Cuts", }, ), item_for( root, "tools/board-viewer/generated/board-silkscreen.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "F.SilkS,Edge.Cuts", }, ), item_for( root, "tools/board-viewer/generated/board-mask-edge.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "F.Mask,Edge.Cuts", }, ), item_for( root, "tools/board-viewer/generated/board-copper-back.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "B.Cu,Edge.Cuts", "mirror": "KiCad --mirror about vertical/Y axis", }, ), item_for( root, "tools/board-viewer/generated/board-silkscreen-back.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "B.SilkS,Edge.Cuts", "mirror": "KiCad --mirror about vertical/Y axis", }, ), item_for( root, "tools/board-viewer/generated/board-mask-edge-back.svg", notes={ "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure", "layer": "B.Mask,Edge.Cuts", "mirror": "KiCad --mirror about vertical/Y axis", }, ), ] present = sum(1 for item in items if item.get("exists")) # Policy-missing rows are intentional absences, not inventory gaps. missing = sum( 1 for item in items if not item.get("exists") and item.get("confidence") != "missing_by_policy" ) policy_missing = sum( 1 for item in items if item.get("confidence") == "missing_by_policy" ) hash_ok = sum(1 for item in items if item.get("hash_match") is True) # Missing optional/gitignored mirrors are tracked under `missing`, not hash_fail. hash_fail = sum( 1 for item in items if item.get("exists") and item.get("hash_match") is False ) canonical = next((item for item in items if item.get("role") == "canonical_brd"), None) canonical_ok = bool(canonical and canonical.get("hash_match") is True) historical_0611 = next( ( item for item in items if item.get("path") == HISTORICAL_0611_PDF ), None, ) return { "schema": "prod2u-reference-inventory-v1", "generated_at_utc": datetime.now(timezone.utc).isoformat(), "repository_root": str(root.resolve()), "evidence_boundaries": { "board_viewer_svgs_and_json": ( "Derived analysis evidence from the Allegro BRD via KiCad. " "Not RTL/TD/ADC/bitstream source closure." ), "board_viewer_derived_assets": [ "tools/board-viewer/generated/board-data.json", "tools/board-viewer/generated/build-info.json", "tools/board-viewer/generated/import-report.json", "tools/board-viewer/generated/board-copper.svg", "tools/board-viewer/generated/board-silkscreen.svg", "tools/board-viewer/generated/board-mask-edge.svg", "tools/board-viewer/generated/board-copper-back.svg", "tools/board-viewer/generated/board-silkscreen-back.svg", "tools/board-viewer/generated/board-mask-edge-back.svg", ], "canonical_brd": CANONICAL_BRD, "duplicate_brd_archive": ARCHIVE_BRD, "authoritative_order": [ "v1_2_brd_physical_path_confirmed_by_brd", "product_polarity_confirmed_by_electrical_staff", "hardware_measurement_not_run", ], "historical_schematic_side_evidence": HISTORICAL_0611_PDF, "v1_2_schematic_pdf": { "path": V12_SCHEMATIC_PDF_POLICY_PATH, "status": "not_provided", "confidence": "missing_by_policy", }, "io_evidence_grades": { "physical_path": "confirmed_by_brd", "product_polarity": "confirmed_by_electrical_staff", "hardware_measurement": "not_run", "matrix_doc": "docs/IO_EVIDENCE_MATRIX.zh-CN.md", }, "packaging_recommendation": ( "Compact/review packages: keep the six board-viewer derived assets " "once under tools/board-viewer/generated/ (derived_evidence); do not " "also materialize a second physical copy via external-source staging. " "Do not ship PDF/BRD/DSN in compact. Archive-local / reference may ship " f"one physical BRD at {CANONICAL_BRD}; treat {ARCHIVE_BRD} as a " "local-only mirror. Include 0611 PDF only as " "historical_schematic_side_evidence; it must not override V1.2 " "CON104/105/106/120/12/129 mapping. V1.2 schematic PDF remains " "missing_by_policy/not_provided. BRD regeneration remains local-only / " "not_packaged_by_policy for compact." ), "expected_brd_sha256": EXPECTED_BRD_SHA256, "reference_regeneration_replay": "not_packaged_by_policy", }, "items": items, "board_viewer_build_info": build_info, "summary": { "present": present, "missing": missing, "policy_missing": policy_missing, "hash_ok": hash_ok, "hash_fail": hash_fail, "canonical_brd_hash_ok": canonical_ok, "canonical_brd_present": bool(canonical and canonical.get("exists")), "historical_0611_present": bool( historical_0611 and historical_0611.get("exists") ), "v1_2_schematic_pdf": "missing_by_policy", }, } def render_markdown(inventory: dict[str, Any]) -> str: bounds = inventory.get("evidence_boundaries") or {} summary = inventory.get("summary") or {} grades = bounds.get("io_evidence_grades") or {} v12_pdf = bounds.get("v1_2_schematic_pdf") or {} lines = [ "# Reference Inventory", "", f"Generated: {inventory.get('generated_at_utc')}", "", f"- present: {summary.get('present', 0)}", f"- missing: {summary.get('missing', 0)}", f"- policy_missing: {summary.get('policy_missing', 0)}", f"- hash_ok: {summary.get('hash_ok', 0)}", f"- hash_fail: {summary.get('hash_fail', 0)}", f"- canonical_brd_hash_ok: {summary.get('canonical_brd_hash_ok')}", f"- historical_0611_present: {summary.get('historical_0611_present')}", f"- v1_2_schematic_pdf: {summary.get('v1_2_schematic_pdf')}", "", "## Evidence boundaries", "", f"- Board-viewer JSON/SVG: {bounds.get('board_viewer_svgs_and_json')}", f"- Canonical BRD: `{bounds.get('canonical_brd')}`", f"- Duplicate archive BRD: `{bounds.get('duplicate_brd_archive')}` " "(byte-identical local mirror; packaging should keep one physical copy)", f"- Expected BRD SHA-256: `{bounds.get('expected_brd_sha256')}`", f"- Authoritative order: {', '.join(bounds.get('authoritative_order') or [])}", f"- IO evidence grades: physical_path=`{grades.get('physical_path')}`, " f"product_polarity=`{grades.get('product_polarity')}`, " f"hardware_measurement=`{grades.get('hardware_measurement')}` " f"(see `{grades.get('matrix_doc')}`)", f"- 0611 PDF: `{bounds.get('historical_schematic_side_evidence')}` " "(historical_schematic_side_evidence; must not override V1.2 CON104/105/106/120/12/129)", f"- V1.2 schematic PDF: `{v12_pdf.get('path')}` → " f"{v12_pdf.get('confidence')}/{v12_pdf.get('status')}", f"- Packager recommendation: {bounds.get('packaging_recommendation')}", "", "| Path | Exists | Size | Confidence | Hash notes | Evidence |", "|------|--------|------|------------|------------|----------|", ] for item in inventory.get("items") or []: sha = item.get("sha256") or "" if item.get("hash_match") is True: hash_notes = "MATCH" elif item.get("hash_match") is False: hash_notes = "FAIL" elif item.get("confidence") == "missing_by_policy": hash_notes = "POLICY" elif sha: hash_notes = sha[:16] + "..." else: hash_notes = "-" evidence = item.get("evidence_class") or item.get("role") or "source/reference" lines.append( f"| `{item.get('path')}` | {item.get('exists')} | {item.get('size')} | " f"{item.get('confidence')} | {hash_notes} | {evidence} |" ) lines.append("") return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=ROOT) parser.add_argument( "--json-out", type=Path, default=ROOT / "docs" / "REFERENCE-INVENTORY.json", ) parser.add_argument( "--md-out", type=Path, default=ROOT / "docs" / "REFERENCE-INVENTORY.md", ) args = parser.parse_args(argv) inventory = build_inventory(args.root.resolve()) args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text( json.dumps(inventory, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) args.md_out.write_text(render_markdown(inventory), encoding="utf-8") print(f"wrote {args.json_out}") print(f"wrote {args.md_out}") print(json.dumps(inventory["summary"], ensure_ascii=False)) summary = inventory["summary"] if summary.get("hash_fail", 0) != 0: return 1 if not summary.get("canonical_brd_hash_ok"): return 1 return 0 if __name__ == "__main__": sys.exit(main())