| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- #!/usr/bin/env python3
- """Minimal multi-target firmware entry. Users remember: target + action."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- import re
- import signal
- import subprocess
- import sys
- import tempfile
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line
- from tools.generate_target import generate_named_target
- from tools.target_registry import TargetError, release_blocked, resolve_target
- def _configure_worktree_git() -> None:
- """Point Linux git at the Windows worktree gitdir when `.git` is a pointer file."""
- git_file = ROOT / ".git"
- if git_file.is_dir() or os.environ.get("GIT_DIR"):
- return
- if not git_file.is_file():
- return
- raw = git_file.read_text(encoding="utf-8").strip()
- if not raw.lower().startswith("gitdir:"):
- return
- gitdir = raw.split(":", 1)[1].strip()
- candidates = [Path(gitdir)]
- posix = gitdir.replace("\\", "/")
- match = re.search(r"/Agentworkspace/(.+)$", posix)
- if match:
- candidates.append(Path("/root/Agentworkspace") / match.group(1))
- for candidate in candidates:
- if candidate.is_dir():
- os.environ["GIT_DIR"] = str(candidate)
- os.environ["GIT_WORK_TREE"] = str(ROOT)
- return
- def _external_run_root(name: str) -> Path:
- base = Path(os.environ.get("XDG_STATE_HOME") or tempfile.gettempdir()) / "prod2u" / "fw" / name
- base.mkdir(parents=True, exist_ok=True)
- return base
- def _die(message: str, code: int = 2) -> int:
- print(message, file=sys.stderr)
- return code
- def cmd_list(_args: argparse.Namespace) -> int:
- for alias in list_aliases(ROOT):
- print(target_status_line(alias, ROOT))
- return 0
- def _generate_one(alias: str) -> None:
- generate_named_target(alias)
- def cmd_generate(args: argparse.Namespace) -> int:
- try:
- _generate_one(args.target)
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- print(f"generated {args.target}")
- return 0
- def _python() -> str:
- for candidate in (
- os.environ.get("PRODU2_VERIFY_PYTHON"),
- "/data/prod2u/venvs/verify/bin/python",
- "/data/prod2u/bin/python3",
- sys.executable,
- ):
- if not candidate:
- continue
- path = Path(candidate)
- if not path.is_file():
- continue
- probe = subprocess.run(
- [str(path), "-c", "import pytest"],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- check=False,
- )
- if probe.returncode == 0:
- return str(path)
- return sys.executable
- def cmd_build(args: argparse.Namespace) -> int:
- try:
- target = resolve_target(args.target)
- _generate_one(target.alias)
- blocked, pins = release_blocked(target)
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- if blocked:
- lines = [f"{name} pin unresolved" for name in pins]
- return _die("\n".join(lines) + "\nproduction build blocked: bitstream_not_releaseable", 3)
- if target.alias == "6400":
- return _die(
- "6400 build artifact lookup is disabled; use run_6400_td.py with an explicit "
- "profile, then package with the commit-bound --td-receipt",
- 3,
- )
- if target.alias != "mrdimm":
- return _die(f"production TD for {target.alias} is not wired", 3)
- return _run_mrdimm_matrix("td")
- def _run_mrdimm_matrix(lanes: str) -> int:
- _configure_worktree_git()
- work = _external_run_root(f"mrdimm-{lanes.replace(',', '_')}")
- report = work / "report.json"
- return subprocess.call(
- [
- _python(),
- "-B",
- str(ROOT / "tools" / "run_verification_matrix.py"),
- "--run-root",
- str(work / "work"),
- "--report-file",
- str(report),
- "--lanes",
- lanes,
- ],
- cwd=str(ROOT),
- )
- def _run_6400_verify() -> int:
- # The former run_6400_v1.py suite is historical and imports retired
- # modules. Use the current product-scoped verifier for both hosts.
- action = "unit"
- env = os.environ.copy()
- env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
- env.setdefault(
- "PYTHONPYCACHEPREFIX",
- str(_external_run_root("python-cache")),
- )
- return subprocess.call(
- [
- _python(),
- "-B",
- str(ROOT / "tools" / "run_6400_verify.py"),
- action,
- ],
- cwd=str(ROOT),
- env=env,
- )
- def cmd_test(args: argparse.Namespace) -> int:
- try:
- if args.target != "all":
- resolve_dict(args.target, ROOT)
- resolve_target(args.target)
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- codes: list[int] = []
- if args.target in ("6400", "all"):
- try:
- _generate_one("6400")
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- codes.append(_run_6400_verify())
- if args.target in ("mrdimm", "all"):
- try:
- _generate_one("mrdimm")
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- if sys.platform == "win32":
- focused = [
- "tests/unit/test_multiproject_targets.py",
- "tests/unit/test_three_axis_door_contract.py",
- "tests/unit/test_project_generation.py",
- "tests/unit/test_protocol.py",
- "tests/unit/test_6400_contract.py",
- "tests/unit/test_6400_closure_separation.py",
- "tests/unit/test_6400_canonical_packages.py",
- ]
- codes.append(
- subprocess.call(
- [_python(), "-B", "-m", "pytest", *focused, "-q", "--tb=short"],
- cwd=str(ROOT),
- )
- )
- else:
- codes.append(_run_mrdimm_matrix("python,icarus,verilator,cocotb,formal"))
- if not codes:
- return 2
- return next((code for code in codes if code not in (0,)), 0)
- def cmd_package(args: argparse.Namespace) -> int:
- try:
- target = resolve_target(args.target)
- _generate_one(target.alias)
- blocked, pins = release_blocked(target)
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- if args.kind == "firmware" and blocked:
- return _die(
- "firmware package blocked: release_blocked unresolved pins: " + ", ".join(pins),
- 3,
- )
- from tools.package_target import build_target_package
- path = build_target_package(
- target.alias,
- args.kind,
- ROOT / "dist",
- profile_name=args.profile,
- td_receipt=args.td_receipt,
- )
- print(path)
- return 0
- def cmd_diagnose(args: argparse.Namespace) -> int:
- """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
- if sys.platform != "linux":
- return _die("Run RTL diagnostics in the authorized LAN Linux container")
- out = args.run_root.resolve()
- if out == ROOT or ROOT in out.parents:
- return _die("--run-root must be outside the source checkout")
- out.mkdir(parents=True, exist_ok=False)
- products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,)
- tests = {
- "6400-front-rear": ("frame_rx_tb", "prod2u_6400_uart_e2e_tb"),
- "mrdimm-chamber": ("motor_axis_contract_tb", "motor_engine_tb", "motor_event_ring_tb", "prod2u_mrdimm_uart_e2e_tb"),
- }
- receipt = {"scope": "migration-diagnostic-only", "run_id": out.name,
- "hardware": "NOT_RUN", "results": [], "inputs": {}}
- receipt["commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
- receipt["tree"] = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=ROOT, text=True).strip()
- for tool, flag in (("iverilog", "-V"), ("vvp", "-V")):
- receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0]
- def execute(name: str, command: list[str], marker: str | None = None) -> bool:
- log_path = out / (name + ".log")
- with log_path.open("w", encoding="utf-8") as log:
- log.write(json.dumps(command) + "\n"); log.flush()
- process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
- try:
- code = process.wait(timeout=args.timeout)
- except subprocess.TimeoutExpired:
- os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
- observed = log_path.read_text(errors="replace")
- passed = code == 0 and (marker is None or marker in observed)
- receipt["results"].append({"name": name, "command": command, "exit_code": code,
- "status": "PASS" if passed else "FAIL", "required_marker": marker,
- "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
- receipt["status"] = "PASS" if all(x["status"] == "PASS" for x in receipt["results"]) else "FAIL"
- (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
- print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
- return passed
- for product in products:
- manifest_path = ROOT / "products" / product / "source-closure.json"
- manifest = json.loads(manifest_path.read_text())
- sources = manifest["sources"]
- benches = tests[product]
- contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"]
- input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches])
- input_paths.add(manifest_path.relative_to(ROOT).as_posix())
- # Include transitive generated headers imported by the mailbox.
- input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh"))
- input_paths.add("tools/fw_cli.py")
- if product == "6400-front-rear":
- input_paths.add("src/modules/double_bank_target_store.v")
- receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)}
- source_args = [p for p in sources if p.endswith(".v")]
- for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]:
- binary = out / (top + ".vvp")
- argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args]
- if behavior:
- argv.append(f"tests/sim/{top}.v")
- if top == "prod2u_6400_uart_e2e_tb":
- argv.append("src/modules/double_bank_target_store.v")
- if execute(top + "-compile", argv) and behavior:
- execute(top, ["vvp", str(binary)], top + " PASS")
- return 0 if receipt["status"] == "PASS" else 1
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry")
- sub = parser.add_subparsers(dest="command", required=True)
- sub.add_parser("list")
- gen = sub.add_parser("generate")
- gen.add_argument("target")
- tes = sub.add_parser("test")
- tes.add_argument("target")
- diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
- diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber"))
- diag.add_argument("--run-root", type=Path, required=True)
- diag.add_argument("--timeout", type=int, default=60)
- bld = sub.add_parser("build")
- bld.add_argument("target")
- pkg = sub.add_parser("package")
- pkg.add_argument("target")
- pkg.add_argument("--kind", default="source", choices=("source", "review", "firmware"))
- pkg.add_argument(
- "--profile",
- choices=("6400-front-rear",),
- )
- pkg.add_argument("--td-receipt", type=Path)
- args = parser.parse_args(argv)
- commands = {
- "list": cmd_list,
- "generate": cmd_generate,
- "test": cmd_test,
- "diagnose": cmd_diagnose,
- "build": cmd_build,
- "package": cmd_package,
- }
- try:
- return commands[args.command](args)
- except SystemExit as exc:
- return int(exc.code or 0)
- except (TargetError, ValueError) as exc:
- return _die(str(exc), 2)
- if __name__ == "__main__":
- _configure_worktree_git()
- load_registry(ROOT)
- raise SystemExit(main())
|