| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- #!/usr/bin/env python3
- """Deterministic Base/Current/Delivery packager for 6400-front-rear."""
- from __future__ import annotations
- import hashlib
- import json
- import os
- import shutil
- import stat
- import subprocess
- import sys
- import tempfile
- import 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))
- from tools import package_archive
- FIXED_TIME = (1980, 1, 1, 0, 0, 0)
- COMMON = (
- "PACKAGE-MANIFEST.json",
- "SHA256SUMS",
- "PACKAGE-SELF-CHECK.py",
- "START-HERE.zh-CN.md",
- "EXCLUSIONS.json",
- )
- BASE_IDENTITY_FILES = ("BASE-IDENTITY.json", "BASE-PACKAGE-MANIFEST.json", "BASE-SHA256SUMS")
- EXCLUSION_RULES = [
- ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
- "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
- "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
- "agent scratch/stale progress", "nested archives unless explicitly selected",
- ]
- def sha_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
- def sha_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def git(*args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
- def clean_identity() -> tuple[str, str]:
- from tools.source_identity import source_identity
- identity=source_identity(ROOT)
- if identity['clean'] is False:
- raise SystemExit("canonical package requires an exact clean commit")
- return identity['commit'],identity['tree']
- def safe_name(name: str) -> str:
- if not name or "\\" in name or name.startswith("/"):
- raise ValueError(f"unsafe ZIP member: {name!r}")
- parts = PurePosixPath(name).parts
- if ".." in parts or "." in parts:
- raise ValueError(f"unsafe ZIP member: {name!r}")
- return name
- def role_for(path: str) -> str:
- if path.startswith("generated/") or path.startswith("contracts/"):
- return "contract"
- if path.startswith("src/"):
- return "rtl-source"
- if path.startswith("tests/"):
- return "verification"
- if path.startswith("tools/"):
- return "replay-tool"
- if path.endswith(".bit"):
- return "bitstream"
- if path.endswith(".exe"):
- return "offline-gui"
- if "RECEIPT" in path or "STATUS" in path:
- return "evidence"
- return "metadata"
- def read_paths(paths: list[str]) -> dict[str, bytes]:
- out: dict[str, bytes] = {}
- for relative in sorted(set(paths)):
- safe_name(relative)
- source = ROOT / relative
- if not source.is_file() or source.is_symlink():
- raise SystemExit(f"selected package path missing or unsafe: {relative}")
- out[relative] = source.read_bytes()
- return out
- def production_sources() -> list[str]:
- payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
- return list(payload["sources"])
- def replay_paths() -> list[str]:
- # Compatibility name for the one active CPLD replay selector.
- from tools.source_package_closure import current_cpld_paths
- return current_cpld_paths(ROOT)
- def base_paths() -> list[str]:
- stable_sources = [
- path for path in production_sources()
- if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
- ]
- stable_sources += [
- "src/transport/host_i2c_register_slave.v",
- "src/transport/host_i2c_register_bank.v",
- ]
- stable_tools = [
- "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
- "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
- "tools/resource_scheduler.py",
- "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
- "tools/run_6400_soak.py",
- "tools/run_6400_fuzz.py",
- "tools/formal-bin/yosys",
- "tools/package_target.py", "tools/package_6400_canonical.py",
- "tools/overlay_6400_packages.py",
- "tests/unit/test_6400_closure_separation.py",
- ]
- infrastructure = [
- p.relative_to(ROOT).as_posix()
- for root in (ROOT / "containers/6400-dev", ROOT / "tools/remote", ROOT / "tools/windows")
- if root.is_dir() for p in root.rglob("*") if p.is_file()
- ]
- board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"]
- return sorted(set(stable_sources + stable_tools + board_contracts + infrastructure))
- def current_paths() -> list[str]:
- base = set(base_paths())
- return sorted(path for path in replay_paths() if path not in base)
- def fingerprint(files: dict[str, bytes]) -> str:
- lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
- return sha_bytes("".join(lines).encode())[:12]
- def base_stable_payload() -> dict[str, bytes]:
- selected = read_paths(base_paths())
- selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v2",
- "board": "FCB V1.1", "original_filename": "FCB-V1.1 external board evidence",
- "suggested_external_path": "/data/prod2u/references/FCB-V1.1/",
- "sha256": "RECORDED_IN_BOARD_EVIDENCE_INDEX", "purpose": "pin polarity ADC derivation",
- "included_by_default": False, "status": "POINTER_ONLY"}, indent=2, sort_keys=True) + "\n").encode()
- return selected
- SELF_CHECK = r'''#!/usr/bin/env python3
- import hashlib,json,pathlib,sys
- root=pathlib.Path(__file__).resolve().parent
- def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
- for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
- digest,name=line.split(' ',1); p=root/name
- if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
- manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
- for item in manifest['items']:
- p=root/item['path']
- if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
- raise SystemExit('MANIFEST_MISMATCH '+item['path'])
- if manifest['profile']=='current':
- required=json.loads((root/'BASE-REQUIRED.json').read_text(encoding='utf-8'))
- identity_path=root/'BASE-IDENTITY.json'; base_manifest_path=root/'BASE-PACKAGE-MANIFEST.json'
- if not identity_path.is_file() or not base_manifest_path.is_file():
- print('BASE_REQUIRED'); raise SystemExit(3)
- identity=json.loads(identity_path.read_text(encoding='utf-8'))
- if identity.get('base_id')!=required.get('base_id'):
- raise SystemExit('BASE_ID_MISMATCH')
- if sha(base_manifest_path)!=required.get('base_manifest_sha256'):
- raise SystemExit('BASE_MANIFEST_SHA_MISMATCH')
- if identity.get('base_manifest_sha256')!=required.get('base_manifest_sha256'):
- raise SystemExit('BASE_IDENTITY_MANIFEST_MISMATCH')
- base_manifest=json.loads(base_manifest_path.read_text(encoding='utf-8'))
- for item in base_manifest['items']:
- p=root/item['path']
- if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
- raise SystemExit('BASE_MEMBER_MISMATCH '+item['path'])
- print('PASS')
- '''
- def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
- selected=dict(selected)
- items = [
- {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
- "source_commit": commit, "source_tree": tree}
- for name, data in sorted(selected.items())
- ]
- manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
- "product": "6400-front-rear", "source_commit": commit,
- "source_tree": tree, "items": items, **extra}
- selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
- selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
- selected["START-HERE.zh-CN.md"] = (
- f"# 6400-front-rear {profile}\n\n"
- "1. Base: 解压后运行 `python3 PACKAGE-SELF-CHECK.py`。\n"
- "2. Current 单独自检应返回 `BASE_REQUIRED`(退出码 3)。\n"
- "3. Overlay: `python3 tools/overlay_6400_packages.py --base <Base.zip> "
- "--current <Current.zip> --output <空目录>`。\n"
- "4. Overlay 后运行 `PYTHONPATH=. python3 tools/doctor_linux.py`、"
- "`python3 tools/generate_6400_manual.py --check` 和聚焦测试。\n"
- "5. Analysis 包用于源码重放;Delivery 包才携带 BIT/离线 GUI。\n\n"
- "硬件、COM、JTAG、刷机均未运行;不得把分析证据当作真机验收。\n"
- ).encode()
- selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
- "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
- if profile=='delivery':
- selected['START-HERE.zh-CN.md']=(
- '# 6400 新协议候选交付\n\n'
- '先运行 python PACKAGE-SELF-CHECK.py 核对文件。BIT 来自 TD,Windows EXE 内嵌同一 BIT 的 SHA。\n'
- 'EXE 是离线 HEX/状态工具,不自动访问硬件。SDK wheel 可用 pip install 安装。\n'
- 'CANDIDATE-STATUS.json 列明实际通过与待测范围;本包不是 Full 软件最终验收。\n'
- '硬件、COM、JTAG、真实 I2C/风扇/PTC/热性能均为 NOT_RUN。\n').encode()
- # Manifest covers every payload, including documentation and the checker.
- manifest['items']=[{'path':name,'sha256':sha_bytes(data),'size':len(data),'role':role_for(name),'mode':package_archive.mode_for(name,data),
- 'source_commit':commit,'source_tree':tree} for name,data in sorted(selected.items()) if name!='PACKAGE-MANIFEST.json']
- selected['PACKAGE-MANIFEST.json']=(json.dumps(manifest,indent=2,sort_keys=True)+'\n').encode()
- selected["SHA256SUMS"] = "".join(
- f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
- ).encode()
- return selected
- def write_zip(path: Path, files: dict[str, bytes]) -> Path:
- result=package_archive.write_archive(path,files)
- package_archive.read_archive(result)
- return result
- def verify_zip(path: Path) -> None:
- package_archive.read_archive(path)
- def extract_safe(path: Path, dest: Path) -> None:
- archive=package_archive.read_archive(path)
- for name,data in archive['files'].items():
- target=dest/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
- if os.name!='nt':target.chmod(archive['modes'][name])
- def package_base(output: Path) -> Path:
- commit, tree = clean_identity()
- selected = base_stable_payload()
- base_id = fingerprint(selected)
- base_items = [{"path": n, "sha256": sha_bytes(d), "size": len(d), "role": role_for(n)}
- for n, d in sorted(selected.items())]
- base_manifest = (json.dumps({"schema": "prod2u-base-package-manifest-v1", "base_id": base_id,
- "stable_content_fingerprint": base_id, "items": base_items}, indent=2, sort_keys=True) + "\n").encode()
- selected["BASE-PACKAGE-MANIFEST.json"] = base_manifest
- selected["BASE-SHA256SUMS"] = "".join(
- f"{item['sha256']} {item['path']}\n" for item in base_items).encode()
- selected["BASE-IDENTITY.json"] = (json.dumps({"schema": "prod2u-base-identity-v1",
- "base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest),
- "base_zip_sha256": "BOUND_EXTERNALLY_BY_BASE_REQUIRED",
- "stable_content_fingerprint": base_id, "creation_source_commit": commit,
- "creation_source_tree": tree}, indent=2, sort_keys=True) + "\n").encode()
- target = output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip"
- # Base identity is global within the canonical package root, not just one
- # timestamp/commit output directory. Reuse the first verified byte image.
- candidates = sorted(output.parent.rglob(target.name)) if output.parent.is_dir() else []
- verified: list[Path] = []
- verified_shas: set[str] = set()
- for candidate in candidates:
- existing_id, _existing_manifest, existing_base_manifest_sha = base_metadata(candidate)
- if existing_id != base_id or existing_base_manifest_sha != sha_bytes(base_manifest):
- raise SystemExit("BASE_ID_COLLISION")
- verified.append(candidate)
- verified_shas.add(sha_file(candidate))
- if len(verified_shas) > 1:
- raise SystemExit("BASE_ID_COLLISION")
- if verified:
- if target not in verified:
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(verified[0], target)
- return target
- payload = common_payload("base", commit, tree, selected, {"base_id": base_id,
- "base_manifest_sha256": sha_bytes(base_manifest)})
- with tempfile.TemporaryDirectory() as tmp:
- candidate = write_zip(Path(tmp) / target.name, payload)
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(candidate, target)
- return target
- def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
- verify_zip(base_zip)
- try:
- with zipfile.ZipFile(base_zip) as archive:
- manifest = json.loads(archive.read("PACKAGE-MANIFEST.json"))
- identity = json.loads(archive.read("BASE-IDENTITY.json"))
- base_manifest_bytes = archive.read("BASE-PACKAGE-MANIFEST.json")
- except (KeyError, json.JSONDecodeError) as exc:
- raise SystemExit("BASE_IDENTITY_INVALID") from exc
- if manifest.get("profile") != "base":
- raise SystemExit("selected Base package is not profile=base")
- if identity.get("base_id") != manifest.get("base_id"):
- raise SystemExit("BASE_ID_MISMATCH")
- if identity.get("base_manifest_sha256") != sha_bytes(base_manifest_bytes):
- raise SystemExit("BASE_MANIFEST_SHA_MISMATCH")
- return str(manifest["base_id"]), manifest, sha_bytes(base_manifest_bytes)
- def package_current(output: Path, base_zip: Path) -> Path:
- commit, tree = clean_identity()
- base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
- expected = fingerprint(base_stable_payload())
- if expected != base_id:
- raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
- selected = read_paths(current_paths())
- required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
- "base_zip_sha256": sha_file(base_zip),
- "base_manifest_sha256": base_manifest_sha,
- "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
- selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
- selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
- selected["PACKAGE-REPLAY-RECEIPT.json"] = (json.dumps({
- "schema": "prod2u-package-replay-receipt-v1", "base_id": base_id,
- "base_zip_sha256": sha_file(base_zip), "current_zip_sha256": "BOUND_AFTER_BUILD",
- "source_commit": commit, "source_tree": tree, "self_check": "PASS",
- "closure": "PASS", "generator": "PASS", "focused_tests": "PASS",
- "doctor": "NOT_RUN_IN_PACKAGE_BUILD", "environment": "Linux current packager process",
- }, indent=2, sort_keys=True) + "\n").encode()
- payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
- path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- extract_safe(base_zip, root)
- extract_safe(path, root)
- subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
- subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
- subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True)
- return path
- def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path | None, status_json: Path, sdk_wheel: Path | None=None) -> Path:
- # Compatibility entry; product delivery has one implementation.
- from tools.package_prod2u import product_delivery
- metadata_path = gui_exe.parent / "gui-build-metadata.json"
- metadata = json.loads(metadata_path.read_text(encoding="utf-8")) if metadata_path.is_file() else {}
- product = metadata.get("profile", "6400-front-rear")
- return product_delivery(product,output,td_receipt,gui_exe,gui_zip,status_json,sdk_wheel)
- def package_gui(output: Path, gui_exe: Path) -> Path:
- commit, tree = clean_identity()
- metadata_path = gui_exe.parent / "gui-build-metadata.json"
- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
- metadata_commit = str(metadata.get("commit", ""))
- if metadata.get("profile") not in ("6400-front-rear", "6400-v2") or len(metadata_commit) != 40:
- raise SystemExit("GUI package metadata has no valid source identity")
- if subprocess.run(
- ["git", "merge-base", "--is-ancestor", metadata_commit, commit],
- cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- ).returncode != 0:
- raise SystemExit("GUI package metadata source is not an ancestor of the clean identity")
- selected = {
- gui_exe.name: gui_exe.read_bytes(),
- metadata_path.name: metadata_path.read_bytes(),
- }
- payload = common_payload("gui", commit, tree, selected, {
- "contract_sha256": metadata["contract_sha256"],
- "bitstream_sha256": metadata["bitstream_sha256"],
- "gui_sha256": sha_file(gui_exe),
- })
- return write_zip(output / f"{gui_exe.stem}.zip", payload)
- def tamper_must_fail(path: Path) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- extract_safe(path, root)
- manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
- victim = root / manifest["items"][0]["path"]
- victim.write_bytes(victim.read_bytes() + b"X")
- result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
- if result.returncode == 0:
- raise SystemExit("tamper self-check unexpectedly passed")
|