refresh_reference_inventory.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/env python3
  2. """Refresh docs/REFERENCE-INVENTORY.{json,md} from live reference + board-viewer assets."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import sys
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from typing import Any
  11. ROOT = Path(__file__).resolve().parents[2]
  12. EXPECTED_BRD_SHA256 = "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb"
  13. EXPECTED_PDF_SHA256 = "7ebd0dced194338ceb97ff5a0abcee2d9790e7f6e7a90d9d4be7de593dca7eb5"
  14. CANONICAL_BRD = (
  15. "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
  16. "FCB_FPGA+MCU_V1.2_20260717.brd"
  17. )
  18. ARCHIVE_BRD = "reference/original/local_archives/board/FCB_FPGA+MCU_V1.2_20260717.brd"
  19. def sha256_file(path: Path) -> str:
  20. digest = hashlib.sha256()
  21. with path.open("rb") as stream:
  22. while chunk := stream.read(1024 * 1024):
  23. digest.update(chunk)
  24. return digest.hexdigest()
  25. def item_for(
  26. root: Path,
  27. relative: str,
  28. *,
  29. expected_sha256: str | None = None,
  30. confidence: str = "present",
  31. notes: dict[str, Any] | None = None,
  32. ) -> dict[str, Any]:
  33. path = root / relative
  34. payload: dict[str, Any] = {
  35. "path": relative,
  36. "exists": path.is_file(),
  37. "size": path.stat().st_size if path.is_file() else 0,
  38. }
  39. if path.is_file():
  40. payload["sha256"] = sha256_file(path)
  41. if expected_sha256 is not None:
  42. payload["expected_sha256"] = expected_sha256
  43. payload["hash_match"] = bool(
  44. path.is_file() and payload.get("sha256") == expected_sha256
  45. )
  46. payload["confidence"] = (
  47. "confirmed" if payload.get("hash_match") else ("missing" if not path.is_file() else "hash_fail")
  48. )
  49. else:
  50. payload["confidence"] = confidence if path.is_file() else "missing"
  51. if notes:
  52. payload.update(notes)
  53. return payload
  54. def build_inventory(root: Path) -> dict[str, Any]:
  55. generated = root / "tools/board-viewer/generated"
  56. build_info: dict[str, Any] = {}
  57. if (generated / "build-info.json").is_file():
  58. build_info = json.loads((generated / "build-info.json").read_text(encoding="utf-8"))
  59. items = [
  60. item_for(root, "reference/original/MANIFEST.zh-CN.md"),
  61. item_for(
  62. root,
  63. CANONICAL_BRD,
  64. expected_sha256=EXPECTED_BRD_SHA256,
  65. notes={
  66. "role": "canonical_brd",
  67. "packaging_note": (
  68. "Canonical physical BRD for analysis packages; "
  69. "prefer this path over local_archives duplicate"
  70. ),
  71. },
  72. ),
  73. item_for(
  74. root,
  75. ARCHIVE_BRD,
  76. expected_sha256=EXPECTED_BRD_SHA256,
  77. notes={
  78. "role": "duplicate_archive_mirror",
  79. "byte_identical_to_canonical": True,
  80. "packaging_recommendation": (
  81. "Keep one physical copy in analysis packages: include "
  82. f"{CANONICAL_BRD} and omit {ARCHIVE_BRD} (or replace the "
  83. "archive entry with a provenance pointer to the canonical path)."
  84. ),
  85. },
  86. ),
  87. item_for(
  88. root,
  89. "reference/original/schematics/8000高温罩电气图V2.0.pdf",
  90. expected_sha256=EXPECTED_PDF_SHA256,
  91. ),
  92. item_for(root, "reference/original/schematics/FCB_FPGA+MCU0611.pdf"),
  93. item_for(root, "reference/original/diagrams/上位机逻辑.svg"),
  94. item_for(root, "reference/original/diagrams/接长鑫水滴系统.svg"),
  95. item_for(root, "config/board_viewer_annotations.fcb_fpga_mcu_v1_2.json"),
  96. item_for(
  97. root,
  98. "tools/board-viewer/generated/board-data.json",
  99. notes={
  100. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  101. },
  102. ),
  103. item_for(
  104. root,
  105. "tools/board-viewer/generated/build-info.json",
  106. notes={
  107. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  108. },
  109. ),
  110. item_for(
  111. root,
  112. "tools/board-viewer/generated/import-report.json",
  113. notes={
  114. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  115. },
  116. ),
  117. item_for(
  118. root,
  119. "tools/board-viewer/generated/board-copper.svg",
  120. notes={
  121. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  122. "layer": "F.Cu,Edge.Cuts",
  123. },
  124. ),
  125. item_for(
  126. root,
  127. "tools/board-viewer/generated/board-silkscreen.svg",
  128. notes={
  129. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  130. "layer": "F.SilkS,Edge.Cuts",
  131. },
  132. ),
  133. item_for(
  134. root,
  135. "tools/board-viewer/generated/board-mask-edge.svg",
  136. notes={
  137. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  138. "layer": "F.Mask,Edge.Cuts",
  139. },
  140. ),
  141. ]
  142. present = sum(1 for item in items if item.get("exists"))
  143. missing = sum(1 for item in items if not item.get("exists"))
  144. hash_ok = sum(1 for item in items if item.get("hash_match") is True)
  145. # Missing optional/gitignored mirrors are tracked under `missing`, not hash_fail.
  146. hash_fail = sum(
  147. 1 for item in items if item.get("exists") and item.get("hash_match") is False
  148. )
  149. canonical = next((item for item in items if item.get("role") == "canonical_brd"), None)
  150. canonical_ok = bool(canonical and canonical.get("hash_match") is True)
  151. return {
  152. "schema": "prod2u-reference-inventory-v1",
  153. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  154. "repository_root": str(root.resolve()),
  155. "evidence_boundaries": {
  156. "board_viewer_svgs_and_json": (
  157. "Derived analysis evidence from the Allegro BRD via KiCad. "
  158. "Not RTL/TD/ADC/bitstream source closure."
  159. ),
  160. "board_viewer_six_assets": [
  161. "tools/board-viewer/generated/board-data.json",
  162. "tools/board-viewer/generated/build-info.json",
  163. "tools/board-viewer/generated/import-report.json",
  164. "tools/board-viewer/generated/board-copper.svg",
  165. "tools/board-viewer/generated/board-silkscreen.svg",
  166. "tools/board-viewer/generated/board-mask-edge.svg",
  167. ],
  168. "canonical_brd": CANONICAL_BRD,
  169. "duplicate_brd_archive": ARCHIVE_BRD,
  170. "packaging_recommendation": (
  171. "Compact/review packages: keep the six board-viewer derived assets "
  172. "once under tools/board-viewer/generated/ (derived_evidence); do not "
  173. "also materialize a second physical copy via external-source staging. "
  174. "Do not ship PDF/BRD/DSN in compact. Archive-local may ship one physical "
  175. f"BRD at {CANONICAL_BRD}; treat {ARCHIVE_BRD} as a local-only mirror. "
  176. "BRD regeneration remains local-only / not_packaged_by_policy for compact."
  177. ),
  178. "expected_brd_sha256": EXPECTED_BRD_SHA256,
  179. "reference_regeneration_replay": "not_packaged_by_policy",
  180. },
  181. "items": items,
  182. "board_viewer_build_info": build_info,
  183. "summary": {
  184. "present": present,
  185. "missing": missing,
  186. "hash_ok": hash_ok,
  187. "hash_fail": hash_fail,
  188. "canonical_brd_hash_ok": canonical_ok,
  189. },
  190. }
  191. def render_markdown(inventory: dict[str, Any]) -> str:
  192. bounds = inventory.get("evidence_boundaries") or {}
  193. summary = inventory.get("summary") or {}
  194. lines = [
  195. "# Reference Inventory",
  196. "",
  197. f"Generated: {inventory.get('generated_at_utc')}",
  198. "",
  199. f"- present: {summary.get('present', 0)}",
  200. f"- missing: {summary.get('missing', 0)}",
  201. f"- hash_ok: {summary.get('hash_ok', 0)}",
  202. f"- hash_fail: {summary.get('hash_fail', 0)}",
  203. "",
  204. "## Evidence boundaries",
  205. "",
  206. f"- Board-viewer JSON/SVG: {bounds.get('board_viewer_svgs_and_json')}",
  207. f"- Canonical BRD: `{bounds.get('canonical_brd')}`",
  208. f"- Duplicate archive BRD: `{bounds.get('duplicate_brd_archive')}` "
  209. "(byte-identical local mirror; packaging should keep one physical copy)",
  210. f"- Expected BRD SHA-256: `{bounds.get('expected_brd_sha256')}`",
  211. f"- Packager recommendation: {bounds.get('packaging_recommendation')}",
  212. "",
  213. "| Path | Exists | Size | Confidence | Hash notes | Evidence |",
  214. "|------|--------|------|------------|------------|----------|",
  215. ]
  216. for item in inventory.get("items") or []:
  217. sha = item.get("sha256") or ""
  218. if item.get("hash_match") is True:
  219. hash_notes = "MATCH"
  220. elif item.get("hash_match") is False:
  221. hash_notes = "FAIL"
  222. elif sha:
  223. hash_notes = sha[:16] + "..."
  224. else:
  225. hash_notes = "-"
  226. evidence = item.get("evidence_class") or item.get("role") or "source/reference"
  227. lines.append(
  228. f"| `{item.get('path')}` | {item.get('exists')} | {item.get('size')} | "
  229. f"{item.get('confidence')} | {hash_notes} | {evidence} |"
  230. )
  231. lines.append("")
  232. return "\n".join(lines)
  233. def main(argv: list[str] | None = None) -> int:
  234. parser = argparse.ArgumentParser(description=__doc__)
  235. parser.add_argument("--root", type=Path, default=ROOT)
  236. parser.add_argument(
  237. "--json-out",
  238. type=Path,
  239. default=ROOT / "docs" / "REFERENCE-INVENTORY.json",
  240. )
  241. parser.add_argument(
  242. "--md-out",
  243. type=Path,
  244. default=ROOT / "docs" / "REFERENCE-INVENTORY.md",
  245. )
  246. args = parser.parse_args(argv)
  247. inventory = build_inventory(args.root.resolve())
  248. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  249. args.json_out.write_text(
  250. json.dumps(inventory, indent=2, ensure_ascii=False) + "\n",
  251. encoding="utf-8",
  252. )
  253. args.md_out.write_text(render_markdown(inventory), encoding="utf-8")
  254. print(f"wrote {args.json_out}")
  255. print(f"wrote {args.md_out}")
  256. print(json.dumps(inventory["summary"], ensure_ascii=False))
  257. summary = inventory["summary"]
  258. if summary.get("hash_fail", 0) != 0:
  259. return 1
  260. if not summary.get("canonical_brd_hash_ok"):
  261. return 1
  262. return 0
  263. if __name__ == "__main__":
  264. sys.exit(main())