refresh_reference_inventory.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. HISTORICAL_0611_PDF = "reference/original/schematics/FCB_FPGA+MCU0611.pdf"
  20. # Policy placeholder: there is no V1.2 schematic PDF; do not invent a real filename claim.
  21. V12_SCHEMATIC_PDF_POLICY_PATH = (
  22. "reference/original/schematics/FCB_FPGA_MCU_V1.2_schematic.pdf"
  23. )
  24. def sha256_file(path: Path) -> str:
  25. digest = hashlib.sha256()
  26. with path.open("rb") as stream:
  27. while chunk := stream.read(1024 * 1024):
  28. digest.update(chunk)
  29. return digest.hexdigest()
  30. def item_for(
  31. root: Path,
  32. relative: str,
  33. *,
  34. expected_sha256: str | None = None,
  35. confidence: str | None = None,
  36. notes: dict[str, Any] | None = None,
  37. require_file: bool = True,
  38. ) -> dict[str, Any]:
  39. path = root / relative
  40. payload: dict[str, Any] = {
  41. "path": relative,
  42. "exists": path.is_file(),
  43. "size": path.stat().st_size if path.is_file() else 0,
  44. }
  45. if path.is_file():
  46. payload["sha256"] = sha256_file(path)
  47. if expected_sha256 is not None:
  48. payload["expected_sha256"] = expected_sha256
  49. payload["hash_match"] = bool(
  50. path.is_file() and payload.get("sha256") == expected_sha256
  51. )
  52. if confidence is not None:
  53. payload["confidence"] = confidence
  54. else:
  55. payload["confidence"] = (
  56. "confirmed"
  57. if payload.get("hash_match")
  58. else ("missing" if not path.is_file() else "hash_fail")
  59. )
  60. elif confidence is not None:
  61. payload["confidence"] = confidence
  62. else:
  63. payload["confidence"] = (
  64. "present" if path.is_file() else ("missing" if require_file else "not_provided")
  65. )
  66. if notes:
  67. payload.update(notes)
  68. return payload
  69. def policy_missing_item(
  70. relative: str,
  71. *,
  72. role: str,
  73. evidence_class: str,
  74. notes: dict[str, Any] | None = None,
  75. ) -> dict[str, Any]:
  76. """Inventory row for an asset that is intentionally absent (policy / not provided)."""
  77. payload: dict[str, Any] = {
  78. "path": relative,
  79. "exists": False,
  80. "size": 0,
  81. "confidence": "missing_by_policy",
  82. "status": "not_provided",
  83. "role": role,
  84. "evidence_class": evidence_class,
  85. }
  86. if notes:
  87. payload.update(notes)
  88. return payload
  89. def build_inventory(root: Path) -> dict[str, Any]:
  90. generated = root / "tools/board-viewer/generated"
  91. build_info: dict[str, Any] = {}
  92. if (generated / "build-info.json").is_file():
  93. build_info = json.loads((generated / "build-info.json").read_text(encoding="utf-8"))
  94. items = [
  95. item_for(root, "reference/original/MANIFEST.zh-CN.md"),
  96. item_for(
  97. root,
  98. CANONICAL_BRD,
  99. expected_sha256=EXPECTED_BRD_SHA256,
  100. notes={
  101. "role": "canonical_brd",
  102. "evidence_class": "authoritative_physical_board_database",
  103. "authority": "v1_2_physical_path",
  104. "packaging_note": (
  105. "Canonical physical BRD for analysis packages; "
  106. "prefer this path over local_archives duplicate"
  107. ),
  108. },
  109. ),
  110. item_for(
  111. root,
  112. ARCHIVE_BRD,
  113. expected_sha256=EXPECTED_BRD_SHA256,
  114. notes={
  115. "role": "duplicate_archive_mirror",
  116. "evidence_class": "authoritative_physical_board_database_mirror",
  117. "byte_identical_to_canonical": True,
  118. "packaging_recommendation": (
  119. "Keep one physical copy in analysis packages: include "
  120. f"{CANONICAL_BRD} and omit {ARCHIVE_BRD} (or replace the "
  121. "archive entry with a provenance pointer to the canonical path)."
  122. ),
  123. },
  124. ),
  125. item_for(
  126. root,
  127. "reference/original/schematics/8000高温罩电气图V2.0.pdf",
  128. expected_sha256=EXPECTED_PDF_SHA256,
  129. notes={
  130. "role": "system_electrical_boundary_pdf",
  131. "evidence_class": "system_schematic_reference",
  132. },
  133. ),
  134. item_for(
  135. root,
  136. HISTORICAL_0611_PDF,
  137. notes={
  138. "role": "historical_schematic_side_evidence",
  139. "evidence_class": "historical_schematic_side_evidence",
  140. "authority": "non_authoritative_for_v1_2_product_io",
  141. "must_not_override": [
  142. "CON104",
  143. "CON105",
  144. "CON106",
  145. "CON120",
  146. "CON12",
  147. "CON129",
  148. ],
  149. "notes": (
  150. "Earlier FCB FPGA+MCU schematic PDF (not the 20260717 V1.2 board "
  151. "revision). May help with legacy net names / old sheets only; "
  152. "must not override V1.2 BRD activity mapping for motor/limit/EN."
  153. ),
  154. },
  155. ),
  156. policy_missing_item(
  157. V12_SCHEMATIC_PDF_POLICY_PATH,
  158. role="v1_2_schematic_pdf",
  159. evidence_class="missing_by_policy",
  160. notes={
  161. "status": "not_provided",
  162. "authority": "none",
  163. "notes": (
  164. "No V1.2 schematic PDF was provided. Do not invent one and do not "
  165. "treat FCB_FPGA+MCU0611.pdf as a V1.2 schematic substitute."
  166. ),
  167. },
  168. ),
  169. item_for(root, "reference/original/diagrams/上位机逻辑.svg"),
  170. item_for(root, "reference/original/diagrams/接长鑫水滴系统.svg"),
  171. item_for(
  172. root,
  173. "config/board_viewer_annotations.fcb_fpga_mcu_v1_2.json",
  174. notes={
  175. "role": "v1_2_curated_annotations",
  176. "evidence_class": "curated_annotation_for_v1_2_brd",
  177. },
  178. ),
  179. item_for(
  180. root,
  181. "config/pin_inventory.fcb_fpga_mcu0611.json",
  182. notes={
  183. "role": "historical_schematic_side_evidence",
  184. "evidence_class": "historical_schematic_side_evidence",
  185. "authority": "non_authoritative_for_v1_2_product_io",
  186. "must_not_override": [
  187. "CON104",
  188. "CON105",
  189. "CON106",
  190. "CON120",
  191. "CON12",
  192. "CON129",
  193. ],
  194. },
  195. ),
  196. item_for(
  197. root,
  198. "config/pin_inventory.prod2u_door_temp_v1_2.json",
  199. notes={
  200. "role": "v1_2_product_interface_evidence",
  201. "evidence_class": "product_io_evidence_summary",
  202. },
  203. ),
  204. item_for(
  205. root,
  206. "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  207. notes={
  208. "role": "io_evidence_matrix",
  209. "evidence_class": "split_evidence_grades_physical_polarity_measurement",
  210. },
  211. ),
  212. item_for(
  213. root,
  214. "tools/board-viewer/generated/board-data.json",
  215. notes={
  216. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  217. },
  218. ),
  219. item_for(
  220. root,
  221. "tools/board-viewer/generated/build-info.json",
  222. notes={
  223. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  224. },
  225. ),
  226. item_for(
  227. root,
  228. "tools/board-viewer/generated/import-report.json",
  229. notes={
  230. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  231. },
  232. ),
  233. item_for(
  234. root,
  235. "tools/board-viewer/generated/board-copper.svg",
  236. notes={
  237. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  238. "layer": "F.Cu,Edge.Cuts",
  239. },
  240. ),
  241. item_for(
  242. root,
  243. "tools/board-viewer/generated/board-silkscreen.svg",
  244. notes={
  245. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  246. "layer": "F.SilkS,Edge.Cuts",
  247. },
  248. ),
  249. item_for(
  250. root,
  251. "tools/board-viewer/generated/board-mask-edge.svg",
  252. notes={
  253. "evidence_class": "derived_analysis_from_brd_not_rtl_td_source_closure",
  254. "layer": "F.Mask,Edge.Cuts",
  255. },
  256. ),
  257. ]
  258. present = sum(1 for item in items if item.get("exists"))
  259. # Policy-missing rows are intentional absences, not inventory gaps.
  260. missing = sum(
  261. 1
  262. for item in items
  263. if not item.get("exists") and item.get("confidence") != "missing_by_policy"
  264. )
  265. policy_missing = sum(
  266. 1 for item in items if item.get("confidence") == "missing_by_policy"
  267. )
  268. hash_ok = sum(1 for item in items if item.get("hash_match") is True)
  269. # Missing optional/gitignored mirrors are tracked under `missing`, not hash_fail.
  270. hash_fail = sum(
  271. 1 for item in items if item.get("exists") and item.get("hash_match") is False
  272. )
  273. canonical = next((item for item in items if item.get("role") == "canonical_brd"), None)
  274. canonical_ok = bool(canonical and canonical.get("hash_match") is True)
  275. historical_0611 = next(
  276. (
  277. item
  278. for item in items
  279. if item.get("path") == HISTORICAL_0611_PDF
  280. ),
  281. None,
  282. )
  283. return {
  284. "schema": "prod2u-reference-inventory-v1",
  285. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  286. "repository_root": str(root.resolve()),
  287. "evidence_boundaries": {
  288. "board_viewer_svgs_and_json": (
  289. "Derived analysis evidence from the Allegro BRD via KiCad. "
  290. "Not RTL/TD/ADC/bitstream source closure."
  291. ),
  292. "board_viewer_six_assets": [
  293. "tools/board-viewer/generated/board-data.json",
  294. "tools/board-viewer/generated/build-info.json",
  295. "tools/board-viewer/generated/import-report.json",
  296. "tools/board-viewer/generated/board-copper.svg",
  297. "tools/board-viewer/generated/board-silkscreen.svg",
  298. "tools/board-viewer/generated/board-mask-edge.svg",
  299. ],
  300. "canonical_brd": CANONICAL_BRD,
  301. "duplicate_brd_archive": ARCHIVE_BRD,
  302. "authoritative_order": [
  303. "v1_2_brd_physical_path_confirmed_by_brd",
  304. "product_polarity_confirmed_by_electrical_staff",
  305. "hardware_measurement_not_run",
  306. ],
  307. "historical_schematic_side_evidence": HISTORICAL_0611_PDF,
  308. "v1_2_schematic_pdf": {
  309. "path": V12_SCHEMATIC_PDF_POLICY_PATH,
  310. "status": "not_provided",
  311. "confidence": "missing_by_policy",
  312. },
  313. "io_evidence_grades": {
  314. "physical_path": "confirmed_by_brd",
  315. "product_polarity": "confirmed_by_electrical_staff",
  316. "hardware_measurement": "not_run",
  317. "matrix_doc": "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  318. },
  319. "packaging_recommendation": (
  320. "Compact/review packages: keep the six board-viewer derived assets "
  321. "once under tools/board-viewer/generated/ (derived_evidence); do not "
  322. "also materialize a second physical copy via external-source staging. "
  323. "Do not ship PDF/BRD/DSN in compact. Archive-local / reference may ship "
  324. f"one physical BRD at {CANONICAL_BRD}; treat {ARCHIVE_BRD} as a "
  325. "local-only mirror. Include 0611 PDF only as "
  326. "historical_schematic_side_evidence; it must not override V1.2 "
  327. "CON104/105/106/120/12/129 mapping. V1.2 schematic PDF remains "
  328. "missing_by_policy/not_provided. BRD regeneration remains local-only / "
  329. "not_packaged_by_policy for compact."
  330. ),
  331. "expected_brd_sha256": EXPECTED_BRD_SHA256,
  332. "reference_regeneration_replay": "not_packaged_by_policy",
  333. },
  334. "items": items,
  335. "board_viewer_build_info": build_info,
  336. "summary": {
  337. "present": present,
  338. "missing": missing,
  339. "policy_missing": policy_missing,
  340. "hash_ok": hash_ok,
  341. "hash_fail": hash_fail,
  342. "canonical_brd_hash_ok": canonical_ok,
  343. "canonical_brd_present": bool(canonical and canonical.get("exists")),
  344. "historical_0611_present": bool(
  345. historical_0611 and historical_0611.get("exists")
  346. ),
  347. "v1_2_schematic_pdf": "missing_by_policy",
  348. },
  349. }
  350. def render_markdown(inventory: dict[str, Any]) -> str:
  351. bounds = inventory.get("evidence_boundaries") or {}
  352. summary = inventory.get("summary") or {}
  353. grades = bounds.get("io_evidence_grades") or {}
  354. v12_pdf = bounds.get("v1_2_schematic_pdf") or {}
  355. lines = [
  356. "# Reference Inventory",
  357. "",
  358. f"Generated: {inventory.get('generated_at_utc')}",
  359. "",
  360. f"- present: {summary.get('present', 0)}",
  361. f"- missing: {summary.get('missing', 0)}",
  362. f"- policy_missing: {summary.get('policy_missing', 0)}",
  363. f"- hash_ok: {summary.get('hash_ok', 0)}",
  364. f"- hash_fail: {summary.get('hash_fail', 0)}",
  365. f"- canonical_brd_hash_ok: {summary.get('canonical_brd_hash_ok')}",
  366. f"- historical_0611_present: {summary.get('historical_0611_present')}",
  367. f"- v1_2_schematic_pdf: {summary.get('v1_2_schematic_pdf')}",
  368. "",
  369. "## Evidence boundaries",
  370. "",
  371. f"- Board-viewer JSON/SVG: {bounds.get('board_viewer_svgs_and_json')}",
  372. f"- Canonical BRD: `{bounds.get('canonical_brd')}`",
  373. f"- Duplicate archive BRD: `{bounds.get('duplicate_brd_archive')}` "
  374. "(byte-identical local mirror; packaging should keep one physical copy)",
  375. f"- Expected BRD SHA-256: `{bounds.get('expected_brd_sha256')}`",
  376. f"- Authoritative order: {', '.join(bounds.get('authoritative_order') or [])}",
  377. f"- IO evidence grades: physical_path=`{grades.get('physical_path')}`, "
  378. f"product_polarity=`{grades.get('product_polarity')}`, "
  379. f"hardware_measurement=`{grades.get('hardware_measurement')}` "
  380. f"(see `{grades.get('matrix_doc')}`)",
  381. f"- 0611 PDF: `{bounds.get('historical_schematic_side_evidence')}` "
  382. "(historical_schematic_side_evidence; must not override V1.2 CON104/105/106/120/12/129)",
  383. f"- V1.2 schematic PDF: `{v12_pdf.get('path')}` → "
  384. f"{v12_pdf.get('confidence')}/{v12_pdf.get('status')}",
  385. f"- Packager recommendation: {bounds.get('packaging_recommendation')}",
  386. "",
  387. "| Path | Exists | Size | Confidence | Hash notes | Evidence |",
  388. "|------|--------|------|------------|------------|----------|",
  389. ]
  390. for item in inventory.get("items") or []:
  391. sha = item.get("sha256") or ""
  392. if item.get("hash_match") is True:
  393. hash_notes = "MATCH"
  394. elif item.get("hash_match") is False:
  395. hash_notes = "FAIL"
  396. elif item.get("confidence") == "missing_by_policy":
  397. hash_notes = "POLICY"
  398. elif sha:
  399. hash_notes = sha[:16] + "..."
  400. else:
  401. hash_notes = "-"
  402. evidence = item.get("evidence_class") or item.get("role") or "source/reference"
  403. lines.append(
  404. f"| `{item.get('path')}` | {item.get('exists')} | {item.get('size')} | "
  405. f"{item.get('confidence')} | {hash_notes} | {evidence} |"
  406. )
  407. lines.append("")
  408. return "\n".join(lines)
  409. def main(argv: list[str] | None = None) -> int:
  410. parser = argparse.ArgumentParser(description=__doc__)
  411. parser.add_argument("--root", type=Path, default=ROOT)
  412. parser.add_argument(
  413. "--json-out",
  414. type=Path,
  415. default=ROOT / "docs" / "REFERENCE-INVENTORY.json",
  416. )
  417. parser.add_argument(
  418. "--md-out",
  419. type=Path,
  420. default=ROOT / "docs" / "REFERENCE-INVENTORY.md",
  421. )
  422. args = parser.parse_args(argv)
  423. inventory = build_inventory(args.root.resolve())
  424. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  425. args.json_out.write_text(
  426. json.dumps(inventory, indent=2, ensure_ascii=False) + "\n",
  427. encoding="utf-8",
  428. )
  429. args.md_out.write_text(render_markdown(inventory), encoding="utf-8")
  430. print(f"wrote {args.json_out}")
  431. print(f"wrote {args.md_out}")
  432. print(json.dumps(inventory["summary"], ensure_ascii=False))
  433. summary = inventory["summary"]
  434. if summary.get("hash_fail", 0) != 0:
  435. return 1
  436. if not summary.get("canonical_brd_hash_ok"):
  437. return 1
  438. return 0
  439. if __name__ == "__main__":
  440. sys.exit(main())