瀏覽代碼

chore(delivery): switch artifacts to sha8

Codex Resource Selftest 4 月之前
父節點
當前提交
1e38a933b6

+ 3 - 3
README.zh-CN.md

@@ -14,7 +14,7 @@
 - `busy_mask`、`fault_mask` 和 `position_valid_mask` 恒为 0,current/target 恒为 `0xFF`。
 - DISABLE、watchdog 和 LS 都不会停止电机;异常时必须断电、复位或重新配置 CPLD。
 - LS1/X=`B9`、LS2/Y=`A11`,A5 不使用。
-- 版本号为完整 Git commit,不在设备运行时发送额外身份帧。
+- 版本号统一使用 8 位小写 Git SHA,不在设备运行时发送额外身份帧。
 
 ## 离线验证
 
@@ -60,7 +60,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
   -ConfirmationTdReceipt '<td-b-path>\receipt.json' `
   -ValidationReceipt '<strict-offline-path>\receipt.json'
 
-$commit = (git rev-parse HEAD).Trim().ToLowerInvariant()
+$commit = (git rev-parse --short=8 HEAD).Trim().ToLowerInvariant()
 $bitstreamSha256 = (Get-FileHash -Algorithm SHA256 '<td-bitgen-path>\prod2u_p4_normal_v3.bit').Hash.ToLowerInvariant()
 $packageDir = "C:\Users\Administrator\CodexTemp\p4-normal-images\$commit\prod2u-p4-normal-$commit-$($bitstreamSha256.Substring(0, 16))"
 
@@ -78,7 +78,7 @@ python tools\prod2u_p4_harness.py p4-normal-v3-final-gate `
   --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-final-gate-v3-receipt.json
 ```
 
-输出固定为 `C:\Users\Administrator\CodexTemp\p4-normal-images\<40位commit>\prod2u-p4-normal-<40位commit>-<bitstream-sha256前16位>`。包内包含两份 TD receipt/报告、验证矩阵、包自检结果、SRAM 脚本、初始化 DISABLE、通用 HEX 发送方法以及兼容 Snapshot 和 JOG 的冻结 HEX。
+输出固定为 `C:\Users\Administrator\CodexTemp\p4-normal-images\<8位小写SHA>\prod2u-p4-normal-<8位小写SHA>-<bitstream-sha256前16位>`。包内包含两份 TD receipt/报告、验证矩阵、包自检结果、SRAM 脚本、初始化 DISABLE、通用 HEX 发送方法以及兼容 Snapshot 和 JOG 的冻结 HEX。
 
 strict offline、两次 TD、打包自检和 final gate 必须显式使用同一个 32 位小写十六进制 `verification_run_id`。最终 normal dual-TD 交付只接受两份独立 TD receipt 的 bitstream SHA-256 完全相同;run ID、位流或包内验证 receipt 任一不一致都会 fail closed。
 

+ 1 - 1
config/prod2u_p4_normal_host_contract_v4.json

@@ -3,7 +3,7 @@
   "profile": "prod2u-p4-normal-actuator-binary921-v3",
   "profile_id": 4,
   "protocol": "binary921-v3",
-  "version_source": "full_git_commit",
+  "version_source": "lowercase_git_sha8",
   "wire": {
     "magic_hex": "A55A",
     "version": 2,

+ 1 - 1
schemas/prod2u_p4_normal_host_contract_v4.schema.json

@@ -25,7 +25,7 @@
     "profile": {"const": "prod2u-p4-normal-actuator-binary921-v3"},
     "profile_id": {"const": 4},
     "protocol": {"const": "binary921-v3"},
-    "version_source": {"const": "full_git_commit"},
+    "version_source": {"const": "lowercase_git_sha8"},
     "wire": {
       "type": "object",
       "required": [

+ 1 - 1
schemas/prod2u_p4_normal_v3_final_gate_receipt.schema.json

@@ -13,7 +13,7 @@
     "status": {"enum": ["pass", "fail"]},
     "generated_at": {"type": "string", "minLength": 1},
     "verification_run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
-    "commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
+    "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
     "source_state": {"type": "object"},
     "child_receipts": {
       "type": "object",

+ 1 - 1
schemas/prod2u_p4_normal_v3_offline_gate_receipt.schema.json

@@ -11,7 +11,7 @@
     "schema": {"const": "prod2u-p4-normal-v3-strict-offline-gate-v1"},
     "status": {"enum": ["pass", "fail"]},
     "verification_run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
-    "commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
+    "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
     "source_state": {"type": "object"},
     "profile": {"const": "prod2u_p4_normal_v3"},
     "runtime_profile": {"const": "prod2u-p4-normal-actuator-binary921-v3"},

+ 1 - 1
schemas/prod2u_p4_normal_v3_package_selftest_receipt.schema.json

@@ -19,7 +19,7 @@
     "status": {"enum": ["pass", "fail"]},
     "generated_at": {"type": "string", "minLength": 1},
     "verification_run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
-    "commit": {"type": ["string", "null"], "pattern": "^[0-9a-f]{40}$"},
+    "commit": {"type": ["string", "null"], "pattern": "^[0-9a-f]{8}$"},
     "bitstream_sha256": {"type": ["string", "null"], "pattern": "^[0-9a-f]{64}$"},
     "package_dir": {"type": "string", "minLength": 1},
     "delivery_mode": {"enum": ["normal_dual_td", "urgent_single_td", null]},

+ 1 - 1
schemas/prod2u_p4_normal_v3_resource_baseline.schema.json

@@ -42,7 +42,7 @@
       },
       "additionalProperties": true
     },
-    "measured_commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
+    "measured_commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
     "synthesis_input_hash": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
     "envelope": {"type": "object"}
   },

+ 1 - 1
schemas/prod2u_p4_normal_v3_td_build_receipt.schema.json

@@ -20,7 +20,7 @@
     "verification_run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
     "run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
     "work_root": {"type": "string", "pattern": "^[A-Za-z]:[\\\\/]"},
-    "commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
+    "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
     "bitstream_sha256": {"type": ["string", "null"], "pattern": "^[0-9a-f]{64}$"},
     "synthesis_input_hash": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
     "resources": {"type": ["object", "null"]},

+ 1 - 1
schemas/prod2u_program_sram_receipt.schema.json

@@ -43,7 +43,7 @@
       "properties": {
         "path": {"type": "string", "minLength": 1},
         "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
-        "commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"}
+        "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"}
       },
       "additionalProperties": true
     },

+ 119 - 26
tests/unit/test_prod2u_p4_harness.py

@@ -109,7 +109,7 @@ def valid_resources() -> dict[str, object]:
     }
 
 
-def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, object]:
+def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 8) -> dict[str, object]:
     digest = harness.sha256_file(bitstream)
     observed_pins = {
         row["name"]: row
@@ -187,7 +187,7 @@ def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, ob
     }
 
 
-def valid_offline_receipt(*, commit: str = "a" * 40) -> dict[str, object]:
+def valid_offline_receipt(*, commit: str = "a" * 8) -> dict[str, object]:
     layers = {
         name: {"status": "pass"}
         for name in ("source_integrity", "unit", "hdl_sim", "formal")
@@ -208,7 +208,7 @@ def valid_package_receipt(
     package: Path,
     *,
     digest: str,
-    commit: str = "a" * 40,
+    commit: str = "a" * 8,
 ) -> dict[str, object]:
     return {
         "schema": harness.PACKAGE_RECEIPT_SCHEMA,
@@ -231,7 +231,7 @@ def materialize_valid_package(
     package: Path,
     *,
     bitstream_bytes: bytes = b"package-final-gate",
-    commit: str = "a" * 40,
+    commit: str = "a" * 8,
 ) -> tuple[dict[str, object], dict[str, object], dict[str, object]]:
     package.mkdir(parents=True)
     bitstream = package / "fw.bit"
@@ -631,6 +631,70 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             {"pass", "fail", "running", "not_run"},
         )
 
+    def test_all_external_commit_schemas_accept_only_lowercase_sha8(self) -> None:
+        schema_fields = {
+            "prod2u_p4_normal_v3_final_gate_receipt.schema.json": (
+                "properties",
+                "commit",
+            ),
+            "prod2u_p4_normal_v3_offline_gate_receipt.schema.json": (
+                "properties",
+                "commit",
+            ),
+            "prod2u_p4_normal_v3_package_selftest_receipt.schema.json": (
+                "properties",
+                "commit",
+            ),
+            "prod2u_p4_normal_v3_resource_baseline.schema.json": (
+                "properties",
+                "measured_commit",
+            ),
+            "prod2u_p4_normal_v3_td_build_receipt.schema.json": ("properties", "commit"),
+            "prod2u_program_sram_receipt.schema.json": (
+                "properties",
+                "bitstream",
+                "properties",
+                "commit",
+            ),
+        }
+        invalid = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
+
+        for filename, path in schema_fields.items():
+            with self.subTest(schema=filename):
+                value = json.loads(
+                    (ROOT / "schemas" / filename).read_text(encoding="utf-8")
+                )
+                for component in path:
+                    value = value[component]
+                pattern = value["pattern"]
+                self.assertIsNotNone(re.fullmatch(pattern, "abcdef12"))
+                for rejected in invalid:
+                    self.assertIsNone(re.fullmatch(pattern, rejected), rejected)
+
+    def test_source_state_validates_full_head_but_exposes_only_sha8(self) -> None:
+        full_commit = "abcdef12" + ("3" * 32)
+        results = (
+            subprocess.CompletedProcess(
+                ["git"], 0, stdout=full_commit + "\n", stderr=""
+            ),
+            subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
+        )
+        with mock.patch.object(harness, "_git", side_effect=results) as git:
+            observed = harness.source_state()
+
+        self.assertEqual(observed["status"], "pass")
+        self.assertEqual(observed["commit"], "abcdef12")
+        git.assert_any_call("rev-parse", "HEAD")
+
+        invalid_results = (
+            subprocess.CompletedProcess(["git"], 0, stdout="abcdef12\n", stderr=""),
+            subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
+        )
+        with mock.patch.object(harness, "_git", side_effect=invalid_results):
+            invalid = harness.source_state()
+        self.assertEqual(invalid["status"], "fail")
+        self.assertIn("git_commit_unavailable", invalid["failures"])
+
     def test_td_receipt_identifiers_are_valid_and_canonically_independent(self) -> None:
         schema = json.loads(
             (
@@ -789,7 +853,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
     def test_external_clean_staging_rechecks_synthesis_hash(self) -> None:
         clean_state = {
             "status": "pass",
-            "commit": "a" * 40,
+            "commit": "a" * 8,
             "clean": True,
             "tracked_changes": [],
             "failures": [],
@@ -800,7 +864,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             verified = harness.verify_staged_source_manifest(staged)
 
         self.assertEqual(verified["status"], "pass", verified["failures"])
-        self.assertEqual(staged.source_state["commit"], "a" * 40)
+        self.assertEqual(staged.source_state["commit"], "a" * 8)
         self.assertEqual(
             staged.synthesis_input_manifest["sha256"],
             harness.build_synthesis_input_manifest(ROOT)["sha256"],
@@ -962,7 +1026,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             bitstream.write_bytes(b"minimal-final-gate")
             baseline = valid_td_receipt(bitstream)
             self.assertEqual(
-                harness._td_final_failures(baseline, label="td", expected_commit="a" * 40),
+                harness._td_final_failures(baseline, label="td", expected_commit="a" * 8),
                 [],
             )
 
@@ -973,7 +1037,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                     failures = harness._td_final_failures(
                         forged,
                         label="td",
-                        expected_commit="a" * 40,
+                        expected_commit="a" * 8,
                     )
                     self.assertTrue(any(f"resource:{resource}:" in item for item in failures))
 
@@ -992,7 +1056,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                         harness._td_final_failures(
                             forged,
                             label="td",
-                            expected_commit="a" * 40,
+                            expected_commit="a" * 8,
                         )
                     )
 
@@ -1000,7 +1064,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             failures = harness._td_final_failures(
                 baseline,
                 label="td",
-                expected_commit="a" * 40,
+                expected_commit="a" * 8,
             )
             self.assertIn("td:bitstream_file_hash", failures)
 
@@ -1015,7 +1079,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             self.assertEqual(
                 harness._package_final_failures(
                     receipt,
-                    expected_commit="a" * 40,
+                    expected_commit="a" * 8,
                     expected_bitstream_sha256=digest,
                     expected_primary_td_receipt_sha256=primary_sha,
                     expected_confirmation_td_receipt_sha256=confirmation_sha,
@@ -1025,26 +1089,26 @@ class Prod2UP4HarnessTests(unittest.TestCase):
 
             info_path = package / "package-info.json"
             info = json.loads(info_path.read_text(encoding="utf-8"))
-            info["commit"] = "b" * 40
+            info["commit"] = "b" * 8
             info_path.write_text(json.dumps(info), encoding="utf-8")
             self.assertIn(
                 "package:info_binding",
                 harness._package_final_failures(
                     receipt,
-                    expected_commit="a" * 40,
+                    expected_commit="a" * 8,
                     expected_bitstream_sha256=digest,
                     expected_primary_td_receipt_sha256=primary_sha,
                     expected_confirmation_td_receipt_sha256=confirmation_sha,
                 ),
             )
-            info["commit"] = "a" * 40
+            info["commit"] = "a" * 8
             info_path.write_text(json.dumps(info), encoding="utf-8")
             (package / "fw.bit").write_bytes(b"tampered")
             self.assertIn(
                 "package:file_hash",
                 harness._package_final_failures(
                     receipt,
-                    expected_commit="a" * 40,
+                    expected_commit="a" * 8,
                     expected_bitstream_sha256=digest,
                     expected_primary_td_receipt_sha256=primary_sha,
                     expected_confirmation_td_receipt_sha256=confirmation_sha,
@@ -1057,7 +1121,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 "package:verification_incomplete",
                 harness._package_final_failures(
                     incomplete,
-                    expected_commit="a" * 40,
+                    expected_commit="a" * 8,
                     expected_bitstream_sha256=digest,
                     expected_primary_td_receipt_sha256=primary_sha,
                     expected_confirmation_td_receipt_sha256=confirmation_sha,
@@ -1081,7 +1145,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 mutate(package, receipt)
                 failures = harness._package_final_failures(
                     receipt,
-                    expected_commit="a" * 40,
+                    expected_commit="a" * 8,
                     expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
                     expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
                     expected_confirmation_td_receipt_sha256=str(
@@ -1098,7 +1162,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             receipt, _, _ = materialize_valid_package(package)
             failures = harness._package_final_failures(
                 receipt,
-                expected_commit="a" * 40,
+                expected_commit="a" * 8,
                 expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
                 expected_primary_td_receipt_sha256="0" * 64,
                 expected_confirmation_td_receipt_sha256="1" * 64,
@@ -1122,7 +1186,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             failures = harness._td_final_failures(
                 receipt,
                 label="td",
-                expected_commit="a" * 40,
+                expected_commit="a" * 8,
             )
 
         self.assertIn("td:structural_gate:cdc", failures)
@@ -1151,10 +1215,39 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             observed["failures"],
         )
 
+    def test_package_selftest_rejects_every_non_sha8_commit_form(self) -> None:
+        invalid_commits = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
+        for commit in invalid_commits:
+            with self.subTest(commit=commit), tempfile.TemporaryDirectory(
+                dir=ROOT.parent
+            ) as temporary:
+                digest = hashlib.sha256(b"invalid-commit-package").hexdigest()
+                package = (
+                    Path(temporary)
+                    / commit
+                    / f"prod2u-p4-normal-{commit}-{digest[:16]}"
+                )
+                materialize_valid_package(
+                    package,
+                    bitstream_bytes=b"invalid-commit-package",
+                    commit=commit,
+                )
+                completed = subprocess.CompletedProcess(
+                    ["powershell.exe"], 0, stdout="selftest pass", stderr=""
+                )
+                with mock.patch.object(harness.subprocess, "run", return_value=completed):
+                    observed = harness.package_selftest_payload(
+                        package,
+                        verification_run_id=VERIFICATION_RUN_ID,
+                    )
+
+                self.assertEqual(observed["status"], "fail")
+                self.assertIn("package_commit_invalid", observed["failures"])
+
     def test_package_validator_preserves_running_but_final_gate_rejects_it(self) -> None:
         bitstream_bytes = b"running-validation-package"
         digest = hashlib.sha256(bitstream_bytes).hexdigest()
-        commit = "a" * 40
+        commit = "a" * 8
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             package = (
                 Path(temporary)
@@ -1204,7 +1297,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             with self.subTest(field=field), tempfile.TemporaryDirectory(
                 dir=ROOT.parent
             ) as temporary:
-                commit = "a" * 40
+                commit = "a" * 8
                 digest = hashlib.sha256(b"independent-package-selftest").hexdigest()
                 package = (
                     Path(temporary)
@@ -1238,7 +1331,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
     def test_urgent_validator_allows_running_td_confirmation_only(self) -> None:
         bitstream_bytes = b"urgent-running-confirmation"
         digest = hashlib.sha256(bitstream_bytes).hexdigest()
-        commit = "a" * 40
+        commit = "a" * 8
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             package = (
                 Path(temporary)
@@ -1336,7 +1429,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 mock.patch.object(
                     harness,
                     "source_state",
-                    return_value={"status": "pass", "commit": "a" * 40, "clean": True},
+                    return_value={"status": "pass", "commit": "a" * 8, "clean": True},
                 ),
                 mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
             ):
@@ -1367,7 +1460,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 mock.patch.object(
                     harness,
                     "source_state",
-                    return_value={"status": "pass", "commit": "a" * 40, "clean": True},
+                    return_value={"status": "pass", "commit": "a" * 8, "clean": True},
                 ),
                 mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
             ):
@@ -1382,7 +1475,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 mock.patch.object(
                     harness,
                     "source_state",
-                    return_value={"status": "pass", "commit": "a" * 40, "clean": True},
+                    return_value={"status": "pass", "commit": "a" * 8, "clean": True},
                 ),
                 mock.patch.object(
                     harness,
@@ -1406,7 +1499,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 mock.patch.object(
                     harness,
                     "source_state",
-                    return_value={"status": "fail", "commit": "a" * 40, "clean": False},
+                    return_value={"status": "fail", "commit": "a" * 8, "clean": False},
                 ),
                 mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
             ):

+ 90 - 6
tests/unit/test_prod2u_p4_minimal_delivery_contract.py

@@ -151,7 +151,7 @@ def _create_clean_package_fixture(
     _git(source, "config", "user.name", "Minimal delivery contract")
     _git(source, "add", ".")
     _git(source, "commit", "-m", "fixture")
-    return source, _git(source, "rev-parse", "HEAD")
+    return source, _git(source, "rev-parse", "HEAD")[:8]
 
 
 def _artifact(path: Path) -> dict[str, object]:
@@ -196,6 +196,7 @@ def _build_package(
     running_validation_layers: tuple[str, ...] = (),
     dirty_source: bool = False,
     untracked_source: bool = False,
+    commit_argument: str | None = None,
 ) -> tuple[Path, str, str]:
     source, commit = _create_clean_package_fixture(root, selftest_fails=selftest_fails)
     if dirty_source:
@@ -359,6 +360,11 @@ def _build_package(
         _ps_literal(layer) for layer in running_validation_layers
     ) + ")"
     invocation = root / "invoke-package.ps1"
+    explicit_commit = (
+        commit_argument.replace("{commit}", commit).replace("{COMMIT}", commit.upper())
+        if commit_argument is not None
+        else None
+    )
     invocation.write_text(
         "$ErrorActionPreference = 'Stop'\n"
         + "& " + _ps_literal(source / "tools" / f"package_{STEM}.ps1") + " `\n"
@@ -371,6 +377,11 @@ def _build_package(
         + " `\n"
         + "    -ValidationReceipt " + validation_array + " `\n"
         + "    -WheelhouseRoot " + _ps_literal(wheelhouse)
+        + (
+            " `\n    -Commit " + _ps_literal(explicit_commit)
+            if explicit_commit is not None
+            else ""
+        )
         + (" `\n    -UrgentSingleTd" if urgent_single_td else "")
         + (
             " `\n    -RunningValidationLayer " + running_array
@@ -499,7 +510,7 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
         compact = build_helpers.create_compact_td_receipt(
             {
                 "status": "fail",
-                "commit": "a" * 40,
+                "commit": "abcdef12",
                 "bitstream_sha256": "b" * 64,
                 "synthesis_input_hash": "c" * 64,
                 "resources": {"utilization": {}},
@@ -511,6 +522,79 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
         self.assertTrue(compact["image_available"])
         self.assertFalse(compact["validation_passed"])
 
+    def test_build_metadata_accepts_only_lowercase_sha8(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            bitstream = Path(temporary) / "fw.bit"
+            bitstream.write_bytes(b"sha8-build-info")
+            accepted = build_helpers.create_build_info(
+                bitstream=bitstream,
+                commit="abcdef12",
+            )
+
+            self.assertEqual(accepted["commit"], "abcdef12")
+            for invalid in (
+                "a" * 7,
+                "a" * 9,
+                "a" * 40,
+                "ABCDEF12",
+                " abcdef12",
+                "abcdef12 ",
+            ):
+                with self.subTest(invalid=invalid), self.assertRaisesRegex(
+                    ValueError, "8 lowercase hexadecimal"
+                ):
+                    build_helpers.create_build_info(
+                        bitstream=bitstream,
+                        commit=invalid,
+                    )
+
+        receipt = {
+            "status": "fail",
+            "commit": "abcdef12",
+            "bitstream_sha256": "b" * 64,
+            "synthesis_input_hash": "c" * 64,
+            "resources": {"utilization": {}},
+            "timing": {"worst_setup_slack_ns": -0.1},
+        }
+        self.assertEqual(
+            build_helpers.create_compact_td_receipt(receipt)["commit"],
+            "abcdef12",
+        )
+        for invalid in (
+            "a" * 7,
+            "a" * 9,
+            "a" * 40,
+            "ABCDEF12",
+            " abcdef12",
+            "abcdef12 ",
+        ):
+            with self.subTest(receipt_commit=invalid), self.assertRaisesRegex(
+                ValueError, "invalid commit"
+            ):
+                build_helpers.create_compact_td_receipt({**receipt, "commit": invalid})
+
+    def test_packager_rejects_non_exact_explicit_commit_argument(self) -> None:
+        invalid_arguments = (
+            " {commit}",
+            "{commit} ",
+            "{COMMIT}",
+            "a" * 7,
+            "a" * 9,
+            "a" * 40,
+        )
+        for argument in invalid_arguments:
+            with self.subTest(argument=argument), tempfile.TemporaryDirectory(
+                dir=ROOT.parent
+            ) as temporary:
+                with self.assertRaisesRegex(
+                    AssertionError,
+                    "Commit must be an 8-digit lowercase Git object id",
+                ):
+                    _build_package(
+                        Path(temporary),
+                        commit_argument=argument,
+                    )
+
     def test_production_rtl_and_td_have_no_trace_boot_build_id_or_temperature_logic(self) -> None:
         rtl_files = sorted((ROOT / "src" / "rtl").glob("*.v"))
         rtl_files += sorted((ROOT / "src" / "top").glob("*.v"))
@@ -580,7 +664,7 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
         self.assertIn(DISABLE_HEX, re.sub(r"\s+", "", initialize_text).upper())
         self.assertNotRegex(initialize_text, r"(?i)(?:trace|0x0f|boot_build_id|build_id)")
 
-    def test_package_name_and_manifest_use_full_commit_and_bitstream_hash(self) -> None:
+    def test_package_name_and_manifest_use_sha8_and_bitstream_hash(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             package, commit, bitstream_sha256 = _build_package(Path(temporary))
             package_info = json.loads((package / "package-info.json").read_text(encoding="utf-8"))
@@ -762,7 +846,7 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
         cases = (
             ("empty bitstream", {"bitstream_bytes": b""}, "bitstream"),
             ("receipt schema", {"primary_schema": "legacy-receipt"}, "schema"),
-            ("commit mismatch", {"primary_commit": "f" * 40}, "commit"),
+            ("commit mismatch", {"primary_commit": "f" * 8}, "commit"),
             ("hash mismatch", {"primary_hash": "0" * 64}, "hash"),
             (
                 "dirty receipt source",
@@ -771,7 +855,7 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
             ),
             (
                 "receipt source commit",
-                {"primary_source_commit": "f" * 40},
+                {"primary_source_commit": "f" * 8},
                 "source state",
             ),
             (
@@ -1102,7 +1186,7 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
                 AssertionError,
                 "Confirmation TD receipt commit does not match package commit",
             ):
-                _build_package(Path(temporary), confirmation_commit="f" * 40)
+                _build_package(Path(temporary), confirmation_commit="f" * 8)
 
     def test_packager_rejects_confirmation_bitstream_that_differs_from_primary(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:

+ 1 - 1
tests/unit/test_prod2u_p4_protocol_v3.py

@@ -156,7 +156,7 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
         )
 
         self.assertEqual(contract["profile"], "prod2u-p4-normal-actuator-binary921-v3")
-        self.assertEqual(contract["version_source"], "full_git_commit")
+        self.assertEqual(contract["version_source"], "lowercase_git_sha8")
         self.assertEqual(contract["wire"]["ordinary_response_order"], ["HOST_ACK"])
         self.assertEqual(
             contract["wire"]["motor_status_response_order"],

+ 1 - 1
tests/unit/test_prod2u_p4_retirement_contract.py

@@ -102,7 +102,7 @@ class Prod2UP4RetirementContractTests(unittest.TestCase):
         )
 
         self.assertEqual(contract["profile"], "prod2u-p4-normal-actuator-binary921-v3")
-        self.assertEqual(contract["version_source"], "full_git_commit")
+        self.assertEqual(contract["version_source"], "lowercase_git_sha8")
         self.assertFalse(contract["wire"]["unsolicited_frames"])
         serialized = json.dumps(contract, sort_keys=True).casefold()
         for retired in ("trace_event", "boot_build_id", "build_id", "capability_flags"):

+ 1 - 1
tests/unit/test_prod2u_p4_wrapper_v3.py

@@ -72,7 +72,7 @@ class Prod2UP4WrapperV3Tests(unittest.TestCase):
         self.assertIn("attempt_count = 1", source)
         self.assertIn("speed_hz = 200000", source)
         self.assertIn("no retry was attempted", source)
-        self.assertIn("$info.commit -notmatch '^[0-9a-f]{40}$'", source)
+        self.assertIn("$info.commit -cnotmatch '^[0-9a-f]{8}$'", source)
         self.assertIn('$stage = Join-Path "C:\\P2U" ([string]$info.commit)', source)
         self.assertNotRegex(source, r"(?i)build[_-]?id")
         for forbidden in (

+ 16 - 10
tools/package_prod2u_p4_normal_v3.ps1

@@ -71,20 +71,24 @@ function Resolve-Git {
 
 function Resolve-Commit([string]$Requested) {
     $git = Resolve-Git
-    $head = (& $git -C $repo rev-parse HEAD).Trim().ToLowerInvariant()
-    if ($LASTEXITCODE -ne 0 -or $head -notmatch '^[0-9a-f]{40}$') {
+    $headFull = (& $git -C $repo rev-parse HEAD).Trim().ToLowerInvariant()
+    if ($LASTEXITCODE -ne 0 -or $headFull -cnotmatch '^[0-9a-f]{40}$') {
         throw "Unable to resolve package commit"
     }
+    $headShort = $headFull.Substring(0, 8)
     if ($Requested) {
-        $requestedCommit = $Requested.Trim().ToLowerInvariant()
-        if ($requestedCommit -notmatch '^[0-9a-f]{40}$') {
-            throw "Commit must be a 40-digit lowercase Git object id"
+        $requestedCommit = $Requested
+        if ($requestedCommit -cnotmatch '^[0-9a-f]{8}$') {
+            throw "Commit must be an 8-digit lowercase Git object id"
         }
-        if ($requestedCommit -ne $head) {
+        if ($requestedCommit -cne $headShort) {
             throw "Explicit Commit does not match repository HEAD"
         }
     }
-    return $head
+    return [ordered]@{
+        full = $headFull
+        short = $headShort
+    }
 }
 
 function Resolve-RepoRelativePath([string]$Path, [string]$Label) {
@@ -568,9 +572,11 @@ foreach ($relative in $sourceRelatives) {
     Assert-File (Join-Path $repo $relative) "Package source $relative"
 }
 
-$resolvedCommit = Resolve-Commit $Commit
+$commitBinding = Resolve-Commit $Commit
+$resolvedFullCommit = [string]$commitBinding.full
+$resolvedCommit = [string]$commitBinding.short
 $git = Resolve-Git
-Assert-CleanCommittedSources $git $resolvedCommit $sourceRelatives
+Assert-CleanCommittedSources $git $resolvedFullCommit $sourceRelatives
 
 $bitstreamSha256 = Get-Sha256 $NormalBitstream
 $tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
@@ -642,7 +648,7 @@ New-Item -ItemType Directory -Path $stage | Out-Null
 
 try {
     $sourceSnapshot = Join-Path $stage ".source-snapshot"
-    New-CommitSourceSnapshot $git $resolvedCommit $sourceRelatives $sourceSnapshot
+    New-CommitSourceSnapshot $git $resolvedFullCommit $sourceRelatives $sourceSnapshot
 
     $configDir = Join-Path $stage "config"
     $evidenceDir = Join-Path $stage "evidence"

+ 1 - 1
tools/package_templates/PROGRAM_SRAM.ps1

@@ -13,7 +13,7 @@ $source = Join-Path $root "fw.bit"
 $info = Get-Content -LiteralPath $infoPath -Raw -Encoding UTF8 | ConvertFrom-Json
 $observed = (Get-FileHash -Algorithm SHA256 -LiteralPath $source).Hash.ToLowerInvariant()
 if ($observed -ne [string]$info.bitstream_sha256) { throw "bitstream hash mismatch" }
-if ([string]$info.commit -notmatch '^[0-9a-f]{40}$') { throw "package commit is invalid" }
+if ([string]$info.commit -cnotmatch '^[0-9a-f]{8}$') { throw "package commit is invalid" }
 
 $active = @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
     $_.ProcessName -in @("td", "bw", "bw_commands_prompt")

+ 1 - 1
tools/package_templates/selftest.ps1

@@ -99,7 +99,7 @@ if ($deliveryMode -eq "normal_dual_td") {
     }
 }
 $commit = [string]$info.commit
-if ($commit -notmatch '^[0-9a-f]{40}$') { throw "package commit is invalid" }
+if ($commit -cnotmatch '^[0-9a-f]{8}$') { throw "package commit is invalid" }
 $firmware = Join-Path $root "fw.bit"
 $bitstreamSha256 = Get-BoundSha256 $firmware
 if ([string]$info.bitstream_sha256 -ne $bitstreamSha256) {

+ 13 - 6
tools/prod2u_p4_harness.py

@@ -415,7 +415,12 @@ def _git(*args: str) -> subprocess.CompletedProcess[str]:
 def source_state() -> dict[str, Any]:
     commit_result = _git("rev-parse", "HEAD")
     status_result = _git("status", "--porcelain", "--untracked-files=all")
-    commit = commit_result.stdout.strip().lower()
+    full_commit = commit_result.stdout.strip().lower()
+    commit = (
+        full_commit[:8]
+        if re.fullmatch(r"[0-9a-f]{40}", full_commit)
+        else full_commit
+    )
     changes = []
     for line in status_result.stdout.splitlines():
         if not line.strip():
@@ -425,7 +430,9 @@ def source_state() -> dict[str, Any]:
             continue
         changes.append(line)
     failures: list[str] = []
-    if commit_result.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", commit):
+    if commit_result.returncode != 0 or not re.fullmatch(
+        r"[0-9a-f]{40}", full_commit
+    ):
         failures.append("git_commit_unavailable")
     if status_result.returncode != 0:
         failures.append("git_status_unavailable")
@@ -3046,18 +3053,18 @@ def package_selftest_payload(
             if confirmation_td_present is not False:
                 failures.append("urgent_confirmation_td_present_must_be_false")
         commit = str(info.get("commit", ""))
-        if not re.fullmatch(r"[0-9a-f]{40}", commit):
+        if not re.fullmatch(r"[0-9a-f]{8}", commit):
             failures.append("package_commit_invalid")
         if info.get("bitstream_sha256") != digest:
             failures.append("package_bitstream_sha256_mismatch")
         expected_name = (
             f"prod2u-p4-normal-{commit}-{digest[:16]}"
-            if digest is not None and re.fullmatch(r"[0-9a-f]{40}", commit)
+            if digest is not None and re.fullmatch(r"[0-9a-f]{8}", 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]{40}", commit) and package.parent.name != commit:
+        if re.fullmatch(r"[0-9a-f]{8}", commit) and package.parent.name != commit:
             failures.append("package_commit_parent_mismatch")
         if info.get("td_receipt_sha256") != (
             sha256_file(primary_td_path) if primary_td_path.is_file() else None
@@ -3718,7 +3725,7 @@ 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]{40}", str(expected_commit))
+        or not re.fullmatch(r"[0-9a-f]{8}", str(expected_commit))
     ):
         failures = ["final_source_state_not_clean"]
     else:

+ 3 - 3
tools/prod2u_p4_normal_v3_build.py

@@ -12,7 +12,7 @@ from typing import Any, Mapping, Sequence
 
 
 SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
-COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
+COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
 BUILD_INFO_SCHEMA = "prod2u-p4-normal-v3-build-info-v2"
 COMPACT_TD_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-td-build-compact-receipt-v3"
 SYNTHESIS_INPUT_SCHEMA = "prod2u-p4-normal-v3-synthesis-inputs-v2"
@@ -97,9 +97,9 @@ def build_synthesis_input_manifest(
 
 def create_build_info(*, bitstream: Path, commit: str) -> dict[str, Any]:
     target = Path(bitstream)
-    normalized_commit = str(commit).strip().lower()
+    normalized_commit = str(commit)
     if not COMMIT_RE.fullmatch(normalized_commit):
-        raise ValueError("commit must be 40 lowercase hexadecimal characters")
+        raise ValueError("commit must be 8 lowercase hexadecimal characters")
     if not target.is_file() or target.stat().st_size <= 0:
         raise FileNotFoundError(f"bitstream is missing or empty: {target}")
     return {