| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- #!/usr/bin/env python3
- """Focused tests for Lane P4 evidence canonicalization."""
- from __future__ import annotations
- import importlib.util
- import json
- import shutil
- import subprocess
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[2]
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- import package_evidence_canon as evidence_canon # noqa: E402
- def load_analyzer():
- path = ROOT / "package_for_agent_analysis.py"
- spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path)
- assert spec is not None and spec.loader is not None
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
- def write_file(root: Path, relative: str, payload: bytes) -> Path:
- path = root / Path(*relative.split("/"))
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(payload)
- return path
- def init_git_repo(repo: Path) -> None:
- """review-compact fail-closed requires live Git provenance."""
- git = shutil.which("git")
- if not git:
- raise unittest.SkipTest("Git is required")
- repo.mkdir(parents=True, exist_ok=True)
- subprocess.run([git, "init", "-q", str(repo)], check=True)
- subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
- subprocess.run(
- [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
- check=True,
- )
- subprocess.run([git, "-C", str(repo), "add", "-A"], check=True)
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- class EvidenceCanonUnitTests(unittest.TestCase):
- def test_allowlist_loads_and_lists_compact_keys(self) -> None:
- allowlist = evidence_canon.load_allowlist()
- keys = evidence_canon.compact_default_key_list(allowlist)
- for required in (
- "final_matrix",
- "formal_receipt",
- "td_receipt",
- "tip_binding",
- "source_closure",
- "bitstream",
- "firmware_selftest",
- "package_selftest_pointer",
- "deep_review_summary",
- "io_evidence",
- "hardware_bringup",
- ):
- self.assertIn(required, keys)
- def test_workspace_canonical_placement(self) -> None:
- self.assertEqual(
- evidence_canon.workspace_canonical_path("docs/IO_EVIDENCE_MATRIX.zh-CN.md"),
- "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md",
- )
- self.assertEqual(
- evidence_canon.workspace_canonical_path("config/source_closure.json"),
- "evidence/td/source-closure.json",
- )
- self.assertEqual(
- evidence_canon.workspace_canonical_path(
- "receipts/verification-matrix-final.json"
- ),
- "evidence/matrix/verification-matrix-final.json",
- )
- def test_process_evidence_detection(self) -> None:
- self.assertTrue(evidence_canon.is_process_evidence("lane-status/lane-a-docs.json"))
- self.assertTrue(
- evidence_canon.is_process_evidence(
- "receipts/verification-matrix-rerun3.json"
- )
- )
- self.assertTrue(
- evidence_canon.is_process_evidence("deep-reviews/round-1-product-protocol.json")
- )
- self.assertFalse(
- evidence_canon.is_process_evidence("deep-reviews/summary.json")
- )
- self.assertFalse(
- evidence_canon.is_process_evidence(
- "evidence/matrix/verification-matrix-final.json"
- )
- )
- def test_log_policy_pass_summary_fail_full(self) -> None:
- self.assertEqual(evidence_canon.log_retention_for_status("pass"), "summary")
- self.assertEqual(evidence_canon.log_retention_for_status("not_run"), "summary")
- self.assertEqual(evidence_canon.log_retention_for_status("FAIL"), "full")
- self.assertEqual(evidence_canon.log_retention_for_status("blocked"), "full")
- self.assertEqual(evidence_canon.log_retention_for_status("timeout"), "full")
- summary = evidence_canon.build_pass_log_summary(
- source_path="formal.log",
- status="pass",
- metadata={
- "command": ["sby", "run"],
- "exit_code": 0,
- "duration_seconds": 12.5,
- "warning_summary": [],
- },
- )
- self.assertEqual(summary["retention"], "summary")
- self.assertEqual(summary["exit_code"], 0)
- self.assertIn("full stdout/stderr is omitted", summary["note"])
- def test_stage_evidence_root_dedup_and_aliases(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- evid = root / "delivery"
- # Duplicate final matrix under two discovery paths (same bytes).
- payload = b'{"status":"pass","lanes":{"python":{"status":"pass"}}}\n'
- write_file(evid, "evidence/matrix-receipt.json", payload)
- write_file(evid, "receipts/verification-matrix-final.json", payload)
- write_file(
- evid,
- "evidence/td-primary-receipt.json",
- b'{"status":"pass","tool":"td2026"}\n',
- )
- write_file(
- evid,
- "lane-status/lane-a-docs.json",
- b'{"status":"pass","lane":"A"}\n',
- )
- write_file(
- evid,
- "receipts/verification-matrix-rerun3.json",
- b'{"status":"fail"}\n',
- )
- # PASS log should collapse to summary only.
- write_file(evid, "evidence/td-primary.log", b"INFO built ok\n" * 50)
- result = evidence_canon.stage_evidence_root(
- evid,
- staging_root=root / "stage",
- include_process_evidence=False,
- )
- rels = {item.relative for item in result.staged}
- self.assertIn("evidence/matrix/verification-matrix-final.json", rels)
- self.assertIn("evidence/td/td-primary-receipt.json", rels)
- self.assertNotIn("evidence/process/lane-status/lane-a-docs.json", rels)
- self.assertTrue(any(row.get("key") == "final_matrix" for row in result.aliases))
- rules = {row["rule"] for row in result.excluded}
- self.assertIn(evidence_canon.PROCESS_EXCLUDE_RULE, rules)
- debug = evidence_canon.stage_evidence_root(
- evid,
- staging_root=root / "stage-debug",
- include_process_evidence=True,
- )
- debug_rels = {item.relative for item in debug.staged}
- self.assertTrue(
- any(path.startswith("evidence/process/") for path in debug_rels)
- )
- def test_prefer_canonical_path(self) -> None:
- chosen = evidence_canon.prefer_canonical_path(
- [
- "evidence/from/matrix-receipt.json",
- "evidence/matrix/verification-matrix-final.json",
- "source/receipts/verification-matrix-final.json",
- ]
- )
- self.assertEqual(chosen, "evidence/matrix/verification-matrix-final.json")
- class EvidenceCanonPackagerIntegrationTests(unittest.TestCase):
- def test_review_compact_filters_process_and_places_io_evidence(self) -> None:
- analyzer = load_analyzer()
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- write_file(repo, "src/core.v", b"module core; endmodule\n")
- write_file(
- repo,
- "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
- b"# IO evidence\n",
- )
- write_file(
- repo,
- "config/source_closure.json",
- b'{"schema":"fixture","files":[]}\n',
- )
- write_file(
- repo,
- "receipts/verification-matrix-final.json",
- b'{"status":"pass"}\n',
- )
- write_file(
- repo,
- "receipts/verification-matrix-rerun3.json",
- b'{"status":"fail"}\n',
- )
- write_file(
- repo,
- "receipts/deep-reviews/summary.json",
- b'{"status":"closed","rounds":5}\n',
- )
- write_file(
- repo,
- "receipts/deep-reviews/round-1-product-protocol.json",
- b'{"round":1}\n',
- )
- init_git_repo(repo)
- config = analyzer.HandoffConfig(
- max_zip_bytes=5_000_000,
- target_zip_bytes=4_000_000,
- external_sources=(),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- include_git_bundle=False,
- profile="review-compact",
- package_name="evidence-canon-smoke",
- )
- paths = {item.candidate.relative for item in collection.items}
- self.assertIn("evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md", paths)
- # Canonical tracked path must remain for active markdown links.
- self.assertIn("source/docs/IO_EVIDENCE_MATRIX.zh-CN.md", paths)
- self.assertIn("evidence/td/source-closure.json", paths)
- self.assertIn("source/config/source_closure.json", paths)
- self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
- self.assertIn("evidence/deep-reviews/summary.json", paths)
- self.assertNotIn("evidence/receipts/verification-matrix-rerun3.json", paths)
- self.assertNotIn(
- "evidence/selftest/compact-package-selftest.json",
- paths,
- )
- self.assertIn(
- "evidence/selftest/compact-package-selftest-pointer.json",
- paths,
- )
- self.assertFalse(any("round-1-product-protocol" in path for path in paths))
- self.assertIsNotNone(collection.evidence_canon)
- assert collection.evidence_canon is not None
- self.assertEqual(collection.evidence_canon["schema"], "cpld-evidence-canon-v1")
- self.assertFalse(collection.evidence_canon["include_process_evidence"])
- self.assertIn("final_matrix", collection.evidence_canon["compact_default_keys"])
- excluded_rules = {row["rule"] for row in collection.excluded}
- self.assertTrue(
- evidence_canon.PROCESS_EXCLUDE_RULE in excluded_rules
- or evidence_canon.NON_ALLOWLIST_RECEIPT_RULE in excluded_rules
- )
- def test_evidence_root_staging_into_package_index(self) -> None:
- analyzer = load_analyzer()
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- write_file(repo, "src/core.v", b"module core; endmodule\n")
- # Workspace IO path remaps to the same canonical evidence/io path as
- # an evidence-root copy; packager must physically dedupe.
- write_file(
- repo,
- "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
- b"# IO evidence workspace\n",
- )
- evid = temp / "evid"
- write_file(
- evid,
- "IO_EVIDENCE_MATRIX.zh-CN.md",
- b"# IO evidence staged\n",
- )
- write_file(
- evid,
- "evidence/formal-receipt.json",
- b'{"status":"pass","tool":"sby"}\n',
- )
- write_file(
- evid,
- "HARDWARE_BRINGUP_NOTES.zh-CN.md",
- b"# bring-up\n",
- )
- write_file(
- evid,
- "bitstream/prod2u_p4_normal_v3.bit",
- b"BITSTREAM",
- )
- write_file(
- evid,
- "lane-status/lane-f-td.json",
- b'{"status":"pass"}\n',
- )
- init_git_repo(repo)
- config = analyzer.HandoffConfig(
- max_zip_bytes=5_000_000,
- target_zip_bytes=4_000_000,
- external_sources=(),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- include_git_bundle=False,
- profile="review-compact",
- package_name="evidence-root-smoke",
- evidence_root=evid,
- )
- paths = [item.candidate.relative for item in collection.items]
- self.assertEqual(
- paths.count("evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md"),
- 1,
- "workspace+evidence-root IO must physically dedupe",
- )
- io_item = next(
- item
- for item in collection.items
- if item.candidate.relative == "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md"
- )
- self.assertEqual(io_item.source_id, "evidence-root")
- self.assertIn("evidence/formal/formal-receipt.json", paths)
- self.assertIn("evidence/hardware/HARDWARE_BRINGUP_NOTES.zh-CN.md", paths)
- self.assertIn("evidence/bitstream/prod2u_p4_normal_v3.bit", paths)
- self.assertFalse(any("lane-f-td" in path for path in paths))
- self.assertTrue(
- any(
- row.get("rule") == "canonical_path_physical_dedup"
- for row in collection.excluded
- )
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="evidence-root-smoke",
- max_zip_bytes=5_000_000,
- target_zip_bytes=4_000_000,
- force=False,
- profile="review-compact",
- )
- index = json.loads(
- (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(
- encoding="utf-8"
- )
- )
- self.assertIn("evidence_canon", index)
- self.assertIn("evidence_aliases", index)
- self.assertEqual(index["evidence_canon"]["schema"], "cpld-evidence-canon-v1")
- self.assertIn("formal_receipt", index["evidence_canon"]["compact_default_keys"])
- schema = json.loads(
- (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
- encoding="utf-8"
- )
- )
- import jsonschema
- jsonschema.validate(index, schema)
- if __name__ == "__main__":
- unittest.main()
|