test_evidence_canon.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #!/usr/bin/env python3
  2. """Focused tests for Lane P4 evidence canonicalization."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import json
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import unittest
  11. from pathlib import Path
  12. ROOT = Path(__file__).resolve().parents[2]
  13. TOOLS = ROOT / "tools"
  14. if str(TOOLS) not in sys.path:
  15. sys.path.insert(0, str(TOOLS))
  16. import package_evidence_canon as evidence_canon # noqa: E402
  17. def load_analyzer():
  18. path = ROOT / "package_for_agent_analysis.py"
  19. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path)
  20. assert spec is not None and spec.loader is not None
  21. module = importlib.util.module_from_spec(spec)
  22. sys.modules[spec.name] = module
  23. spec.loader.exec_module(module)
  24. return module
  25. def write_file(root: Path, relative: str, payload: bytes) -> Path:
  26. path = root / Path(*relative.split("/"))
  27. path.parent.mkdir(parents=True, exist_ok=True)
  28. path.write_bytes(payload)
  29. return path
  30. def init_git_repo(repo: Path) -> None:
  31. """review-compact fail-closed requires live Git provenance."""
  32. git = shutil.which("git")
  33. if not git:
  34. raise unittest.SkipTest("Git is required")
  35. repo.mkdir(parents=True, exist_ok=True)
  36. subprocess.run([git, "init", "-q", str(repo)], check=True)
  37. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  38. subprocess.run(
  39. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  40. check=True,
  41. )
  42. subprocess.run([git, "-C", str(repo), "add", "-A"], check=True)
  43. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  44. class EvidenceCanonUnitTests(unittest.TestCase):
  45. def test_allowlist_loads_and_lists_compact_keys(self) -> None:
  46. allowlist = evidence_canon.load_allowlist()
  47. keys = evidence_canon.compact_default_key_list(allowlist)
  48. for required in (
  49. "final_matrix",
  50. "formal_receipt",
  51. "td_receipt",
  52. "tip_binding",
  53. "source_closure",
  54. "bitstream",
  55. "firmware_selftest",
  56. "package_selftest_pointer",
  57. "deep_review_summary",
  58. "io_evidence",
  59. "hardware_bringup",
  60. ):
  61. self.assertIn(required, keys)
  62. def test_workspace_canonical_placement(self) -> None:
  63. self.assertEqual(
  64. evidence_canon.workspace_canonical_path("docs/IO_EVIDENCE_MATRIX.zh-CN.md"),
  65. "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md",
  66. )
  67. self.assertEqual(
  68. evidence_canon.workspace_canonical_path("config/source_closure.json"),
  69. "evidence/td/source-closure.json",
  70. )
  71. self.assertEqual(
  72. evidence_canon.workspace_canonical_path(
  73. "receipts/verification-matrix-final.json"
  74. ),
  75. "evidence/matrix/verification-matrix-final.json",
  76. )
  77. def test_process_evidence_detection(self) -> None:
  78. self.assertTrue(evidence_canon.is_process_evidence("lane-status/lane-a-docs.json"))
  79. self.assertTrue(
  80. evidence_canon.is_process_evidence(
  81. "receipts/verification-matrix-rerun3.json"
  82. )
  83. )
  84. self.assertTrue(
  85. evidence_canon.is_process_evidence("deep-reviews/round-1-product-protocol.json")
  86. )
  87. self.assertFalse(
  88. evidence_canon.is_process_evidence("deep-reviews/summary.json")
  89. )
  90. self.assertFalse(
  91. evidence_canon.is_process_evidence(
  92. "evidence/matrix/verification-matrix-final.json"
  93. )
  94. )
  95. def test_log_policy_pass_summary_fail_full(self) -> None:
  96. self.assertEqual(evidence_canon.log_retention_for_status("pass"), "summary")
  97. self.assertEqual(evidence_canon.log_retention_for_status("not_run"), "summary")
  98. self.assertEqual(evidence_canon.log_retention_for_status("FAIL"), "full")
  99. self.assertEqual(evidence_canon.log_retention_for_status("blocked"), "full")
  100. self.assertEqual(evidence_canon.log_retention_for_status("timeout"), "full")
  101. summary = evidence_canon.build_pass_log_summary(
  102. source_path="formal.log",
  103. status="pass",
  104. metadata={
  105. "command": ["sby", "run"],
  106. "exit_code": 0,
  107. "duration_seconds": 12.5,
  108. "warning_summary": [],
  109. },
  110. )
  111. self.assertEqual(summary["retention"], "summary")
  112. self.assertEqual(summary["exit_code"], 0)
  113. self.assertIn("full stdout/stderr is omitted", summary["note"])
  114. def test_stage_evidence_root_dedup_and_aliases(self) -> None:
  115. with tempfile.TemporaryDirectory() as tmp:
  116. root = Path(tmp)
  117. evid = root / "delivery"
  118. # Duplicate final matrix under two discovery paths (same bytes).
  119. payload = b'{"status":"pass","lanes":{"python":{"status":"pass"}}}\n'
  120. write_file(evid, "evidence/matrix-receipt.json", payload)
  121. write_file(evid, "receipts/verification-matrix-final.json", payload)
  122. write_file(
  123. evid,
  124. "evidence/td-primary-receipt.json",
  125. b'{"status":"pass","tool":"td2026"}\n',
  126. )
  127. write_file(
  128. evid,
  129. "lane-status/lane-a-docs.json",
  130. b'{"status":"pass","lane":"A"}\n',
  131. )
  132. write_file(
  133. evid,
  134. "receipts/verification-matrix-rerun3.json",
  135. b'{"status":"fail"}\n',
  136. )
  137. # PASS log should collapse to summary only.
  138. write_file(evid, "evidence/td-primary.log", b"INFO built ok\n" * 50)
  139. result = evidence_canon.stage_evidence_root(
  140. evid,
  141. staging_root=root / "stage",
  142. include_process_evidence=False,
  143. )
  144. rels = {item.relative for item in result.staged}
  145. self.assertIn("evidence/matrix/verification-matrix-final.json", rels)
  146. self.assertIn("evidence/td/td-primary-receipt.json", rels)
  147. self.assertNotIn("evidence/process/lane-status/lane-a-docs.json", rels)
  148. self.assertTrue(any(row.get("key") == "final_matrix" for row in result.aliases))
  149. rules = {row["rule"] for row in result.excluded}
  150. self.assertIn(evidence_canon.PROCESS_EXCLUDE_RULE, rules)
  151. debug = evidence_canon.stage_evidence_root(
  152. evid,
  153. staging_root=root / "stage-debug",
  154. include_process_evidence=True,
  155. )
  156. debug_rels = {item.relative for item in debug.staged}
  157. self.assertTrue(
  158. any(path.startswith("evidence/process/") for path in debug_rels)
  159. )
  160. def test_prefer_canonical_path(self) -> None:
  161. chosen = evidence_canon.prefer_canonical_path(
  162. [
  163. "evidence/from/matrix-receipt.json",
  164. "evidence/matrix/verification-matrix-final.json",
  165. "source/receipts/verification-matrix-final.json",
  166. ]
  167. )
  168. self.assertEqual(chosen, "evidence/matrix/verification-matrix-final.json")
  169. class EvidenceCanonPackagerIntegrationTests(unittest.TestCase):
  170. def test_review_compact_filters_process_and_places_io_evidence(self) -> None:
  171. analyzer = load_analyzer()
  172. with tempfile.TemporaryDirectory() as tmp:
  173. temp = Path(tmp)
  174. repo = temp / "repo"
  175. write_file(repo, "src/core.v", b"module core; endmodule\n")
  176. write_file(
  177. repo,
  178. "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  179. b"# IO evidence\n",
  180. )
  181. write_file(
  182. repo,
  183. "config/source_closure.json",
  184. b'{"schema":"fixture","files":[]}\n',
  185. )
  186. write_file(
  187. repo,
  188. "receipts/verification-matrix-final.json",
  189. b'{"status":"pass"}\n',
  190. )
  191. write_file(
  192. repo,
  193. "receipts/verification-matrix-rerun3.json",
  194. b'{"status":"fail"}\n',
  195. )
  196. write_file(
  197. repo,
  198. "receipts/deep-reviews/summary.json",
  199. b'{"status":"closed","rounds":5}\n',
  200. )
  201. write_file(
  202. repo,
  203. "receipts/deep-reviews/round-1-product-protocol.json",
  204. b'{"round":1}\n',
  205. )
  206. init_git_repo(repo)
  207. config = analyzer.HandoffConfig(
  208. max_zip_bytes=5_000_000,
  209. target_zip_bytes=4_000_000,
  210. external_sources=(),
  211. extra_exclusions=(),
  212. )
  213. collection = analyzer.collect_analysis_inputs(
  214. repo_root=repo,
  215. config=config,
  216. temp_root=temp / "run",
  217. include_git_bundle=False,
  218. profile="review-compact",
  219. package_name="evidence-canon-smoke",
  220. )
  221. paths = {item.candidate.relative for item in collection.items}
  222. self.assertIn("evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md", paths)
  223. # Canonical tracked path must remain for active markdown links.
  224. self.assertIn("source/docs/IO_EVIDENCE_MATRIX.zh-CN.md", paths)
  225. self.assertIn("evidence/td/source-closure.json", paths)
  226. self.assertIn("source/config/source_closure.json", paths)
  227. self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
  228. self.assertIn("evidence/deep-reviews/summary.json", paths)
  229. self.assertNotIn("evidence/receipts/verification-matrix-rerun3.json", paths)
  230. self.assertNotIn(
  231. "evidence/selftest/compact-package-selftest.json",
  232. paths,
  233. )
  234. self.assertIn(
  235. "evidence/selftest/compact-package-selftest-pointer.json",
  236. paths,
  237. )
  238. self.assertFalse(any("round-1-product-protocol" in path for path in paths))
  239. self.assertIsNotNone(collection.evidence_canon)
  240. assert collection.evidence_canon is not None
  241. self.assertEqual(collection.evidence_canon["schema"], "cpld-evidence-canon-v1")
  242. self.assertFalse(collection.evidence_canon["include_process_evidence"])
  243. self.assertIn("final_matrix", collection.evidence_canon["compact_default_keys"])
  244. excluded_rules = {row["rule"] for row in collection.excluded}
  245. self.assertTrue(
  246. evidence_canon.PROCESS_EXCLUDE_RULE in excluded_rules
  247. or evidence_canon.NON_ALLOWLIST_RECEIPT_RULE in excluded_rules
  248. )
  249. def test_evidence_root_staging_into_package_index(self) -> None:
  250. analyzer = load_analyzer()
  251. with tempfile.TemporaryDirectory() as tmp:
  252. temp = Path(tmp)
  253. repo = temp / "repo"
  254. write_file(repo, "src/core.v", b"module core; endmodule\n")
  255. # Workspace IO path remaps to the same canonical evidence/io path as
  256. # an evidence-root copy; packager must physically dedupe.
  257. write_file(
  258. repo,
  259. "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  260. b"# IO evidence workspace\n",
  261. )
  262. evid = temp / "evid"
  263. write_file(
  264. evid,
  265. "IO_EVIDENCE_MATRIX.zh-CN.md",
  266. b"# IO evidence staged\n",
  267. )
  268. write_file(
  269. evid,
  270. "evidence/formal-receipt.json",
  271. b'{"status":"pass","tool":"sby"}\n',
  272. )
  273. write_file(
  274. evid,
  275. "HARDWARE_BRINGUP_NOTES.zh-CN.md",
  276. b"# bring-up\n",
  277. )
  278. write_file(
  279. evid,
  280. "bitstream/prod2u_p4_normal_v3.bit",
  281. b"BITSTREAM",
  282. )
  283. write_file(
  284. evid,
  285. "lane-status/lane-f-td.json",
  286. b'{"status":"pass"}\n',
  287. )
  288. init_git_repo(repo)
  289. config = analyzer.HandoffConfig(
  290. max_zip_bytes=5_000_000,
  291. target_zip_bytes=4_000_000,
  292. external_sources=(),
  293. extra_exclusions=(),
  294. )
  295. collection = analyzer.collect_analysis_inputs(
  296. repo_root=repo,
  297. config=config,
  298. temp_root=temp / "run",
  299. include_git_bundle=False,
  300. profile="review-compact",
  301. package_name="evidence-root-smoke",
  302. evidence_root=evid,
  303. )
  304. paths = [item.candidate.relative for item in collection.items]
  305. self.assertEqual(
  306. paths.count("evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md"),
  307. 1,
  308. "workspace+evidence-root IO must physically dedupe",
  309. )
  310. io_item = next(
  311. item
  312. for item in collection.items
  313. if item.candidate.relative == "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md"
  314. )
  315. self.assertEqual(io_item.source_id, "evidence-root")
  316. self.assertIn("evidence/formal/formal-receipt.json", paths)
  317. self.assertIn("evidence/hardware/HARDWARE_BRINGUP_NOTES.zh-CN.md", paths)
  318. self.assertIn("evidence/bitstream/prod2u_p4_normal_v3.bit", paths)
  319. self.assertFalse(any("lane-f-td" in path for path in paths))
  320. self.assertTrue(
  321. any(
  322. row.get("rule") == "canonical_path_physical_dedup"
  323. for row in collection.excluded
  324. )
  325. )
  326. result = analyzer.create_analysis_package(
  327. collection=collection,
  328. output_root=temp / "output",
  329. package_name="evidence-root-smoke",
  330. max_zip_bytes=5_000_000,
  331. target_zip_bytes=4_000_000,
  332. force=False,
  333. profile="review-compact",
  334. )
  335. index = json.loads(
  336. (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(
  337. encoding="utf-8"
  338. )
  339. )
  340. self.assertIn("evidence_canon", index)
  341. self.assertIn("evidence_aliases", index)
  342. self.assertEqual(index["evidence_canon"]["schema"], "cpld-evidence-canon-v1")
  343. self.assertIn("formal_receipt", index["evidence_canon"]["compact_default_keys"])
  344. schema = json.loads(
  345. (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
  346. encoding="utf-8"
  347. )
  348. )
  349. import jsonschema
  350. jsonschema.validate(index, schema)
  351. if __name__ == "__main__":
  352. unittest.main()