fw_cli.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #!/usr/bin/env python3
  2. """Minimal multi-target firmware entry. Users remember: target + action."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import signal
  10. import subprocess
  11. import sys
  12. import tempfile
  13. from pathlib import Path
  14. ROOT = Path(__file__).resolve().parents[1]
  15. if str(ROOT) not in sys.path:
  16. sys.path.insert(0, str(ROOT))
  17. from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line
  18. from tools.generate_target import generate_named_target
  19. from tools.target_registry import TargetError, release_blocked, resolve_target
  20. def _configure_worktree_git() -> None:
  21. """Point Linux git at the Windows worktree gitdir when `.git` is a pointer file."""
  22. git_file = ROOT / ".git"
  23. if git_file.is_dir() or os.environ.get("GIT_DIR"):
  24. return
  25. if not git_file.is_file():
  26. return
  27. raw = git_file.read_text(encoding="utf-8").strip()
  28. if not raw.lower().startswith("gitdir:"):
  29. return
  30. gitdir = raw.split(":", 1)[1].strip()
  31. candidates = [Path(gitdir)]
  32. posix = gitdir.replace("\\", "/")
  33. match = re.search(r"/Agentworkspace/(.+)$", posix)
  34. if match:
  35. candidates.append(Path("/root/Agentworkspace") / match.group(1))
  36. for candidate in candidates:
  37. if candidate.is_dir():
  38. os.environ["GIT_DIR"] = str(candidate)
  39. os.environ["GIT_WORK_TREE"] = str(ROOT)
  40. return
  41. def _external_run_root(name: str) -> Path:
  42. base = Path(os.environ.get("XDG_STATE_HOME") or tempfile.gettempdir()) / "prod2u" / "fw" / name
  43. base.mkdir(parents=True, exist_ok=True)
  44. return base
  45. def _die(message: str, code: int = 2) -> int:
  46. print(message, file=sys.stderr)
  47. return code
  48. def cmd_list(_args: argparse.Namespace) -> int:
  49. for alias in list_aliases(ROOT):
  50. print(target_status_line(alias, ROOT))
  51. return 0
  52. def _generate_one(alias: str) -> None:
  53. generate_named_target(alias)
  54. def cmd_generate(args: argparse.Namespace) -> int:
  55. try:
  56. _generate_one(args.target)
  57. except (TargetError, ValueError) as exc:
  58. return _die(str(exc), 2)
  59. print(f"generated {args.target}")
  60. return 0
  61. def _python() -> str:
  62. for candidate in (
  63. os.environ.get("PRODU2_VERIFY_PYTHON"),
  64. "/data/prod2u/venvs/verify/bin/python",
  65. "/data/prod2u/bin/python3",
  66. sys.executable,
  67. ):
  68. if not candidate:
  69. continue
  70. path = Path(candidate)
  71. if not path.is_file():
  72. continue
  73. probe = subprocess.run(
  74. [str(path), "-c", "import pytest"],
  75. stdout=subprocess.DEVNULL,
  76. stderr=subprocess.DEVNULL,
  77. check=False,
  78. )
  79. if probe.returncode == 0:
  80. return str(path)
  81. return sys.executable
  82. def cmd_build(args: argparse.Namespace) -> int:
  83. try:
  84. target = resolve_target(args.target)
  85. _generate_one(target.alias)
  86. blocked, pins = release_blocked(target)
  87. except (TargetError, ValueError) as exc:
  88. return _die(str(exc), 2)
  89. if blocked:
  90. lines = [f"{name} pin unresolved" for name in pins]
  91. return _die("\n".join(lines) + "\nproduction build blocked: bitstream_not_releaseable", 3)
  92. if target.alias == "6400":
  93. return _die(
  94. "6400 build artifact lookup is disabled; use run_6400_td.py with an explicit "
  95. "profile, then package with the commit-bound --td-receipt",
  96. 3,
  97. )
  98. if target.alias != "mrdimm":
  99. return _die(f"production TD for {target.alias} is not wired", 3)
  100. return _run_mrdimm_matrix("td")
  101. def _run_mrdimm_matrix(lanes: str) -> int:
  102. _configure_worktree_git()
  103. work = _external_run_root(f"mrdimm-{lanes.replace(',', '_')}")
  104. report = work / "report.json"
  105. return subprocess.call(
  106. [
  107. _python(),
  108. "-B",
  109. str(ROOT / "tools" / "run_verification_matrix.py"),
  110. "--run-root",
  111. str(work / "work"),
  112. "--report-file",
  113. str(report),
  114. "--lanes",
  115. lanes,
  116. ],
  117. cwd=str(ROOT),
  118. )
  119. def _run_6400_verify() -> int:
  120. # The former run_6400_v1.py suite is historical and imports retired
  121. # modules. Use the current product-scoped verifier for both hosts.
  122. action = "unit"
  123. env = os.environ.copy()
  124. env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
  125. env.setdefault(
  126. "PYTHONPYCACHEPREFIX",
  127. str(_external_run_root("python-cache")),
  128. )
  129. return subprocess.call(
  130. [
  131. _python(),
  132. "-B",
  133. str(ROOT / "tools" / "run_6400_verify.py"),
  134. action,
  135. ],
  136. cwd=str(ROOT),
  137. env=env,
  138. )
  139. def cmd_test(args: argparse.Namespace) -> int:
  140. try:
  141. if args.target != "all":
  142. resolve_dict(args.target, ROOT)
  143. resolve_target(args.target)
  144. except (TargetError, ValueError) as exc:
  145. return _die(str(exc), 2)
  146. codes: list[int] = []
  147. if args.target in ("6400", "all"):
  148. try:
  149. _generate_one("6400")
  150. except (TargetError, ValueError) as exc:
  151. return _die(str(exc), 2)
  152. codes.append(_run_6400_verify())
  153. if args.target in ("mrdimm", "all"):
  154. try:
  155. _generate_one("mrdimm")
  156. except (TargetError, ValueError) as exc:
  157. return _die(str(exc), 2)
  158. if sys.platform == "win32":
  159. focused = [
  160. "tests/unit/test_multiproject_targets.py",
  161. "tests/unit/test_three_axis_door_contract.py",
  162. "tests/unit/test_project_generation.py",
  163. "tests/unit/test_protocol.py",
  164. "tests/unit/test_6400_contract.py",
  165. "tests/unit/test_6400_closure_separation.py",
  166. "tests/unit/test_6400_canonical_packages.py",
  167. ]
  168. codes.append(
  169. subprocess.call(
  170. [_python(), "-B", "-m", "pytest", *focused, "-q", "--tb=short"],
  171. cwd=str(ROOT),
  172. )
  173. )
  174. else:
  175. codes.append(_run_mrdimm_matrix("python,icarus,verilator,cocotb,formal"))
  176. if not codes:
  177. return 2
  178. return next((code for code in codes if code not in (0,)), 0)
  179. def cmd_package(args: argparse.Namespace) -> int:
  180. try:
  181. target = resolve_target(args.target)
  182. _generate_one(target.alias)
  183. blocked, pins = release_blocked(target)
  184. except (TargetError, ValueError) as exc:
  185. return _die(str(exc), 2)
  186. if args.kind == "firmware" and blocked:
  187. return _die(
  188. "firmware package blocked: release_blocked unresolved pins: " + ", ".join(pins),
  189. 3,
  190. )
  191. from tools.package_target import build_target_package
  192. path = build_target_package(
  193. target.alias,
  194. args.kind,
  195. ROOT / "dist",
  196. profile_name=args.profile,
  197. td_receipt=args.td_receipt,
  198. )
  199. print(path)
  200. return 0
  201. def cmd_diagnose(args: argparse.Namespace) -> int:
  202. """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
  203. if sys.platform != "linux":
  204. return _die("Run RTL diagnostics in the authorized LAN Linux container")
  205. out = args.run_root.resolve()
  206. if out == ROOT or ROOT in out.parents:
  207. return _die("--run-root must be outside the source checkout")
  208. out.mkdir(parents=True, exist_ok=False)
  209. products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,)
  210. tests = {
  211. "6400-front-rear": ("frame_rx_tb", "prod2u_6400_uart_e2e_tb"),
  212. "mrdimm-chamber": ("motor_axis_contract_tb", "motor_engine_tb", "motor_event_ring_tb", "prod2u_mrdimm_uart_e2e_tb"),
  213. }
  214. receipt = {"scope": "migration-diagnostic-only", "run_id": out.name,
  215. "hardware": "NOT_RUN", "results": [], "inputs": {}}
  216. receipt["commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
  217. receipt["tree"] = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=ROOT, text=True).strip()
  218. for tool, flag in (("iverilog", "-V"), ("vvp", "-V")):
  219. receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0]
  220. def execute(name: str, command: list[str], marker: str | None = None) -> bool:
  221. log_path = out / (name + ".log")
  222. with log_path.open("w", encoding="utf-8") as log:
  223. log.write(json.dumps(command) + "\n"); log.flush()
  224. process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
  225. try:
  226. code = process.wait(timeout=args.timeout)
  227. except subprocess.TimeoutExpired:
  228. os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
  229. observed = log_path.read_text(errors="replace")
  230. passed = code == 0 and (marker is None or marker in observed)
  231. receipt["results"].append({"name": name, "command": command, "exit_code": code,
  232. "status": "PASS" if passed else "FAIL", "required_marker": marker,
  233. "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
  234. receipt["status"] = "PASS" if all(x["status"] == "PASS" for x in receipt["results"]) else "FAIL"
  235. (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
  236. print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
  237. return passed
  238. for product in products:
  239. manifest_path = ROOT / "products" / product / "source-closure.json"
  240. manifest = json.loads(manifest_path.read_text())
  241. sources = manifest["sources"]
  242. benches = tests[product]
  243. contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"]
  244. input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches])
  245. input_paths.add(manifest_path.relative_to(ROOT).as_posix())
  246. # Include transitive generated headers imported by the mailbox.
  247. input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh"))
  248. input_paths.add("tools/fw_cli.py")
  249. if product == "6400-front-rear":
  250. input_paths.add("src/modules/double_bank_target_store.v")
  251. receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)}
  252. source_args = [p for p in sources if p.endswith(".v")]
  253. for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]:
  254. binary = out / (top + ".vvp")
  255. argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args]
  256. if behavior:
  257. argv.append(f"tests/sim/{top}.v")
  258. if top == "prod2u_6400_uart_e2e_tb":
  259. argv.append("src/modules/double_bank_target_store.v")
  260. if execute(top + "-compile", argv) and behavior:
  261. execute(top, ["vvp", str(binary)], top + " PASS")
  262. return 0 if receipt["status"] == "PASS" else 1
  263. def main(argv: list[str] | None = None) -> int:
  264. parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry")
  265. sub = parser.add_subparsers(dest="command", required=True)
  266. sub.add_parser("list")
  267. gen = sub.add_parser("generate")
  268. gen.add_argument("target")
  269. tes = sub.add_parser("test")
  270. tes.add_argument("target")
  271. diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
  272. diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber"))
  273. diag.add_argument("--run-root", type=Path, required=True)
  274. diag.add_argument("--timeout", type=int, default=60)
  275. bld = sub.add_parser("build")
  276. bld.add_argument("target")
  277. pkg = sub.add_parser("package")
  278. pkg.add_argument("target")
  279. pkg.add_argument("--kind", default="source", choices=("source", "review", "firmware"))
  280. pkg.add_argument(
  281. "--profile",
  282. choices=("6400-front-rear",),
  283. )
  284. pkg.add_argument("--td-receipt", type=Path)
  285. args = parser.parse_args(argv)
  286. commands = {
  287. "list": cmd_list,
  288. "generate": cmd_generate,
  289. "test": cmd_test,
  290. "diagnose": cmd_diagnose,
  291. "build": cmd_build,
  292. "package": cmd_package,
  293. }
  294. try:
  295. return commands[args.command](args)
  296. except SystemExit as exc:
  297. return int(exc.code or 0)
  298. except (TargetError, ValueError) as exc:
  299. return _die(str(exc), 2)
  300. if __name__ == "__main__":
  301. _configure_worktree_git()
  302. load_registry(ROOT)
  303. raise SystemExit(main())