| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286 |
- #!/usr/bin/env python3
- """Single canonical Base/Current/Delivery package dispatcher.
- Product-specific legacy packagers remain implementation details; this entrypoint
- is the only supported command surface and performs fail-closed ZIP verification.
- """
- from __future__ import annotations
- import argparse, hashlib, json, shutil, stat, sys, tempfile, zipfile
- from pathlib import Path, PurePosixPath
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
- def sha(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest()
- FIXED_TIME = (1980, 1, 1, 0, 0, 0)
- def _safe(name: str) -> str:
- p = PurePosixPath(name)
- if not name or name.startswith("/") or ".." in p.parts or "\\" in name:
- raise ValueError(f"unsafe package path: {name}")
- return name
- def _zip(path: Path, files: dict[str, bytes]) -> Path:
- path.parent.mkdir(parents=True, exist_ok=True)
- with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as z:
- for name in sorted(files):
- _safe(name)
- info = zipfile.ZipInfo(name, FIXED_TIME); info.create_system = 3
- info.external_attr = (stat.S_IFREG | 0o644) << 16
- z.writestr(info, files[name], compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
- return path
- def _dual_paths() -> list[str]:
- """Current-only closure for both products, excluding build/cache/secrets."""
- wanted = {
- "projects/registry.json", "projects/mrdimm-chamber/project.json",
- "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
- "products/6400-front-rear/analysis-replay-closure.json",
- "docs/prod2u-6400-front-back-protocol.zh-CN.md",
- "contracts/6400-manual.yaml", "contracts/6400-wire.yaml", "contracts/6400-snapshot.yaml",
- "contracts/6400-fixed-point.yaml", "contracts/channel-map.yaml",
- "contracts/host-i2c-pin-evidence.json", "contracts/mrdimm-wire.yaml",
- "constraints/prod2u_mrdimm.adc", "constraints/prod2u_mrdimm.sdc",
- "td/prod2u_mrdimm.prj", "td/syn/prod2u_mrdimm.tcl",
- "td/phy/prod2u_mrdimm.tcl", "td/bitgen/prod2u_mrdimm.tcl",
- "tools/generate_mrdimm_adc.py", "tools/generate_mrdimm_params.py",
- "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
- "constraints/prod2u_p4_normal_v3.adc", "constraints/prod2u_p4_normal_v3.sdc",
- "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
- "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
- "td/prod2u_p4_normal_v3.prj", "td/syn/prod2u_p4_normal_v3.tcl",
- "td/phy/prod2u_p4_normal_v3.tcl", "td/bitgen/prod2u_p4_normal_v3.tcl",
- "tools/generate_target.py", "tools/generate_project.py", "tools/generate_6400_manual.py",
- "tools/target_registry.py", "tools/fw_cli.py", "tools/package_prod2u.py",
- "tools/mrdimm_hex_gui.py", "tools/build_mrdimm_hex_gui.py", "tools/6400_hex_gui.py",
- "tools/build_6400_hex_gui.py", "tools/overlay_6400_packages.py",
- "tools/_vendor/hth_protocol.py", "tools/_vendor/hth_protocol.sha256",
- "tools/fw_targets.py",
- "tests/sim/frame_rx_tb.v", "tests/sim/frame_tx_tb.v",
- "tests/sim/prod2u_6400_uart_e2e_tb.v",
- "tests/sim/motor_engine_tb.v", "tests/sim/prod2u_mrdimm_uart_e2e_tb.v",
- "tests/legacy/README.md",
- "generated/mrdimm/prod2u_mrdimm_params.vh",
- "src/top/prod2u_mrdimm_rs232_only_top.v",
- "src/control/mrdimm_output_core.v",
- "src/telemetry/mrdimm_snapshot_mux.v",
- "ACTIVE_GOAL_LOCK.yaml", "EXECUTION_PLAN.md", "PHASE_STATE.json",
- "TEST_IMPACT_MAP.yaml", "DECISION_TRACE.md", "RECOVERY_LOG.md", "EVIDENCE_INDEX.json",
- "evidence/solver-map.yaml",
- }
- for closure in (ROOT/"config/source_closure.json",
- ROOT/"products/6400-front-rear/source-closure.json",
- ROOT/"products/mrdimm-chamber/source-closure.json"):
- data = json.loads(closure.read_text(encoding="utf-8"))
- wanted.add(closure.relative_to(ROOT).as_posix())
- wanted.update(str(x).replace("\\", "/") for x in data.get("sources", []))
- wanted.update(str(x).replace("\\", "/") for x in data.get("files", []))
- for root in (ROOT/"src/generated", ROOT/"generated/6400"):
- if root.is_dir():
- wanted.update(p.relative_to(ROOT).as_posix() for p in root.rglob("*") if p.is_file())
- return sorted(p for p in wanted if (ROOT/p).is_file() and not any(x in p.lower() for x in ("__pycache__", ".pyc", ".pytest_cache", "secret", "token", "password")))
- def _dual_current(output: Path, base_zip: Path) -> Path:
- from tools.package_6400_canonical import base_metadata
- base_id, _manifest, base_manifest_sha = base_metadata(base_zip)
- files = {p: (ROOT/p).read_bytes() for p in _dual_paths()}
- import subprocess
- def _git(repo: Path, *args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
- commits = _git(ROOT, "rev-parse", "HEAD")
- repos = []
- for name, rel in (("cpld-temperature-control", ROOT),
- ("hth-platform", ROOT.parent / "hth-platform"),
- ("engineering-manifests", ROOT.parent / "engineering-manifests")):
- if (rel / ".git").exists():
- repos.append({"name": name, "commit": _git(rel, "rev-parse", "HEAD"),
- "tree": _git(rel, "rev-parse", "HEAD^{tree}")})
- contract_shas = []
- for p in (ROOT/"src/generated/host-contract.json", ROOT/"generated/6400/host-contract.json",
- ROOT/"generated/mrdimm/prod2u_mrdimm_params.vh"):
- if p.is_file(): contract_shas.append(sha(p))
- identity = {"repos": repos, "contract_shas": sorted(contract_shas), "base_id": base_id}
- snapshot = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:16]
- # Explicit overlay declarations (D08): every Current file that also
- # exists in Base with different content is a declared replacement.
- import zipfile as _zf
- base_hashes: dict[str, str] = {}
- with _zf.ZipFile(base_zip) as bz:
- for info in bz.infolist():
- name = info.filename
- if name in ("SHA256SUMS", "PACKAGE-MANIFEST.json", "PACKAGE-SELF-CHECK.py",
- "BASE-REQUIRED.json", "OVERLAY-RECEIPT.json"):
- continue
- base_hashes[name] = hashlib.sha256(bz.read(info)).hexdigest()
- replacements = [{"path": pth, "base_sha256": base_hashes[pth],
- "current_sha256": hashlib.sha256(data).hexdigest()}
- for pth, data in sorted(files.items())
- if pth in base_hashes and base_hashes[pth] != hashlib.sha256(data).hexdigest()]
- additions = sorted(p for p in files if p not in base_hashes)
- required = {"schema":"prod2u-base-required-v1","base_id":base_id,"base_manifest_sha256":base_manifest_sha,"base_zip_sha256":sha(base_zip)}
- files["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True)+"\n").encode()
- ws = {"schema":"prod2u-workspace-snapshot-v1", **identity, "snapshot_id": snapshot}
- files["WORKSPACE-SNAPSHOT.json"] = (json.dumps(ws, indent=2, sort_keys=True)+"\n").encode()
- files["OVERLAY-REPLACEMENTS.json"] = (json.dumps({"schema":"prod2u-overlay-replacements-v1","count":len(replacements),"replacements":replacements}, indent=2, sort_keys=True)+"\n").encode()
- files["OVERLAY-ADDITIONS.json"] = (json.dumps({"schema":"prod2u-overlay-additions-v1","count":len(additions),"additions":additions}, indent=2, sort_keys=True)+"\n").encode()
- files["EXCLUSIONS.json"]=(json.dumps({"excluded":[".git","venv","node_modules","__pycache__","BIT/GUI binaries","tokens/secrets/licenses","raw board files","large logs"]},indent=2,ensure_ascii=False)+"\n").encode()
- files["PACKAGE-SELF-CHECK.py"]=("import hashlib,json,pathlib,sys\nroot=pathlib.Path(__file__).parent\nm=json.loads((root/'PACKAGE-MANIFEST.json').read_text())\ndeclared={i['path'] for i in m['items']}\nactual={p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()}\nmissing=declared-actual\nif missing:\n print('FILESET_MISMATCH missing='+str(sorted(missing)))\n sys.exit(2)\nfor i in m['items']:\n p=root/i['path']\n if not p.is_file() or hashlib.sha256(p.read_bytes()).hexdigest()!=i['sha256']:\n print('HASH_MISMATCH '+i['path'])\n sys.exit(2)\nprint('archive integrity OK; full replay requires Base '+m['base_id'])\nsys.exit(3)\n").encode()
- items = [{"path":p,"sha256":hashlib.sha256(data).hexdigest(),"size":len(data)} for p,data in sorted(files.items())]
- manifest = {"schema":"prod2u-dual-current-manifest-v1","profile":"current","products":["6400-front-rear","mrdimm-chamber"],"source_commit":commits,"snapshot_id":snapshot,"base_id":base_id,"repos":repos,"overlay_replacements_count":len(replacements),"items":items}
- files["PACKAGE-MANIFEST.json"]=(json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
- files["SHA256SUMS"]="".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
- return _zip(output/(f"Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip"), files)
- def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
- """Replay a dual Current over its matching Base without path escapes."""
- from tools.package_6400_canonical import extract_safe, base_metadata
- from tools.package_6400_canonical import sha_file as _sha_file
- base_id, _manifest, _base_manifest_sha = base_metadata(base_zip)
- with zipfile.ZipFile(current_zip) as z:
- manifest = json.loads(z.read("PACKAGE-MANIFEST.json"))
- reps_declared = json.loads(z.read("OVERLAY-REPLACEMENTS.json"))["replacements"] if "OVERLAY-REPLACEMENTS.json" in z.namelist() else []
- if manifest.get("schema") != "prod2u-dual-current-manifest-v1" or manifest.get("base_id") != base_id:
- raise SystemExit("BASE_ID_MISMATCH")
- if output.exists() and any(output.iterdir()): raise SystemExit("output directory must be empty")
- output.mkdir(parents=True, exist_ok=True)
- extract_safe(base_zip, output)
- with zipfile.ZipFile(current_zip) as z:
- for info in z.infolist():
- name = _safe(info.filename)
- dest = output / name
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_bytes(z.read(info))
- selfcheck = __import__("subprocess").run([sys.executable, "PACKAGE-SELF-CHECK.py"], cwd=output, text=True, capture_output=True)
- if selfcheck.returncode not in (0, 3): raise SystemExit("DUAL_OVERLAY_SELF_CHECK_FAILED: "+selfcheck.stdout+selfcheck.stderr)
- # declared replacements must match the actual Base/Current content diff
- for r in reps_declared:
- overlaid = output / r["path"]
- if not overlaid.is_file() or hashlib.sha256(overlaid.read_bytes()).hexdigest() != r["current_sha256"]:
- raise SystemExit("OVERLAY_REPLACEMENT_MISMATCH "+r["path"])
- required = (output/"products/6400-front-rear/project.json",
- output/"products/mrdimm-chamber/source-closure.json",
- output/"projects/mrdimm-chamber/project.json",
- output/"contracts/mrdimm-wire.yaml",
- output/"constraints/prod2u_mrdimm.adc",
- output/"src/top/prod2u_mrdimm_rs232_only_top.v",
- output/"src/motor/motor_engine.v")
- missing = [str(q) for q in required if not q.is_file()]
- if missing: raise SystemExit("DUAL_OVERLAY_CLOSURE_INCOMPLETE "+", ".join(missing))
- receipt = {"schema":"prod2u-dual-overlay-receipt-v1","status":"PASS","base_id":base_id,"base_zip_sha256":_sha_file(base_zip),"current_zip_sha256":_sha_file(current_zip),"self_check":selfcheck.stdout.strip()}
- (output/"OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True)+"\n", encoding="utf-8")
- return output
- def verify(path: Path) -> dict:
- raw_archive = path.read_bytes()
- with zipfile.ZipFile(path) as z:
- names = z.namelist()
- if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("invalid ZIP ordering or duplicate members")
- if any(n.startswith("/") or ".." in Path(n).parts for n in names): raise SystemExit("unsafe ZIP member")
- with tempfile.TemporaryDirectory() as t:
- d=Path(t); z.extractall(d)
- sums=d/"SHA256SUMS"
- if sums.is_file():
- for line in sums.read_text(encoding="utf-8").splitlines():
- digest,name=line.split(" ",1)
- if not (d/name).is_file() or sha(d/name)!=digest: raise SystemExit("HASH_MISMATCH "+name)
- try: manifest = json.loads((d/"PACKAGE-MANIFEST.json").read_text(encoding="utf-8"))
- except Exception: manifest = None
- if isinstance(manifest, dict) and manifest.get("schema") == "prod2u-dual-current-manifest-v1":
- # manifest item set must equal the archive file set exactly
- declared = {i["path"] for i in manifest["items"]}
- actual = {n for n in names if n not in ("PACKAGE-MANIFEST.json", "SHA256SUMS")}
- if declared != actual:
- raise SystemExit(f"MANIFEST_FILESET_MISMATCH missing={sorted(declared-actual)} extra={sorted(actual-declared)}")
- for i in manifest["items"]:
- fp = d/i["path"]
- if not fp.is_file() or sha(fp) != i["sha256"]:
- raise SystemExit("MANIFEST_HASH_MISMATCH "+i["path"])
- # case-insensitive filesystem collision guard
- lowered = [n.lower() for n in names]
- if len(lowered) != len(set(lowered)): raise SystemExit("CASE_COLLISION_MEMBERS")
- # declared overlay replacements must match reality
- reps_file = d/"OVERLAY-REPLACEMENTS.json"
- if reps_file.is_file():
- reps = {r["path"]: r["base_sha256"] for r in json.loads(reps_file.read_text(encoding="utf-8"))["replacements"]}
- if manifest.get("overlay_replacements_count") != len(reps):
- raise SystemExit("OVERLAY_REPLACEMENTS_COUNT_MISMATCH")
- canonical = _zip(d/".canonical.zip", {n: (d/n).read_bytes() for n in names})
- if canonical.read_bytes() != raw_archive: raise SystemExit("NON_CANONICAL_OR_TAMPERED_ARCHIVE")
- return {"status":"PASS","package":str(path.resolve()),"sha256":sha(path)}
- def dispatch_legacy(args: argparse.Namespace) -> Path:
- from tools import package_6400_canonical as c
- if args.action == "base": return c.package_base(args.output_dir)
- if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
- if args.action == "overlay":
- with zipfile.ZipFile(args.current_zip) as z:
- try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
- except Exception: current_schema = None
- if current_schema == "prod2u-dual-current-manifest-v1":
- return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
- from tools.overlay_6400_packages import run
- run(args.base_zip, args.current_zip, args.output_dir)
- return args.output_dir
- raise SystemExit("unsupported legacy action")
- def main(argv=None) -> int:
- ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
- for name in ("base","current","all"):
- p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
- if name=="current": p.add_argument("--base-zip",type=Path,required=True)
- p=sp.add_parser("verify"); p.add_argument("package",type=Path)
- p=sp.add_parser("overlay"); p.add_argument("--base-zip",type=Path,required=True); p.add_argument("--current-zip",type=Path,required=True); p.add_argument("--output-dir",type=Path,required=True)
- p=sp.add_parser("delivery"); p.add_argument("--product",choices=("6400-v1.1","mrdimm-v1.2"),required=True); p.add_argument("--output-dir",type=Path,default=ROOT/"dist"); p.add_argument("--td-receipt",type=Path); p.add_argument("--gui-exe",type=Path); p.add_argument("--gui-zip",type=Path); p.add_argument("--status-json",type=Path)
- a=ap.parse_args(argv)
- if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
- if a.action == "all":
- base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
- current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
- print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
- return 0
- if a.action in ("base","current","overlay"):
- result=dispatch_legacy(a)
- if a.action == "overlay":
- receipt = result / "OVERLAY-RECEIPT.json"
- payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
- print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
- else:
- print(json.dumps({**verify(result),"action":a.action},indent=2))
- return 0
- if a.action=="delivery":
- if a.product=="6400-v1.1":
- if not all((a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)): ap.error("6400 delivery requires --td-receipt --gui-exe --gui-zip --status-json")
- from tools.package_target import package_6400_canonical
- result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)
- else:
- required=(a.td_receipt,a.gui_exe,a.gui_zip)
- if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
- a.output_dir.mkdir(parents=True,exist_ok=True); commit="unknown"; receipt=json.loads(a.td_receipt.read_text(encoding="utf-8")); commit=str(receipt.get("commit",commit))
- # TD receipts retain the Linux artifact path. Resolve the copied
- # bitstream beside the receipt (the Windows fetch step preserves
- # this basename) so Delivery always contains the actual BIT.
- bit = None
- bit_meta = receipt.get("measurement_artifacts", {}).get("bitstream", {})
- bit_name = Path(str(bit_meta.get("path", ""))).name
- candidates = [a.td_receipt.parent / bit_name] if bit_name else []
- candidates += sorted(a.td_receipt.parent.glob("*.bit"))
- for candidate in candidates:
- if candidate.is_file(): bit = candidate; break
- if bit is None: ap.error("MRDIMM delivery requires fetched TD bitstream beside receipt")
- status = str(receipt.get("status", "unknown")).upper()
- candidate_status = {"status": "PASS" if status == "PASS" else "PARTIAL", "td_status": status, "timing_gate": receipt.get("timing_gate", {}), "structural_gate": receipt.get("structural_gate", {})}
- files = {
- "prod2u-mrdimm-v1.2.bit": bit.read_bytes(),
- "TD-RECEIPT.json": a.td_receipt.read_bytes(),
- a.gui_exe.name: a.gui_exe.read_bytes(),
- a.gui_zip.name: a.gui_zip.read_bytes(),
- "Wire-Contract.md": (ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md").read_bytes(),
- "Snapshot-Contract.json": (ROOT/"src/generated/host-contract.json").read_bytes(),
- "CANDIDATE-STATUS.json": json.dumps(candidate_status,indent=2,sort_keys=True).encode()+b"\n",
- }
- manifest={"schema":"prod2u-delivery-v1","product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"status":"PASS" if status == "PASS" else "PARTIAL","hardware":"NOT RUN","members":sorted(files)}
- files["RELEASE-IDENTITY.json"] = (json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
- files["SHA256SUMS"] = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
- result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; _zip(result, files)
- print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
- return 2
- if __name__=="__main__": raise SystemExit(main())
|