test_codex_harness.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import hashlib
  2. import json
  3. import re
  4. import subprocess
  5. import tempfile
  6. import unittest
  7. import xml.etree.ElementTree as ET
  8. from pathlib import Path
  9. from unittest.mock import patch
  10. from tools import codex_harness
  11. from tools import prod2u_p4_harness
  12. from tools import prod2u_p4_normal_v3_build
  13. ROOT = Path(__file__).resolve().parents[2]
  14. PROJECT = ROOT / "projects" / "prod2u-door-temp" / "project.json"
  15. CONVERGENCE_RUN_ID = "b2a3230e66f74a35bb74ac6730e58bb5"
  16. CONVERGENCE_BRANCH = "codex/final-convergence-" + CONVERGENCE_RUN_ID
  17. ASSIGNED_BASE_COMMIT = "d580b1f9586a0f6efcd9d176595a5b3c5da75329"
  18. OWNED_TEST_PATHS = [
  19. "tests/unit/test_project_config.py",
  20. "tests/unit/test_phase1_contract.py",
  21. "tests/unit/test_codex_harness.py",
  22. "tests/unit/test_native_multi_agent_contract.py",
  23. "tests/unit/test_project_generation.py",
  24. "config/prod2u_p4_verification_targets_v1.json",
  25. ]
  26. def _current_full_commit() -> str:
  27. return codex_harness._run_git(ROOT, ["rev-parse", "HEAD"]).stdout.decode("ascii").strip()
  28. def _current_short_commit() -> str:
  29. return codex_harness.current_commit8(ROOT)
  30. def _report_base(
  31. *,
  32. run_id: str = CONVERGENCE_RUN_ID,
  33. task_id: str = "audit",
  34. assigned_base_commit: str = ASSIGNED_BASE_COMMIT,
  35. ) -> dict:
  36. return {
  37. "schema": codex_harness.AGENT_TASK_REPORT_SCHEMA,
  38. "run_id": run_id,
  39. "task_id": task_id,
  40. "dependencies": [],
  41. "assigned_base_commit": assigned_base_commit,
  42. "result_commit": None,
  43. "integration_commit": None,
  44. "feature_branch": CONVERGENCE_BRANCH,
  45. "worktree": str(ROOT),
  46. "owned_paths": list(OWNED_TEST_PATHS),
  47. "native_thread": {
  48. "model_policy": "unconstrained",
  49. "reasoning_effort_policy": "unconstrained",
  50. "observed_model": None,
  51. "observed_reasoning_effort": None,
  52. "model_selection_source": "not_exposed",
  53. "effort_selection_source": "not_exposed",
  54. "observation_source": "not_exposed",
  55. "observed_permission_mode": "not_exposed",
  56. },
  57. "status": "completed",
  58. "read_only_report": "read-only evidence",
  59. }
  60. class CodexHarnessTests(unittest.TestCase):
  61. def test_run_id_is_lowercase_32_hex(self):
  62. value = codex_harness.new_run_id()
  63. self.assertRegex(value, r"^[0-9a-f]{32}$")
  64. def test_source_manifest_is_project_bound_and_excludes_legacy_protocol_sources(self):
  65. manifest = codex_harness.build_source_manifest(Path.cwd())
  66. paths = manifest["sources"]
  67. self.assertIn("src/top/prod2u_p4_normal_v3_top.v", paths)
  68. self.assertIn("src/common/frame_rx.v", paths)
  69. self.assertNotIn("src/rtl/binary921_crc16.v", paths)
  70. self.assertNotIn("src/rtl/binary921_frame_tx.v", paths)
  71. self.assertEqual(manifest["project_id"], "prod2u-door-temp")
  72. self.assertRegex(manifest["project_sha256"], r"^[0-9a-f]{64}$")
  73. def test_unverified_package_binds_commit_project_and_bitstream_hash(self):
  74. with tempfile.TemporaryDirectory() as directory:
  75. root = Path(directory)
  76. bitstream = root / "candidate.bit"
  77. bitstream.write_bytes(b"candidate-bitstream")
  78. package = codex_harness.create_unverified_package(
  79. bitstream=bitstream,
  80. project=PROJECT,
  81. commit=_current_short_commit(),
  82. run_id="a" * 32,
  83. output_root=root / "dist",
  84. )
  85. manifest = json.loads((package / "package_manifest.json").read_text(encoding="utf-8"))
  86. self.assertEqual(manifest["status"], "UNVERIFIED")
  87. self.assertEqual(manifest["commit"], _current_short_commit())
  88. self.assertEqual(manifest["commit_full"], _current_full_commit())
  89. self.assertEqual(manifest["run_id"], "a" * 32)
  90. self.assertEqual(
  91. manifest["bitstream_sha256"],
  92. hashlib.sha256(b"candidate-bitstream").hexdigest(),
  93. )
  94. self.assertTrue((package / "fw.bit").is_file())
  95. self.assertEqual(package.name, _current_short_commit() + "-" + manifest["bitstream_sha256"][:16])
  96. package_info = json.loads((package / "package-info.json").read_text(encoding="utf-8"))
  97. self.assertEqual(package_info["schema"], "prod2u-p4-normal-v3-folder-package-info-v3")
  98. self.assertEqual(package_info["bitstream"], "fw.bit")
  99. self.assertEqual(package_info["bitstream_sha256"], manifest["bitstream_sha256"])
  100. self.assertTrue((package / "protocol.md").is_file())
  101. self.assertTrue((package / "requirements.zh-CN.md").is_file())
  102. self.assertTrue((package / "source_manifest.json").is_file())
  103. self.assertTrue((package / "verification_targets.json").is_file())
  104. for relative in (
  105. "evidence/td-primary-receipt.json",
  106. "evidence/td-confirmation-receipt.json",
  107. "evidence/python-unit-receipt.json",
  108. "evidence/icarus-receipt.json",
  109. "evidence/verilator-receipt.json",
  110. "evidence/cocotb-receipt.json",
  111. "evidence/formal-receipt.json",
  112. "evidence/validation-summary.json",
  113. ):
  114. self.assertTrue((package / relative).is_file(), relative)
  115. def test_early_unverified_package_binds_full_production_and_input_receipt_hashes(self):
  116. with tempfile.TemporaryDirectory() as directory:
  117. root = Path(directory)
  118. bitstream = root / "candidate.bit"
  119. bitstream.write_bytes(b"early-candidate-bitstream")
  120. td_receipt = root / "td-primary.json"
  121. td_receipt.write_text(
  122. '{"schema":"td","status":"pass"}\n', encoding="utf-8"
  123. )
  124. source_manifest = codex_harness.build_source_manifest()
  125. source_manifest_bytes = (
  126. json.dumps(source_manifest, indent=2, sort_keys=True) + "\n"
  127. ).encode("utf-8")
  128. expected_source_manifest_sha256 = hashlib.sha256(source_manifest_bytes).hexdigest()
  129. expected_td_receipt_sha256 = hashlib.sha256(td_receipt.read_bytes()).hexdigest()
  130. production_commit = _current_full_commit()
  131. package = codex_harness.create_unverified_package(
  132. bitstream=bitstream,
  133. project=PROJECT,
  134. commit=_current_short_commit(),
  135. production_integration_commit=production_commit,
  136. source_manifest_sha256=expected_source_manifest_sha256,
  137. td_receipt_sha256=expected_td_receipt_sha256,
  138. package_class="UNVERIFIED_EARLY_BUILD",
  139. run_id="9" * 32,
  140. output_root=root / "dist",
  141. td_receipt=td_receipt,
  142. )
  143. manifest = json.loads((package / "package_manifest.json").read_text(encoding="utf-8"))
  144. package_info = json.loads((package / "package-info.json").read_text(encoding="utf-8"))
  145. bound_td = package / "evidence" / "td-primary-receipt.json"
  146. bound_td_value = json.loads(bound_td.read_text(encoding="utf-8"))
  147. self.assertEqual(manifest["status"], "UNVERIFIED")
  148. self.assertEqual(manifest["package_class"], "UNVERIFIED_EARLY_BUILD")
  149. self.assertEqual(manifest["commit"], _current_short_commit())
  150. self.assertEqual(manifest["commit_full"], _current_full_commit())
  151. self.assertEqual(manifest["production_integration_commit"], production_commit)
  152. self.assertEqual(manifest["source_manifest_sha256"], expected_source_manifest_sha256)
  153. self.assertEqual(manifest["bitstream_sha256"], hashlib.sha256(bitstream.read_bytes()).hexdigest())
  154. self.assertEqual(
  155. bound_td_value["source_receipt_sha256"], expected_td_receipt_sha256
  156. )
  157. self.assertEqual(
  158. manifest["td_receipt_sha256"], hashlib.sha256(bound_td.read_bytes()).hexdigest()
  159. )
  160. self.assertEqual(package_info["production_integration_commit"], production_commit)
  161. self.assertEqual(package_info["source_manifest_sha256"], expected_source_manifest_sha256)
  162. self.assertEqual(package_info["package_class"], "UNVERIFIED_EARLY_BUILD")
  163. def test_early_unverified_package_rejects_mismatched_binding_hashes(self):
  164. with tempfile.TemporaryDirectory() as directory:
  165. root = Path(directory)
  166. bitstream = root / "candidate.bit"
  167. bitstream.write_bytes(b"early-candidate-bitstream")
  168. td_receipt = root / "td-primary.json"
  169. td_receipt.write_text(
  170. '{"schema":"td","status":"pass"}\n', encoding="utf-8"
  171. )
  172. kwargs = {
  173. "bitstream": bitstream,
  174. "project": PROJECT,
  175. "commit": _current_short_commit(),
  176. "production_integration_commit": "b" * 40,
  177. "source_manifest_sha256": "c" * 64,
  178. "td_receipt_sha256": "d" * 64,
  179. "package_class": "UNVERIFIED_EARLY_BUILD",
  180. "run_id": "a" * 32,
  181. "output_root": root / "dist",
  182. "td_receipt": td_receipt,
  183. }
  184. with self.assertRaisesRegex(ValueError, "source manifest"):
  185. codex_harness.create_unverified_package(**kwargs)
  186. def test_early_package_selftest_accepts_and_detects_production_binding_tamper(self):
  187. with tempfile.TemporaryDirectory() as directory:
  188. root = Path(directory)
  189. bitstream = root / "candidate.bit"
  190. bitstream.write_bytes(b"early-selftest-bitstream")
  191. td_receipt = root / "td-primary.json"
  192. td_receipt.write_text(
  193. '{"schema":"td","status":"pass"}\n', encoding="utf-8"
  194. )
  195. source_manifest = codex_harness.build_source_manifest()
  196. expected_source_manifest_sha256 = hashlib.sha256(
  197. (json.dumps(source_manifest, indent=2, sort_keys=True) + "\n").encode(
  198. "utf-8"
  199. )
  200. ).hexdigest()
  201. expected_td_receipt_sha256 = hashlib.sha256(td_receipt.read_bytes()).hexdigest()
  202. run_id = "8" * 32
  203. production_commit = _current_full_commit()
  204. package = codex_harness.create_unverified_package(
  205. bitstream=bitstream,
  206. project=PROJECT,
  207. commit=_current_short_commit(),
  208. production_integration_commit=production_commit,
  209. source_manifest_sha256=expected_source_manifest_sha256,
  210. td_receipt_sha256=expected_td_receipt_sha256,
  211. package_class="UNVERIFIED_EARLY_BUILD",
  212. run_id=run_id,
  213. output_root=root / "dist",
  214. td_receipt=td_receipt,
  215. )
  216. valid = prod2u_p4_harness.package_selftest_payload(
  217. package, verification_run_id=run_id
  218. )
  219. self.assertEqual(valid["status"], "fail")
  220. self.assertTrue(valid["failures"])
  221. package_info_path = package / "package-info.json"
  222. package_info = json.loads(package_info_path.read_text(encoding="utf-8"))
  223. package_info["production_integration_commit"] = "f" * 40
  224. package_info_path.write_text(
  225. json.dumps(package_info, indent=2, sort_keys=True) + "\n",
  226. encoding="utf-8",
  227. newline="\n",
  228. )
  229. tampered = prod2u_p4_harness.package_selftest_payload(
  230. package, verification_run_id=run_id
  231. )
  232. self.assertEqual(tampered["status"], "fail")
  233. self.assertTrue(tampered["failures"])
  234. self.assertIn(
  235. "early_manifest_commit_mismatch",
  236. " ".join(tampered["failures"]),
  237. )
  238. def test_unverified_package_matches_prod2u_selftest_contract(self):
  239. with tempfile.TemporaryDirectory() as directory:
  240. root = Path(directory)
  241. bitstream = root / "candidate.bit"
  242. bitstream.write_bytes(b"candidate-bitstream")
  243. package = codex_harness.create_unverified_package(
  244. bitstream=bitstream,
  245. project=PROJECT,
  246. commit=_current_short_commit(),
  247. run_id="b" * 32,
  248. output_root=root / "dist",
  249. )
  250. receipt = prod2u_p4_harness.package_selftest_payload(
  251. package,
  252. verification_run_id="b" * 32,
  253. )
  254. self.assertEqual(receipt["status"], "fail")
  255. self.assertTrue(receipt["failures"])
  256. def test_supplied_receipt_is_copied_with_package_bindings(self):
  257. with tempfile.TemporaryDirectory() as directory:
  258. root = Path(directory)
  259. bitstream = root / "candidate.bit"
  260. bitstream.write_bytes(b"candidate-bitstream")
  261. source_receipt = root / "icarus.json"
  262. source_receipt.write_text('{"schema":"hdl","status":"pass"}\n', encoding="utf-8")
  263. package = codex_harness.create_unverified_package(
  264. bitstream=bitstream,
  265. project=PROJECT,
  266. commit=_current_short_commit(),
  267. run_id="c" * 32,
  268. output_root=root / "dist",
  269. verification_receipts={"icarus": source_receipt},
  270. )
  271. bound = json.loads((package / "evidence/icarus-receipt.json").read_text(encoding="utf-8"))
  272. self.assertEqual(bound["status"], "pass")
  273. self.assertEqual(bound["verification_run_id"], "c" * 32)
  274. self.assertEqual(bound["commit"], _current_full_commit())
  275. self.assertEqual(bound["commit_full"], _current_full_commit())
  276. self.assertRegex(bound["project_config_sha256"], r"^[0-9a-f]{64}$")
  277. self.assertRegex(bound["source_receipt_sha256"], r"^[0-9a-f]{64}$")
  278. def test_build_source_list_and_build_info_use_only_the_new_contract(self):
  279. sources = prod2u_p4_normal_v3_build.PRODUCTION_RTL_SOURCES
  280. self.assertIn("src/common/frame_rx.v", sources)
  281. self.assertIn("src/modules/shared_500us_tick.v", sources)
  282. self.assertIn("src/modules/host_watchdog.v", sources)
  283. self.assertIn("src/top/prod2u_p4_normal_v3_top.v", sources)
  284. self.assertNotIn("src/rtl/binary921_crc16.v", sources)
  285. self.assertNotIn("src/rtl/prod2u_p4_normal_v3_watchdog.v", sources)
  286. with tempfile.TemporaryDirectory() as directory:
  287. bitstream = Path(directory) / "candidate.bit"
  288. bitstream.write_bytes(b"candidate")
  289. info = prod2u_p4_normal_v3_build.create_build_info(
  290. bitstream=bitstream,
  291. commit=_current_short_commit(),
  292. )
  293. self.assertEqual(info["serial"], {"baud": 115200, "format": "8N1", "flow_control": "none"})
  294. self.assertEqual(
  295. info["hardware_access"],
  296. {"com": False, "jtag": False, "programming": False, "drivers": False},
  297. )
  298. def test_source_closure_is_bidirectional_across_manifest_build_and_td_consumers(self):
  299. generated = json.loads(
  300. (ROOT / "src" / "generated" / "td-source-manifest.json").read_text(encoding="utf-8")
  301. )
  302. canonical = generated["sources"]
  303. self.assertEqual(canonical, list(prod2u_p4_normal_v3_build.PRODUCTION_RTL_SOURCES))
  304. self.assertEqual(canonical, codex_harness.build_source_manifest(ROOT)["sources"])
  305. project = ET.parse(ROOT / "td" / "prod2u_p4_normal_v3.prj")
  306. td_project_sources = [
  307. Path(node.attrib["Path"]).as_posix().removeprefix("../")
  308. for node in project.findall(".//Verilog/File")
  309. ]
  310. self.assertEqual(td_project_sources, canonical)
  311. syn = (ROOT / "td" / "syn" / "prod2u_p4_normal_v3.tcl").read_text(encoding="ascii")
  312. tcl_sources = [
  313. Path(match).as_posix()
  314. for match in re.findall(r"analyze\s+-file\s+\{([^}]+)\}", syn)
  315. ]
  316. self.assertEqual(tcl_sources, canonical)
  317. self.assertEqual(len(canonical), len(set(canonical)))
  318. self.assertTrue(all((ROOT / source).is_file() for source in canonical))
  319. def test_runtime_profile_is_the_new_115200_contract(self):
  320. self.assertEqual(
  321. prod2u_p4_harness.RUNTIME_PROFILE,
  322. "prod2u-door-temp-115200-v1",
  323. )
  324. def test_qor_attribute_count_accepts_td_gate_qor_name(self):
  325. with tempfile.TemporaryDirectory() as directory:
  326. root = Path(directory)
  327. (root / "gate.qor").write_text(
  328. "| #async_reg | 6 |\n",
  329. encoding="ascii",
  330. )
  331. observed = prod2u_p4_harness.parse_qor_attribute_count(
  332. root / "prod2u_p4_normal_v3_gate.qor",
  333. "async_reg",
  334. )
  335. self.assertEqual(observed, 6)
  336. def test_verification_inventory_uses_only_the_current_manifest(self):
  337. manifest = prod2u_p4_harness.load_target_manifest()
  338. self.assertEqual(
  339. manifest["schema"],
  340. "prod2u-simple-verification-target-manifest-v1",
  341. )
  342. self.assertEqual(
  343. [target["name"] for target in prod2u_p4_harness.cocotb_tests()],
  344. ["prod2u_door_temp_uart_e2e"],
  345. )
  346. self.assertEqual(
  347. [target["name"] for target in prod2u_p4_harness.formal_targets()],
  348. [
  349. "frame_command_contract",
  350. "frame_tx_contract",
  351. "output_target_ram_contract",
  352. "simple_frame_contract",
  353. "simple_motor_temperature_contract",
  354. "pwm_scheduler_contract",
  355. "host_watchdog_contract",
  356. ],
  357. )
  358. icarus_names = [target["name"] for target in prod2u_p4_harness.hdl_testbenches()]
  359. self.assertEqual(
  360. icarus_names,
  361. sorted(manifest["layers"]["icarus"]),
  362. )
  363. def test_agent_task_report_accepts_unconstrained_observations_and_full_commits(self):
  364. # A capability probe is a read-only report for the exact dispatch HEAD.
  365. # It must not reinterpret later production/formal commits as this task's
  366. # owned paths when the shared convergence branch has advanced.
  367. capability_head = _current_full_commit()
  368. report = _report_base(
  369. task_id="capability_probe", assigned_base_commit=capability_head
  370. )
  371. report["result_commit"] = capability_head
  372. report["read_only_report"] = None
  373. report["owned_paths"] = ["tests/", "config/prod2u_p4_verification_targets_v1.json"]
  374. validated = codex_harness.validate_agent_task_report(
  375. report,
  376. expected_run_id=CONVERGENCE_RUN_ID,
  377. expected_base_commit=capability_head,
  378. root=ROOT,
  379. )
  380. self.assertEqual(validated["assigned_base_commit"], capability_head)
  381. self.assertEqual(validated["feature_branch"], CONVERGENCE_BRANCH)
  382. self.assertEqual(validated["worktree"], str(ROOT))
  383. def test_agent_task_report_accepts_read_only_report_with_unexposed_observations(self):
  384. report = _report_base(task_id="repo_process_audit")
  385. report["native_thread"]["observed_model"] = None
  386. report["native_thread"]["observed_reasoning_effort"] = None
  387. validated = codex_harness.validate_agent_task_report(
  388. report,
  389. expected_run_id=CONVERGENCE_RUN_ID,
  390. expected_base_commit=ASSIGNED_BASE_COMMIT,
  391. )
  392. self.assertEqual(validated["read_only_report"], "read-only evidence")
  393. def test_agent_task_report_rejects_stale_assigned_base(self):
  394. report = _report_base(task_id="stale")
  395. report["assigned_base_commit"] = "0" * 40
  396. with self.assertRaisesRegex(ValueError, "stale"):
  397. codex_harness.validate_agent_task_report(
  398. report,
  399. expected_run_id=CONVERGENCE_RUN_ID,
  400. expected_base_commit=ASSIGNED_BASE_COMMIT,
  401. )
  402. def test_agent_task_report_rejects_dependency_mismatch_but_preserves_integration_conflict(self):
  403. report = _report_base(task_id="dependent")
  404. report["dependencies"] = [
  405. {"task_id": "producer", "result_commit": "2" * 40, "integration_commit": None}
  406. ]
  407. report["status"] = "integration_conflict"
  408. report["read_only_report"] = "conflicting paths"
  409. with self.assertRaisesRegex(ValueError, "dependency"):
  410. codex_harness.validate_agent_task_report(
  411. report,
  412. expected_run_id=CONVERGENCE_RUN_ID,
  413. expected_base_commit=ASSIGNED_BASE_COMMIT,
  414. expected_dependencies={
  415. "producer": {"result_commit": "3" * 40, "integration_commit": None}
  416. },
  417. )
  418. report["dependencies"][0]["result_commit"] = "3" * 40
  419. validated = codex_harness.validate_agent_task_report(
  420. report,
  421. expected_run_id=CONVERGENCE_RUN_ID,
  422. expected_base_commit=ASSIGNED_BASE_COMMIT,
  423. expected_dependencies={
  424. "producer": {"result_commit": "3" * 40, "integration_commit": None}
  425. },
  426. )
  427. self.assertEqual(validated["status"], "integration_conflict")
  428. def test_agent_task_report_rejects_duplicate_dependencies(self):
  429. report = _report_base(task_id="duplicate-dependency")
  430. report["dependencies"] = [
  431. {"task_id": "producer", "result_commit": None, "integration_commit": None},
  432. {"task_id": "producer", "result_commit": None, "integration_commit": None},
  433. ]
  434. with self.assertRaisesRegex(ValueError, "duplicate dependency"):
  435. codex_harness.validate_agent_task_report(
  436. report,
  437. expected_run_id=CONVERGENCE_RUN_ID,
  438. expected_base_commit=ASSIGNED_BASE_COMMIT,
  439. )
  440. def test_worktree_identity_rejects_protected_root_wrong_branch_and_wrong_head(self):
  441. with self.assertRaisesRegex(ValueError, "protected_worktree_violation"):
  442. codex_harness.validate_worktree_identity(ROOT, protected_root=ROOT)
  443. with self.assertRaisesRegex(ValueError, "branch"):
  444. codex_harness.validate_worktree_identity(
  445. ROOT, expected_branch=CONVERGENCE_BRANCH + "-wrong"
  446. )
  447. with self.assertRaisesRegex(ValueError, "HEAD"):
  448. codex_harness.validate_worktree_identity(ROOT, expected_head="0" * 40)
  449. def test_agent_task_report_rejects_non_worktree_report_cwd(self):
  450. report = _report_base(task_id="wrong-cwd")
  451. report["worktree"] = str(ROOT / "tools")
  452. with self.assertRaisesRegex(ValueError, "worktree root mismatch"):
  453. codex_harness.validate_agent_task_report(
  454. report,
  455. expected_run_id=CONVERGENCE_RUN_ID,
  456. expected_base_commit=ASSIGNED_BASE_COMMIT,
  457. )
  458. def test_package_rejects_noncanonical_project_input(self):
  459. with tempfile.TemporaryDirectory() as directory:
  460. root = Path(directory)
  461. bitstream = root / "candidate.bit"
  462. bitstream.write_bytes(b"candidate-bitstream")
  463. fake_project = root / "project.json"
  464. fake_project.write_text('{"project_id":"prod2u-door-temp"}\n', encoding="utf-8")
  465. with self.assertRaisesRegex(ValueError, "canonical project"):
  466. codex_harness.create_unverified_package(
  467. bitstream=bitstream,
  468. project=fake_project,
  469. commit=_current_short_commit(),
  470. run_id=CONVERGENCE_RUN_ID,
  471. output_root=root / "dist",
  472. )
  473. def test_name_status_z_parses_rename_and_copy_paths(self):
  474. events = codex_harness.parse_name_status_z(
  475. b"R100\0old.txt\0new.txt\0C100\0source.txt\0copy.txt\0M\0owned.txt\0"
  476. )
  477. self.assertEqual(
  478. events,
  479. [
  480. ("R100", ("old.txt", "new.txt")),
  481. ("C100", ("source.txt", "copy.txt")),
  482. ("M", ("owned.txt",)),
  483. ],
  484. )
  485. def test_owned_paths_require_exact_files_or_explicit_directory_prefixes(self):
  486. events = [("R100", ("tests/unit/old.py", "tests/unit/new.py"))]
  487. self.assertEqual(
  488. codex_harness.validate_changed_paths(events, ["tests/unit/"]),
  489. ["tests/unit/old.py", "tests/unit/new.py"],
  490. )
  491. with self.assertRaisesRegex(ValueError, "owned"):
  492. codex_harness.validate_changed_paths(events, ["tests/unit/old.py"])
  493. with self.assertRaisesRegex(ValueError, "path"):
  494. codex_harness.validate_changed_paths([("M", ("../outside.py",))], ["tests/"])
  495. with self.assertRaisesRegex(ValueError, "glob"):
  496. codex_harness.validate_changed_paths(events, ["tests/*.py"])
  497. def test_agent_receipt_aggregation_preserves_hashes_and_bindings(self):
  498. aggregate = codex_harness.aggregate_agent_receipt_bindings(
  499. {
  500. "unit": {
  501. "verification_run_id": "a" * 32,
  502. "commit": "b" * 40,
  503. "artifact_sha256": "c" * 64,
  504. }
  505. },
  506. expected_run_id="a" * 32,
  507. expected_commit="b" * 40,
  508. )
  509. self.assertEqual(aggregate["receipts"]["unit"]["artifact_sha256"], "c" * 64)
  510. def test_current_commit8_uses_the_git_wrapper(self):
  511. completed = subprocess.CompletedProcess(
  512. args=["git"], returncode=0, stdout=b"0123abcd\n", stderr=b""
  513. )
  514. with patch.object(codex_harness.subprocess, "run", return_value=completed) as run:
  515. self.assertEqual(codex_harness.current_commit8(Path.cwd()), "0123abcd")
  516. args, kwargs = run.call_args
  517. self.assertEqual(args[0][0], "git")
  518. self.assertFalse(kwargs["shell"])
  519. self.assertFalse(kwargs["text"])
  520. self.assertIn("timeout", kwargs)
  521. if __name__ == "__main__":
  522. unittest.main()