Przeglądaj źródła

product-fix: bind p4 harness evidence to exact source state

Codex Resource Selftest 4 miesięcy temu
rodzic
commit
67417c1b1b
2 zmienionych plików z 314 dodań i 54 usunięć
  1. 249 39
      tools/prod2u_p4_harness.py
  2. 65 15
      tools/prod2u_p4_normal_v3_build.py

+ 249 - 39
tools/prod2u_p4_harness.py

@@ -26,7 +26,11 @@ if str(TOOLS) not in sys.path:
     sys.path.insert(0, str(TOOLS))
 
 from prod2u_p4_normal_v3_build import (  # noqa: E402
+    FULL_COMMIT_RE,
     PRODUCTION_RTL_SOURCES,
+    PROJECT_CONFIG_PATH as PROJECT_CONFIG_RELATIVE_PATH,
+    SHORT_COMMIT_RE,
+    TD_SOURCE_MANIFEST_PATH as TD_SOURCE_MANIFEST_RELATIVE_PATH,
     build_synthesis_input_manifest,
 )
 from generate_project import load_project, render_adc  # noqa: E402
@@ -59,7 +63,8 @@ FSM_REPORT_SCHEMA = "prod2u-p4-normal-v3-fsm-encoding-v2"
 TARGET_MANIFEST_SCHEMA = "prod2u-simple-verification-target-manifest-v1"
 TARGET_MANIFEST_PROFILE = "prod2u-door-temp"
 TARGET_MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json"
-PROJECT_CONFIG_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
+PROJECT_CONFIG_PATH = ROOT / PROJECT_CONFIG_RELATIVE_PATH
+TD_SOURCE_MANIFEST_PATH = ROOT / TD_SOURCE_MANIFEST_RELATIVE_PATH
 TARGET_MANIFEST_LAYERS = ("unit", "icarus", "verilator", "cocotb", "formal")
 EXPECTED_CDC_SYNC_REGISTERS = frozenset(
     {
@@ -178,6 +183,61 @@ def sha256_file(path: Path) -> str:
     return digest.hexdigest()
 
 
+def source_identity() -> dict[str, Any]:
+    files = {
+        "project_config_path": PROJECT_CONFIG_PATH,
+        "td_source_manifest_path": TD_SOURCE_MANIFEST_PATH,
+    }
+    result: dict[str, Any] = {
+        "project_config_path": PROJECT_CONFIG_RELATIVE_PATH,
+        "project_config_sha256": None,
+        "td_source_manifest_path": TD_SOURCE_MANIFEST_RELATIVE_PATH,
+        "td_source_manifest_sha256": None,
+    }
+    failures: list[str] = []
+    for field, path in files.items():
+        digest_field = field.replace("_path", "_sha256")
+        if not path.is_file():
+            failures.append(f"source_identity_missing:{field}")
+            continue
+        try:
+            result[digest_field] = sha256_file(path)
+        except OSError as exc:
+            failures.append(f"source_identity_unreadable:{field}:{type(exc).__name__}")
+    result["failures"] = failures
+    return result
+
+
+def source_binding_fields(state: Mapping[str, Any]) -> dict[str, Any]:
+    return {
+        "commit": state.get("commit"),
+        "commit_full": state.get("commit_full"),
+        "commit_short": state.get("commit_short"),
+        "project_config_sha256": state.get("project_config_sha256"),
+        "td_source_manifest_sha256": state.get("td_source_manifest_sha256"),
+    }
+
+
+def receipt_commit_full(receipt: Mapping[str, Any]) -> str | None:
+    for field in ("commit_full", "commit"):
+        value = receipt.get(field)
+        if isinstance(value, str) and FULL_COMMIT_RE.fullmatch(value):
+            return value
+    return None
+
+
+def receipt_commit_matches(receipt: Mapping[str, Any], expected_commit: str) -> bool:
+    full = receipt_commit_full(receipt)
+    if full is not None:
+        return full == expected_commit
+    short = receipt.get("commit")
+    return (
+        isinstance(short, str)
+        and SHORT_COMMIT_RE.fullmatch(short) is not None
+        and short == expected_commit[:8]
+    )
+
+
 def td_receipt_bitstream_binding_status(receipt: Mapping[str, Any]) -> str:
     if receipt.get("status") in {"not_run", "blocked", "running"}:
         return "not_run"
@@ -437,11 +497,7 @@ def source_state() -> dict[str, Any]:
     commit_result = _git("rev-parse", "HEAD")
     status_result = _git("status", "--porcelain", "--untracked-files=all")
     full_commit = commit_result.stdout.strip().lower()
-    commit = (
-        full_commit[:8]
-        if re.fullmatch(r"[0-9a-f]{40}", full_commit)
-        else full_commit
-    )
+    commit = full_commit
     changes = []
     for line in status_result.stdout.splitlines():
         if not line.strip():
@@ -457,9 +513,17 @@ def source_state() -> dict[str, Any]:
         failures.append("git_commit_unavailable")
     if status_result.returncode != 0:
         failures.append("git_status_unavailable")
+    identity = source_identity()
+    failures.extend(identity["failures"])
     return {
         "status": "pass" if not failures else "fail",
         "commit": commit,
+        "commit_full": full_commit if FULL_COMMIT_RE.fullmatch(full_commit) else None,
+        "commit_short": full_commit[:8] if FULL_COMMIT_RE.fullmatch(full_commit) else None,
+        "project_config_path": identity["project_config_path"],
+        "project_config_sha256": identity["project_config_sha256"],
+        "td_source_manifest_path": identity["td_source_manifest_path"],
+        "td_source_manifest_sha256": identity["td_source_manifest_sha256"],
         "clean": status_result.returncode == 0 and not changes,
         "tracked_changes": changes,
         "failures": failures,
@@ -846,7 +910,10 @@ def formal_tool_version_evidence(
     executable: str,
     version_args: Sequence[str],
     env: Mapping[str, str],
+    work_root: Path,
 ) -> dict[str, Any]:
+    resolved_work_root = resolve_work_root(work_root, run=True)
+    assert resolved_work_root is not None
     path = Path(executable).resolve()
     failures: list[str] = []
     digest = "0" * 64
@@ -857,7 +924,7 @@ def formal_tool_version_evidence(
     try:
         completed = subprocess.run(
             [str(path), *version_args],
-            cwd=ROOT,
+            cwd=resolved_work_root,
             env=dict(env),
             text=True,
             stdout=subprocess.PIPE,
@@ -891,8 +958,8 @@ def formal_toolchain_evidence(
     work_root: Path,
 ) -> dict[str, Any]:
     env = formal_tool_env(work_root)
-    sby_evidence = formal_tool_version_evidence("sby", sby, ["--version"], env)
-    yosys_evidence = formal_tool_version_evidence("yosys", yosys, ["-V"], env)
+    sby_evidence = formal_tool_version_evidence("sby", sby, ["--version"], env, work_root)
+    yosys_evidence = formal_tool_version_evidence("yosys", yosys, ["-V"], env, work_root)
     solver_args = {
         "yices": ("yices-smt2", ["--version"]),
         "boolector": ("boolector", ["--version"]),
@@ -913,7 +980,7 @@ def formal_toolchain_evidence(
                 "failures": [f"formal_solver_tool_missing:{solver}"],
             }
         else:
-            evidence = formal_tool_version_evidence(solver, executable, args, env)
+            evidence = formal_tool_version_evidence(solver, executable, args, env, work_root)
         solver_evidence.append(evidence)
         failures.extend(evidence["failures"])
     return {
@@ -1241,8 +1308,8 @@ def _run_verilator(work_root: Path) -> dict[str, Any]:
 
 
 def _run_cocotb(work_root: Path) -> dict[str, Any]:
-    python_exe = cocotb_python()
-    probe_ok = python_has_cocotb(python_exe)
+    python_exe = cocotb_python(work_root)
+    probe_ok = python_has_cocotb(python_exe, work_root)
     missing: list[str] = []
     if not probe_ok:
         missing.append("python_module:cocotb")
@@ -1267,7 +1334,7 @@ def _run_cocotb(work_root: Path) -> dict[str, Any]:
         completed = _run_bounded(
             [python_exe, "-B", str(ROOT / target["runner"])],
             timeout_name="cocotb",
-            cwd=ROOT / "tests" / "cocotb",
+            cwd=target_root,
             env=tool_env(
                 {
                     "TEMP": str(target_root),
@@ -1310,10 +1377,12 @@ def _run_cocotb(work_root: Path) -> dict[str, Any]:
     }
 
 
-def python_has_cocotb(python_exe: str | Path) -> bool:
+def python_has_cocotb(python_exe: str | Path, work_root: Path) -> bool:
+    resolved_work_root = resolve_work_root(work_root, run=True)
+    assert resolved_work_root is not None
     completed = subprocess.run(
         [str(python_exe), "-B", "-c", "import cocotb"],
-        cwd=ROOT,
+        cwd=resolved_work_root,
         env=tool_env(),
         text=True,
         stdout=subprocess.PIPE,
@@ -1324,7 +1393,7 @@ def python_has_cocotb(python_exe: str | Path) -> bool:
     return completed.returncode == 0
 
 
-def cocotb_python() -> str:
+def cocotb_python(work_root: Path) -> str:
     candidates: list[Path] = []
     configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
     if configured:
@@ -1333,7 +1402,7 @@ def cocotb_python() -> str:
     if DEFAULT_VENV_ROOT.is_dir():
         candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe")))
     for candidate in dict.fromkeys(path.expanduser().resolve() for path in candidates):
-        if candidate.is_file() and python_has_cocotb(candidate):
+        if candidate.is_file() and python_has_cocotb(candidate, work_root):
             return str(candidate)
     return str(Path(sys.executable).resolve())
 
@@ -1786,7 +1855,7 @@ def strict_offline_gate_payload(
             "schema": OFFLINE_RECEIPT_SCHEMA,
             "status": "fail",
             "verification_run_id": run_id,
-            "commit": state["commit"],
+            **source_binding_fields(state),
             "source_state": state,
             "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"],
             "layers": {},
@@ -1865,7 +1934,7 @@ def strict_offline_gate_payload(
         "generated_at": utc_now(),
         "status": "pass" if not failures else "fail",
         "verification_run_id": run_id,
-        "commit": state["commit"],
+        **source_binding_fields(state),
         "source_state": state,
         "profile": PROFILE,
         "runtime_profile": RUNTIME_PROFILE,
@@ -1929,6 +1998,8 @@ def _copy_active_sources(target: Path) -> None:
         "constraints/prod2u_p4_normal_v3.adc",
         "constraints/prod2u_p4_normal_v3.sdc",
         "td/prod2u_p4_normal_v3.prj",
+        PROJECT_CONFIG_RELATIVE_PATH,
+        TD_SOURCE_MANIFEST_RELATIVE_PATH,
     ):
         source = ROOT / relative
         destination = target / relative
@@ -1966,6 +2037,10 @@ def prepare_td_build_dirs(*, work_root: Path) -> StagedBuild:
         "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
         "status": "pass",
         "commit": state["commit"],
+        "commit_full": state["commit_full"],
+        "commit_short": state["commit_short"],
+        "project_config_sha256": state["project_config_sha256"],
+        "td_source_manifest_sha256": state["td_source_manifest_sha256"],
         "source_state_clean": state["clean"],
         "phases": phases,
         "failures": [],
@@ -1998,10 +2073,21 @@ def _staged_synthesis_input_manifest(staged: StagedBuild) -> dict[str, Any]:
         else:
             path = staged.syn / relative_text
         observed[relative_text] = sha256_file(path) if path.is_file() else None
+    manifest_binding = {
+        "inputs": observed,
+        "project_config_path": staged.synthesis_input_manifest.get("project_config_path"),
+        "project_config_sha256": observed.get(PROJECT_CONFIG_RELATIVE_PATH),
+        "td_source_manifest_path": staged.synthesis_input_manifest.get("td_source_manifest_path"),
+        "td_source_manifest_sha256": observed.get(TD_SOURCE_MANIFEST_RELATIVE_PATH),
+    }
     return {
         "schema": staged.synthesis_input_manifest.get("schema"),
         "inputs": observed,
-        "sha256": canonical_sha256(observed),
+        "project_config_path": manifest_binding["project_config_path"],
+        "project_config_sha256": manifest_binding["project_config_sha256"],
+        "td_source_manifest_path": manifest_binding["td_source_manifest_path"],
+        "td_source_manifest_sha256": manifest_binding["td_source_manifest_sha256"],
+        "sha256": canonical_sha256(manifest_binding),
     }
 
 
@@ -2067,6 +2153,10 @@ def verify_staged_source_manifest(staged: StagedBuild) -> dict[str, Any]:
         "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
         "status": "pass" if not failures else "fail",
         "commit": staged.source_manifest.get("commit"),
+        "commit_full": staged.source_manifest.get("commit_full"),
+        "commit_short": staged.source_manifest.get("commit_short"),
+        "project_config_sha256": staged.source_manifest.get("project_config_sha256"),
+        "td_source_manifest_sha256": staged.source_manifest.get("td_source_manifest_sha256"),
         "source_state_clean": staged.source_manifest.get("source_state_clean"),
         "phases": verified_phases,
         "synthesis_input_manifest": observed_synthesis,
@@ -2775,6 +2865,12 @@ def td_source_states_clean(
         source_before.get("clean") is True
         and source_after.get("clean") is True
         and staged_manifest.get("source_state_clean") is True
+        and source_before.get("project_config_sha256")
+        == source_after.get("project_config_sha256")
+        == staged_manifest.get("project_config_sha256")
+        and source_before.get("td_source_manifest_sha256")
+        == source_after.get("td_source_manifest_sha256")
+        == staged_manifest.get("td_source_manifest_sha256")
     )
 
 
@@ -2981,7 +3077,7 @@ def td_build_payload(
         "status": "pass" if passed else "fail",
         "generated_at": generated_at,
         "run_id": run_id,
-        "commit": staged.source_state["commit"],
+        **source_binding_fields(staged.source_state),
         "source_state": dict(staged.source_state),
         "repository_state_after": state_after,
         "bitstream_sha256": bitstream_sha256,
@@ -3048,15 +3144,19 @@ def td_build_payload(
 
 
 def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> int:
+    emitted = dict(payload)
+    for field, value in source_binding_fields(source_state()).items():
+        if field not in emitted:
+            emitted[field] = value
     if getattr(args, "report_file", None):
         try:
             report_file = resolve_report_file(args.report_file)
         except ValueError as exc:
             print(json.dumps({"status": "fail", "reason": str(exc)}, indent=2) if getattr(args, "json", False) else f"{label}: fail")
             return 1
-        write_json_report(payload, report_file)
-    print(json.dumps(dict(payload), indent=2) if getattr(args, "json", False) else f"{label}: {payload.get('status', 'unknown')}")
-    return 0 if payload.get("status") == "pass" else 1
+        write_json_report(emitted, report_file)
+    print(json.dumps(emitted, indent=2) if getattr(args, "json", False) else f"{label}: {emitted.get('status', 'unknown')}")
+    return 0 if emitted.get("status") == "pass" else 1
 
 
 def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str, ...]:
@@ -3100,6 +3200,10 @@ def package_selftest_payload(
     packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
     bitstream = package / "fw.bit"
     failures: list[str] = []
+    current_state = source_state()
+    expected_commit = receipt_commit_full(current_state) or ""
+    expected_project_config_sha256 = current_state.get("project_config_sha256")
+    expected_td_source_manifest_sha256 = current_state.get("td_source_manifest_sha256")
     info: Mapping[str, Any] = {}
     package_manifest: Mapping[str, Any] = {}
     primary_td: Mapping[str, Any] = {}
@@ -3183,18 +3287,27 @@ def package_selftest_payload(
             if verification_complete is not False:
                 failures.append("urgent_verification_complete_must_be_false")
         commit = str(info.get("commit", ""))
-        if not re.fullmatch(r"[0-9a-f]{8}", commit):
+        if not (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit)):
             failures.append("package_commit_invalid")
+        info_commit_full = str(info.get("commit_full", ""))
+        if info_commit_full and not FULL_COMMIT_RE.fullmatch(info_commit_full):
+            failures.append("package_commit_full_invalid")
+        if info_commit_full and expected_commit and info_commit_full != expected_commit:
+            failures.append("package_commit_full_mismatch")
+        if info.get("project_config_sha256") != expected_project_config_sha256:
+            failures.append("package_project_config_sha256_mismatch")
+        if info.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256:
+            failures.append("package_td_source_manifest_sha256_mismatch")
         if info.get("bitstream_sha256") != digest:
             failures.append("package_bitstream_sha256_mismatch")
         expected_name = (
             f"{commit}-{digest[:16]}"
-            if digest is not None and re.fullmatch(r"[0-9a-f]{8}", commit)
+            if digest is not None and (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit))
             else None
         )
         if expected_name is not None and package.name != expected_name:
             failures.append("package_folder_name_mismatch")
-        if re.fullmatch(r"[0-9a-f]{8}", commit) and package.parent.name != "prod2u-door-temp":
+        if (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit)) and package.parent.name != "prod2u-door-temp":
             failures.append("package_project_parent_mismatch")
         if info.get("td_receipt_sha256") != (
             sha256_file(primary_td_path) if primary_td_path.is_file() else None
@@ -3257,16 +3370,39 @@ def package_selftest_payload(
             failures.append(f"package_file_missing:{relative}")
 
     commit = info.get("commit") if info else None
+    package_expected_commit = (
+        receipt_commit_full(info) if info else None
+    ) or str(commit or "")
     if primary_td:
-        if primary_td.get("commit") != commit:
+        if not receipt_commit_matches(primary_td, package_expected_commit):
             failures.append("primary_td_commit_mismatch")
+        if primary_td.get("project_config_sha256") not in {
+            None,
+            expected_project_config_sha256,
+        }:
+            failures.append("primary_td_project_config_sha256_mismatch")
+        if primary_td.get("td_source_manifest_sha256") not in {
+            None,
+            expected_td_source_manifest_sha256,
+        }:
+            failures.append("primary_td_td_source_manifest_sha256_mismatch")
         if primary_td.get("bitstream_sha256") != digest:
             failures.append("primary_td_bitstream_sha256_mismatch")
         if info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash"):
             failures.append("primary_td_synthesis_input_hash_mismatch")
     if confirmation_td and confirmation_td.get("status") == "pass":
-        if confirmation_td.get("commit") != commit:
+        if not receipt_commit_matches(confirmation_td, package_expected_commit):
             failures.append("confirmation_td_commit_mismatch")
+        if confirmation_td.get("project_config_sha256") not in {
+            None,
+            expected_project_config_sha256,
+        }:
+            failures.append("confirmation_td_project_config_sha256_mismatch")
+        if confirmation_td.get("td_source_manifest_sha256") not in {
+            None,
+            expected_td_source_manifest_sha256,
+        }:
+            failures.append("confirmation_td_td_source_manifest_sha256_mismatch")
         if (
             confirmation_td.get("bitstream_sha256") not in {None, ""}
             and confirmation_td.get("bitstream_sha256") != digest
@@ -3416,6 +3552,16 @@ def package_selftest_payload(
         "generated_at": utc_now(),
         "verification_run_id": run_id,
         "commit": info.get("commit") if info else None,
+        "commit_full": (
+            receipt_commit_full(info)
+            if info
+            else None
+        ),
+        "commit_short": (
+            (receipt_commit_full(info)[:8] if receipt_commit_full(info) else info.get("commit"))
+            if info
+            else None
+        ),
         "bitstream_sha256": digest,
         "package_dir": str(package),
         "delivery_mode": info.get("delivery_mode") if info else None,
@@ -3436,6 +3582,12 @@ def package_selftest_payload(
         "confirmation_synthesis_input_hash": (
             confirmation_td.get("synthesis_input_hash") if confirmation_td else None
         ),
+        "project_config_sha256": info.get("project_config_sha256") if info else None,
+        "td_source_manifest_sha256": (
+            info.get("td_source_manifest_sha256")
+            if info
+            else None
+        ) or (primary_td.get("td_source_manifest_sha256") if primary_td else None),
         "confirmation_bitstream_sha256": (
             confirmation_td.get("bitstream_sha256") if confirmation_td else None
         ),
@@ -3503,6 +3655,8 @@ def _td_final_failures(
     *,
     label: str,
     expected_commit: str,
+    expected_project_config_sha256: str,
+    expected_td_source_manifest_sha256: str,
 ) -> list[str]:
     failures: list[str] = []
     prefix = f"{label}:"
@@ -3510,8 +3664,14 @@ def _td_final_failures(
         failures.append(prefix + "schema")
     if receipt.get("status") != "pass":
         failures.append(prefix + "status")
-    if receipt.get("commit") != expected_commit:
+    if not receipt_commit_matches(receipt, expected_commit):
         failures.append(prefix + "commit")
+    if receipt.get("commit_full") not in {None, "", expected_commit}:
+        failures.append(prefix + "commit_full")
+    if receipt.get("project_config_sha256") != expected_project_config_sha256:
+        failures.append(prefix + "project_config_sha256")
+    if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256:
+        failures.append(prefix + "td_source_manifest_sha256")
     if not re.fullmatch(
         r"[0-9a-f]{32}", str(receipt.get("verification_run_id", ""))
     ):
@@ -3525,7 +3685,13 @@ def _td_final_failures(
     if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("synthesis_input_hash", ""))):
         failures.append(prefix + "synthesis_input_hash")
     source = receipt.get("source_state")
-    if not isinstance(source, Mapping) or source.get("clean") is not True or source.get("commit") != expected_commit:
+    if (
+        not isinstance(source, Mapping)
+        or source.get("clean") is not True
+        or not receipt_commit_matches(source, expected_commit)
+        or source.get("project_config_sha256") != expected_project_config_sha256
+        or source.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256
+    ):
         failures.append(prefix + "source_state")
     for gate_name in (
         "source_binding_gate",
@@ -3631,14 +3797,26 @@ def _offline_final_failures(
     receipt: Mapping[str, Any],
     *,
     expected_commit: str,
+    expected_project_config_sha256: str,
+    expected_td_source_manifest_sha256: str,
 ) -> list[str]:
     failures: list[str] = []
     if receipt.get("schema") != OFFLINE_RECEIPT_SCHEMA:
         failures.append("offline:schema")
-    if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
+    if receipt.get("status") != "pass" or not receipt_commit_matches(receipt, expected_commit):
         failures.append("offline:status_or_commit")
+    if receipt.get("project_config_sha256") != expected_project_config_sha256:
+        failures.append("offline:project_config_sha256")
+    if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256:
+        failures.append("offline:td_source_manifest_sha256")
     source = receipt.get("source_state")
-    if not isinstance(source, Mapping) or source.get("clean") is not True:
+    if (
+        not isinstance(source, Mapping)
+        or source.get("clean") is not True
+        or not receipt_commit_matches(source, expected_commit)
+        or source.get("project_config_sha256") != expected_project_config_sha256
+        or source.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256
+    ):
         failures.append("offline:source_state")
     layers = receipt.get("layers")
     required = receipt.get("required_layers")
@@ -3657,6 +3835,8 @@ def _package_final_failures(
     receipt: Mapping[str, Any],
     *,
     expected_commit: str,
+    expected_project_config_sha256: str,
+    expected_td_source_manifest_sha256: str,
     expected_bitstream_sha256: str,
     expected_primary_td_receipt_sha256: str,
     expected_confirmation_td_receipt_sha256: str,
@@ -3665,8 +3845,12 @@ def _package_final_failures(
     expected_verification_run_id = receipt.get("verification_run_id")
     if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA:
         failures.append("package:schema")
-    if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
+    if receipt.get("status") != "pass" or receipt_commit_full(receipt) != expected_commit:
         failures.append("package:status_or_commit")
+    if receipt.get("project_config_sha256") != expected_project_config_sha256:
+        failures.append("package:project_config_sha256")
+    if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256:
+        failures.append("package:td_source_manifest_sha256")
     if receipt.get("bitstream_sha256") != expected_bitstream_sha256:
         failures.append("package:bitstream_sha256")
     if not re.fullmatch(
@@ -3724,10 +3908,15 @@ def _package_final_failures(
             info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3"
             or info.get("profile") != RUNTIME_PROFILE
             or info.get("verification_run_id") != expected_verification_run_id
-            or info.get("commit") != expected_commit
             or info.get("bitstream_sha256") != expected_bitstream_sha256
         ):
             failures.append("package:info_binding")
+        if not receipt_commit_matches(info, expected_commit):
+            failures.append("package:info_commit_binding")
+        if info.get("project_config_sha256") != expected_project_config_sha256:
+            failures.append("package:info_project_config_sha256")
+        if info.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256:
+            failures.append("package:info_td_source_manifest_sha256")
         if info.get("delivery_mode") != "normal_dual_td":
             failures.append("package:info_delivery_mode")
         if info.get("verification_complete") is not True:
@@ -3787,20 +3976,27 @@ def _package_final_failures(
 
     if primary_td:
         if (
-            primary_td.get("commit") != expected_commit
+            not receipt_commit_matches(primary_td, expected_commit)
             or primary_td.get("verification_run_id")
             != expected_verification_run_id
             or primary_td.get("bitstream_sha256") != expected_bitstream_sha256
+            or primary_td.get("project_config_sha256") != expected_project_config_sha256
+            or primary_td.get("td_source_manifest_sha256")
+            != expected_td_source_manifest_sha256
             or info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash")
         ):
             failures.append("package:primary_td_binding")
     if confirmation_td:
         if (
-            confirmation_td.get("commit") != expected_commit
+            not receipt_commit_matches(confirmation_td, expected_commit)
             or confirmation_td.get("verification_run_id")
             != expected_verification_run_id
             or confirmation_td.get("bitstream_sha256")
             != expected_bitstream_sha256
+            or confirmation_td.get("project_config_sha256")
+            != expected_project_config_sha256
+            or confirmation_td.get("td_source_manifest_sha256")
+            != expected_td_source_manifest_sha256
             or info.get("confirmation_bitstream_sha256")
             != confirmation_td.get("bitstream_sha256")
             or info.get("confirmation_synthesis_input_hash")
@@ -3813,7 +4009,7 @@ def _package_final_failures(
             != "prod2u-p4-normal-v3-validation-summary-v1"
             or validation.get("verification_run_id")
             != expected_verification_run_id
-            or validation.get("commit") != expected_commit
+            or not receipt_commit_matches(validation, expected_commit)
             or validation.get("bitstream_sha256") != expected_bitstream_sha256
             or validation.get("delivery_mode") != "normal_dual_td"
             or validation.get("verification_complete") is not True
@@ -3864,7 +4060,9 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
     if (
         state.get("status") != "pass"
         or state.get("clean") is not True
-        or not re.fullmatch(r"[0-9a-f]{8}", str(expected_commit))
+        or not FULL_COMMIT_RE.fullmatch(str(expected_commit))
+        or not re.fullmatch(r"[0-9a-f]{64}", str(state.get("project_config_sha256")))
+        or not re.fullmatch(r"[0-9a-f]{64}", str(state.get("td_source_manifest_sha256")))
     ):
         failures = ["final_source_state_not_clean"]
     else:
@@ -3873,6 +4071,8 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
         _offline_final_failures(
             child_receipts["offline"],
             expected_commit=str(expected_commit),
+            expected_project_config_sha256=str(state.get("project_config_sha256")),
+            expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")),
         )
     )
     failures.extend(
@@ -3880,6 +4080,8 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
             child_receipts["td"],
             label="td",
             expected_commit=str(expected_commit),
+            expected_project_config_sha256=str(state.get("project_config_sha256")),
+            expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")),
         )
     )
     failures.extend(
@@ -3887,6 +4089,8 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
             child_receipts["td_confirmation"],
             label="td_confirmation",
             expected_commit=str(expected_commit),
+            expected_project_config_sha256=str(state.get("project_config_sha256")),
+            expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")),
         )
     )
     for name, receipt in child_receipts.items():
@@ -3899,6 +4103,8 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
         _package_final_failures(
             package,
             expected_commit=str(expected_commit),
+            expected_project_config_sha256=str(state.get("project_config_sha256")),
+            expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")),
             expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")),
             expected_primary_td_receipt_sha256=sha256_file(paths["td"]),
             expected_confirmation_td_receipt_sha256=sha256_file(
@@ -3936,6 +4142,10 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
         "generated_at": utc_now(),
         "verification_run_id": verification_run_id,
         "commit": expected_commit,
+        "commit_full": expected_commit,
+        "commit_short": str(expected_commit)[:8],
+        "project_config_sha256": state.get("project_config_sha256"),
+        "td_source_manifest_sha256": state.get("td_source_manifest_sha256"),
         "source_state": state,
         "child_receipts": {
             name: {"path": str(paths[name]), "sha256": sha256_file(paths[name])}

+ 65 - 15
tools/prod2u_p4_normal_v3_build.py

@@ -12,11 +12,15 @@ from typing import Any, Mapping, Sequence
 
 
 SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
-COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
+FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
+SHORT_COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
+COMMIT_RE = FULL_COMMIT_RE
 BUILD_INFO_SCHEMA = "prod2u-simple-build-info-v1"
 COMPACT_TD_RECEIPT_SCHEMA = "prod2u-simple-td-build-receipt-v1"
-SYNTHESIS_INPUT_SCHEMA = "prod2u-simple-synthesis-inputs-v1"
+SYNTHESIS_INPUT_SCHEMA = "prod2u-simple-synthesis-inputs-v2"
 TARGET_DEVICE = "EF2L45BG256B"
+PROJECT_CONFIG_PATH = "projects/prod2u-door-temp/project.json"
+TD_SOURCE_MANIFEST_PATH = "src/generated/td-source-manifest.json"
 PRODUCTION_RTL_SOURCES = (
     "src/generated/prod2u_door_temp_params.vh",
     "src/common/uart_rx_byte.v",
@@ -69,6 +73,21 @@ def _canonical_sha256(value: Mapping[str, Any]) -> str:
     return hashlib.sha256(encoded).hexdigest()
 
 
+def _commit_fields(commit: str) -> dict[str, str]:
+    normalized = str(commit).strip().lower()
+    if FULL_COMMIT_RE.fullmatch(normalized):
+        short = normalized[:8]
+    elif SHORT_COMMIT_RE.fullmatch(normalized):
+        short = normalized
+    else:
+        raise ValueError("commit must be 40 or 8 lowercase hexadecimal characters")
+    return {
+        "commit": normalized,
+        "commit_full": normalized if FULL_COMMIT_RE.fullmatch(normalized) else "",
+        "commit_short": short,
+    }
+
+
 def build_synthesis_input_manifest(
     root: Path,
     _retired_metadata: Mapping[str, Any] | None = None,
@@ -85,30 +104,40 @@ def build_synthesis_input_manifest(
         "td/phy/prod2u_p4_normal_v3.tcl",
         "td/bitgen/prod2u_p4_normal_v3.tcl",
     ]
-    required = [*rtl, *fixed]
+    identity = [PROJECT_CONFIG_PATH, TD_SOURCE_MANIFEST_PATH]
+    required = [*rtl, *fixed, *identity]
     if not rtl:
         raise ValueError("missing synthesis input: src/rtl/*.v")
     missing = [relative for relative in required if not (source_root / relative).is_file()]
     if missing:
         raise ValueError(f"missing synthesis input: {missing[0]}")
     inputs = {relative: _sha256(source_root / relative) for relative in required}
+    manifest_binding = {
+        "inputs": inputs,
+        "project_config_path": PROJECT_CONFIG_PATH,
+        "project_config_sha256": inputs[PROJECT_CONFIG_PATH],
+        "td_source_manifest_path": TD_SOURCE_MANIFEST_PATH,
+        "td_source_manifest_sha256": inputs[TD_SOURCE_MANIFEST_PATH],
+    }
     return {
         "schema": SYNTHESIS_INPUT_SCHEMA,
         "inputs": inputs,
-        "sha256": _canonical_sha256(inputs),
+        "project_config_path": PROJECT_CONFIG_PATH,
+        "project_config_sha256": inputs[PROJECT_CONFIG_PATH],
+        "td_source_manifest_path": TD_SOURCE_MANIFEST_PATH,
+        "td_source_manifest_sha256": inputs[TD_SOURCE_MANIFEST_PATH],
+        "sha256": _canonical_sha256(manifest_binding),
     }
 
 
 def create_build_info(*, bitstream: Path, commit: str) -> dict[str, Any]:
     target = Path(bitstream)
-    normalized_commit = str(commit)
-    if not COMMIT_RE.fullmatch(normalized_commit):
-        raise ValueError("commit must be 8 lowercase hexadecimal characters")
+    commit_fields = _commit_fields(commit)
     if not target.is_file() or target.stat().st_size <= 0:
         raise FileNotFoundError(f"bitstream is missing or empty: {target}")
     return {
         "schema": BUILD_INFO_SCHEMA,
-        "commit": normalized_commit,
+        **commit_fields,
         "bitstream_sha256": _sha256(target),
         "target_device": TARGET_DEVICE,
         "serial": {"baud": 115200, "format": "8N1", "flow_control": "none"},
@@ -123,7 +152,7 @@ def create_build_info(*, bitstream: Path, commit: str) -> dict[str, Any]:
 
 def validate_build_info(value: Mapping[str, Any]) -> dict[str, Any]:
     failures: list[str] = []
-    expected = {
+    required = {
         "schema",
         "commit",
         "bitstream_sha256",
@@ -131,12 +160,25 @@ def validate_build_info(value: Mapping[str, Any]) -> dict[str, Any]:
         "serial",
         "hardware_access",
     }
-    if set(value) != expected:
+    allowed = required | {"commit_full", "commit_short"}
+    if not required.issubset(value) or not set(value).issubset(allowed):
         failures.append("build_info_fields_mismatch")
     if value.get("schema") != BUILD_INFO_SCHEMA:
         failures.append("build_info_schema_mismatch")
-    if not COMMIT_RE.fullmatch(str(value.get("commit", ""))):
+    commit = str(value.get("commit", ""))
+    commit_full = str(value.get("commit_full", ""))
+    commit_short = str(value.get("commit_short", ""))
+    if not (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit)):
         failures.append("commit_invalid")
+    if commit_full and not FULL_COMMIT_RE.fullmatch(commit_full):
+        failures.append("commit_full_invalid")
+    if commit_short and not SHORT_COMMIT_RE.fullmatch(commit_short):
+        failures.append("commit_short_invalid")
+    if FULL_COMMIT_RE.fullmatch(commit):
+        if commit_full not in {"", commit}:
+            failures.append("commit_full_mismatch")
+        if commit_short not in {"", commit[:8]}:
+            failures.append("commit_short_mismatch")
     if not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))):
         failures.append("bitstream_sha256_invalid")
     if value.get("target_device") != TARGET_DEVICE:
@@ -168,18 +210,17 @@ def create_compact_td_receipt(value: Mapping[str, Any]) -> dict[str, Any]:
     commit = str(value.get("commit", ""))
     digest = str(value.get("bitstream_sha256", ""))
     synthesis_hash = str(value.get("synthesis_input_hash", ""))
-    if not COMMIT_RE.fullmatch(commit):
-        raise ValueError("TD build receipt has an invalid commit")
+    commit_fields = _commit_fields(commit)
     if not SHA256_RE.fullmatch(digest):
         raise ValueError("TD build receipt has an invalid bitstream SHA256")
     if not SHA256_RE.fullmatch(synthesis_hash):
         raise ValueError("TD build receipt has an invalid synthesis input hash")
-    return {
+    payload = {
         "schema": COMPACT_TD_RECEIPT_SCHEMA,
         "status": validation_status,
         "image_available": True,
         "validation_passed": validation_status == "pass",
-        "commit": commit,
+        **commit_fields,
         "bitstream_sha256": digest,
         "synthesis_input_hash": synthesis_hash,
         "resources": value.get("resources"),
@@ -187,6 +228,15 @@ def create_compact_td_receipt(value: Mapping[str, Any]) -> dict[str, Any]:
         "structural_gate": value.get("structural_gate"),
         "source_binding_gate": value.get("source_binding_gate"),
     }
+    for field in ("project_config_sha256", "td_source_manifest_sha256"):
+        candidate = value.get(field)
+        if candidate is None and isinstance(value.get("source_state"), Mapping):
+            candidate = value["source_state"].get(field)
+        if candidate is not None:
+            if not SHA256_RE.fullmatch(str(candidate)):
+                raise ValueError(f"TD build receipt has an invalid {field}")
+            payload[field] = str(candidate)
+    return payload
 
 
 def verification_layers_for_paths(paths: Sequence[str | Path]) -> list[str]: