generate_candidate_expectation.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python3
  2. """Regenerate curated candidate-count expectation from live board-data/build-info."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import subprocess
  8. import sys
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parents[2]
  11. VIEWER = ROOT / "tools" / "board-viewer"
  12. GENERATED = VIEWER / "generated"
  13. DEFAULT_OUT = ROOT / "tests" / "board_viewer" / "fixtures" / "candidate_count_expectation.json"
  14. CAPABILITIES = (
  15. "gpio",
  16. "pwm",
  17. "gpio_output",
  18. "gpio_input",
  19. "tach",
  20. "presence",
  21. "uart_tx",
  22. )
  23. def sha256_file(path: Path) -> str:
  24. return hashlib.sha256(path.read_bytes()).hexdigest()
  25. def _run_node(board_data: Path) -> tuple[dict[str, int], dict[str, list[str]]]:
  26. board_data_js = json.dumps(str(board_data))
  27. logic_js = json.dumps(str(VIEWER / "web" / "board-logic.mjs"))
  28. caps_js = json.dumps(list(CAPABILITIES))
  29. script = (
  30. "import {readFileSync} from 'node:fs';"
  31. f"import {{findCandidates}} from {logic_js};"
  32. f"const data = JSON.parse(readFileSync({board_data_js}, 'utf8'));"
  33. f"const caps = {caps_js};"
  34. "const candidate_counts = {};"
  35. "const candidate_keys = {};"
  36. "for (const cap of caps) {"
  37. " const c = findCandidates(data, cap);"
  38. " candidate_counts[cap] = c.length;"
  39. " candidate_keys[cap] = c.map((item) => `${item.reference}.${item.pin.number}`);"
  40. "}"
  41. "process.stdout.write(JSON.stringify({candidate_counts, candidate_keys}));"
  42. )
  43. result = subprocess.run(
  44. ["node", "--input-type=module", "--eval", script],
  45. cwd=str(ROOT),
  46. check=True,
  47. capture_output=True,
  48. text=True,
  49. )
  50. payload = json.loads(result.stdout)
  51. return payload["candidate_counts"], payload["candidate_keys"]
  52. def build_expectation() -> dict:
  53. board_data = GENERATED / "board-data.json"
  54. build_info = GENERATED / "build-info.json"
  55. if not board_data.is_file() or not build_info.is_file():
  56. raise SystemExit("generated board-data.json and build-info.json are required")
  57. info = json.loads(build_info.read_text(encoding="utf-8"))
  58. data = json.loads(board_data.read_text(encoding="utf-8"))
  59. counts, keys = _run_node(board_data)
  60. pin_count = sum(len(touchpoint.get("pins") or []) for touchpoint in data.get("touchpoints") or [])
  61. return {
  62. "schema": "prod2u-board-viewer-candidate-count-expectation-v1",
  63. "description": (
  64. "Curated fail-closed candidate counts bound to generated board-data/build-info digests. "
  65. "Do not relax cross_verified/power/ground/reserved/fixed-load blockers to match counts."
  66. ),
  67. "bound_to": {
  68. "board_data_path": "tools/board-viewer/generated/board-data.json",
  69. "board_data_sha256": sha256_file(board_data),
  70. "build_info_path": "tools/board-viewer/generated/build-info.json",
  71. "build_info_sha256": sha256_file(build_info),
  72. "board_data_asset_sha256": info["assets"]["board-data.json"]["sha256"],
  73. "brd_sha256": info["sources"]["brd"]["sha256"],
  74. },
  75. "candidate_counts": counts,
  76. "candidate_keys": keys,
  77. "ui_counts": {
  78. "touchpoints": len(data.get("touchpoints") or []),
  79. "pins": pin_count,
  80. },
  81. "blockers_must_remain": [
  82. "unverified_or_non_cross_verified",
  83. "power",
  84. "ground",
  85. "reserved",
  86. "fixed_load_conflict",
  87. "mechanical_or_non_electrical",
  88. "unknown_pad_role",
  89. ],
  90. }
  91. def main() -> int:
  92. parser = argparse.ArgumentParser(description=__doc__)
  93. parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
  94. parser.add_argument("--check", action="store_true", help="verify existing expectation instead of writing")
  95. args = parser.parse_args()
  96. expectation = build_expectation()
  97. if args.check:
  98. existing = json.loads(args.out.read_text(encoding="utf-8"))
  99. if existing != expectation:
  100. print("candidate expectation drift detected", file=sys.stderr)
  101. return 1
  102. print("candidate expectation: pass")
  103. return 0
  104. args.out.parent.mkdir(parents=True, exist_ok=True)
  105. args.out.write_text(json.dumps(expectation, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  106. print(f"wrote {args.out}")
  107. print(json.dumps(expectation["candidate_counts"], indent=2))
  108. return 0
  109. if __name__ == "__main__":
  110. raise SystemExit(main())