| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293 |
- #!/usr/bin/env python3
- """Tests for the root-level complete agent analysis packager."""
- from __future__ import annotations
- import importlib.util
- import hashlib
- import json
- import random
- import shutil
- import subprocess
- import sys
- import tempfile
- import unittest
- import zipfile
- from pathlib import Path
- from types import ModuleType
- from unittest import mock
- import jsonschema
- ROOT = Path(__file__).resolve().parents[2]
- MODULE_PATH = ROOT / "package_for_agent_analysis.py"
- def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
- path = root / Path(relative)
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(data)
- return path
- def load_analyzer(testcase: unittest.TestCase) -> ModuleType:
- testcase.assertTrue(MODULE_PATH.is_file(), "root analysis packager is missing")
- spec = importlib.util.spec_from_file_location("package_for_agent_analysis", MODULE_PATH)
- testcase.assertIsNotNone(spec)
- testcase.assertIsNotNone(spec.loader)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- class PackageForAgentAnalysisTests(unittest.TestCase):
- maxDiff = None
- def test_config_expands_source_roots_and_rejects_positive_include_rules(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- config_path = temp / "sources.json"
- config_path.write_text(
- json.dumps(
- {
- "schema": "cpld-agent-analysis-sources-v1",
- "max_zip_bytes": 380_000_000,
- "target_zip_bytes": 350_000_000,
- "external_sources": [
- {
- "id": "board-viewer",
- "category": "hardware",
- "kind": "directory",
- "path_candidates": ["{user_profile}/board-viewer"],
- "archive_policy": "inspect",
- }
- ],
- "extra_exclusions": [],
- }
- ),
- encoding="utf-8",
- )
- config = analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- self.assertEqual(config.max_zip_bytes, 380_000_000)
- self.assertEqual(config.target_zip_bytes, 350_000_000)
- self.assertEqual(
- config.external_sources[0].path_candidates,
- (temp / "user" / "board-viewer",),
- )
- payload = json.loads(config_path.read_text(encoding="utf-8"))
- payload["external_sources"][0]["include_globs"] = ["*.brd"]
- config_path.write_text(json.dumps(payload), encoding="utf-8")
- with self.assertRaisesRegex(analyzer.PackagingError, "include"):
- analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- del payload["external_sources"][0]["include_globs"]
- payload["extra_exclusions"] = [
- {
- "path": "generated/cache",
- "reason": "known_rebuildable_cache",
- "include_globs": ["*.brd"],
- }
- ]
- config_path.write_text(json.dumps(payload), encoding="utf-8")
- with self.assertRaisesRegex(analyzer.PackagingError, "include"):
- analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- def test_default_config_and_output_index_match_versioned_schemas(self) -> None:
- analyzer = load_analyzer(self)
- config_path = ROOT / "config" / "agent_analysis_handoff_sources.json"
- config_schema_path = ROOT / "schemas" / "agent_analysis_handoff_sources.schema.json"
- index_schema_path = ROOT / "schemas" / "agent_analysis_handoff_index.schema.json"
- config_payload = json.loads(config_path.read_text(encoding="utf-8"))
- config_schema = json.loads(config_schema_path.read_text(encoding="utf-8"))
- jsonschema.validate(config_payload, config_schema)
- external_ids = {item["id"] for item in config_payload["external_sources"]}
- self.assertIn("board-viewer-generated", external_ids)
- self.assertEqual(len(external_ids), len(config_payload["external_sources"]))
- for item in config_payload["external_sources"]:
- self.assertTrue(item["id"])
- self.assertIn(item["kind"], {"directory", "file", "archive"})
- self.assertTrue(item["path_candidates"])
- self.assertIn(
- {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
- config_payload["extra_exclusions"],
- )
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"fixture")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="schema-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- index = json.loads(
- (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
- )
- index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
- jsonschema.validate(index, index_schema)
- def test_analysis_scan_recursively_excludes_generated_files_and_keeps_analysis_evidence(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- write_file(root, "src/rtl/core.v")
- write_file(root, "src/main.brd", b"board")
- write_file(root, "reference/original/board/main.brd", b"board")
- write_file(root, "reference/original/schematics/main.pdf", b"schematic")
- write_file(root, "td/build/current/design.bit", b"bitstream")
- write_file(root, "evidence/bitstream/prod2u_p4_normal_v3.bit", b"canonical-bit")
- write_file(root, ".codegraph/codegraph.db", b"graph")
- write_file(root, "tmp/formal/result.vvp", b"simulation")
- write_file(root, "tmp/formal/result.vcd", b"formal trace")
- write_file(root, "unknown/evidence.bin", b"unknown")
- write_file(root, ".venv/Scripts/python.exe", b"venv")
- write_file(root, "pkg/nested/__pycache__/cache.pyc", b"cache")
- write_file(root, "pkg/nested/.pytest_cache/v/cache/nodeids", b"cache")
- write_file(root, "pkg/nested/.venv/Scripts/python.exe", b"venv")
- write_file(root, "pkg/nested/build/design.db", b"database")
- write_file(root, "pkg/nested/build/design.vvp", b"simulation")
- write_file(root, "pkg/not__pycache__/keep.bin", b"keep")
- write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
- write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
- candidates, excluded, _ = analyzer.scan_analysis_root(root)
- included = {item.relative for item in candidates}
- self.assertIn("src/rtl/core.v", included)
- self.assertIn("reference/original/schematics/main.pdf", included)
- self.assertIn("reference/original/board/main.brd", included)
- self.assertNotIn("src/main.brd", included)
- self.assertNotIn("td/build/current/design.bit", included)
- self.assertIn("evidence/bitstream/prod2u_p4_normal_v3.bit", included)
- self.assertNotIn(".codegraph/codegraph.db", included)
- self.assertNotIn("tmp/formal/result.vvp", included)
- self.assertNotIn("tmp/formal/result.vcd", included)
- self.assertNotIn("unknown/evidence.bin", included)
- self.assertNotIn("pkg/not__pycache__/keep.bin", included)
- excluded_by_path = {item["path"]: item["rule"] for item in excluded}
- self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
- self.assertEqual(excluded_by_path["pkg/nested/__pycache__"], "python_bytecode_cache")
- self.assertEqual(excluded_by_path["pkg/nested/.pytest_cache"], "pytest_cache")
- self.assertEqual(excluded_by_path["pkg/nested/.venv"], "virtual_environment")
- self.assertEqual(excluded_by_path["pkg/nested/build"], "build_output")
- self.assertEqual(excluded_by_path["td/build"], "td_build_output")
- self.assertEqual(excluded_by_path[".codegraph"], "declared_external_reparse_alias")
- self.assertEqual(excluded_by_path["tmp"], "temporary_workspace_directory")
- self.assertEqual(excluded_by_path["src/main.brd"], "board_design_file")
- self.assertEqual(
- excluded_by_path["reference/original/local_archives/Anlogic.lic"],
- "credential_or_license_file",
- )
- self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
- def test_package_builds_without_7zip(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- source,
- relative="workspace-current/src/core.v",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- with mock.patch.object(analyzer, "find_7z", return_value=None):
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="no-7z-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertEqual(result["status"], "pass")
- self.assertEqual(len(result["volumes"]), 1)
- volume = package_dir / result["volumes"][0]["file"]
- self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
- self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
- self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
- with zipfile.ZipFile(volume) as archive:
- self.assertIsNone(archive.testzip())
- names = archive.namelist()
- self.assertIn("CPLD/workspace-current/src/core.v", names)
- self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", names)
- self.assertEqual(
- archive.read("CPLD/workspace-current/src/core.v"),
- b"module core; endmodule\n",
- )
- def test_zip_archive_expands_without_7zip(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- archive = temp / "vendor.zip"
- with zipfile.ZipFile(archive, "w") as zf:
- zf.writestr("docs/readme.txt", b"safe\n")
- zf.writestr("build/demo.bit", b"bitstream\n")
- item = analyzer.make_package_item(
- archive,
- relative="external/vendor/vendor.zip",
- category="hardware",
- source_id="vendor",
- )
- prepared = analyzer.prepare_unsupported_archives(
- (item,),
- temp_root=temp / "expanded",
- seven_zip=None,
- extra_exclusions=(),
- )
- paths = {it.candidate.relative for it in prepared.items}
- self.assertIn("external/vendor/vendor.zip.expanded/docs/readme.txt", paths)
- self.assertNotIn("external/vendor/vendor.zip.expanded/build/demo.bit", paths)
- self.assertTrue(
- any(
- entry["path"] == "external/vendor/vendor.zip"
- and entry["rule"] == "archive_contains_excluded_members"
- for entry in prepared.excluded
- )
- )
- def test_unsupported_reference_archive_warns_without_7zip(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- archive = temp / "ref.7z"
- archive.write_bytes(b"dummy")
- item = analyzer.make_package_item(
- archive,
- relative="reference/original/ref.7z",
- category="core",
- source_id="ref",
- )
- prepared = analyzer.prepare_unsupported_archives(
- (item,),
- temp_root=temp / "expanded",
- seven_zip=None,
- extra_exclusions=(),
- )
- self.assertEqual(len(prepared.items), 1)
- self.assertEqual(prepared.items[0].candidate.relative, "reference/original/ref.7z")
- self.assertFalse(prepared.items[0].scan_archive)
- self.assertTrue(
- any(
- warning["code"] == "unsupported_archive_without_7zip"
- for warning in prepared.warnings
- )
- )
- def test_unsupported_core_archive_raises_without_7zip(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- archive = temp / "core.7z"
- archive.write_bytes(b"dummy")
- item = analyzer.make_package_item(
- archive,
- relative="core/archive.7z",
- category="core",
- source_id="core",
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
- analyzer.prepare_unsupported_archives(
- (item,),
- temp_root=temp / "expanded",
- seven_zip=None,
- extra_exclusions=(),
- )
- def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
- analyzer = load_analyzer(self)
- command = analyzer.build_7zip_create_command(
- analyzer.Path("package.zip"),
- analyzer.Path("staging"),
- )
- self.assertEqual(command[:4], ["a", "-tzip", "-mm=Deflate", "-mx=9"])
- self.assertNotIn("LZMA", " ".join(command).upper())
- def test_package_rejects_source_file_added_after_collection(self) -> None:
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- repo.mkdir()
- 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,
- )
- write_file(repo, "src/core.v", b"module core; endmodule\n")
- subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- config = analyzer.HandoffConfig(
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- external_sources=(),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- )
- real_write_volume = analyzer._write_volume
- added = False
- def write_then_add(*args: object, **kwargs: object) -> dict[str, object]:
- nonlocal added
- result = real_write_volume(*args, **kwargs)
- if not added:
- write_file(repo, "new-after-scan.txt", b"late file\n")
- added = True
- return result
- with mock.patch.object(analyzer, "_write_volume", side_effect=write_then_add):
- with self.assertRaisesRegex(analyzer.PackagingError, "source tree changed"):
- analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="source-snapshot",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- def test_missing_external_sources_are_warnings(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- existing = temp / "existing"
- write_file(existing, "board.xml", b"board")
- source_type = analyzer.ExternalSource
- sources = (
- source_type(
- id="existing",
- category="hardware",
- kind="directory",
- path_candidates=(existing,),
- archive_policy="inspect",
- ),
- source_type(
- id="missing",
- category="td-docs",
- kind="directory",
- path_candidates=(temp / "missing",),
- archive_policy="inspect",
- ),
- )
- resolved, warnings = analyzer.resolve_external_sources(sources)
- self.assertEqual([item.id for item in resolved], ["existing"])
- self.assertEqual(len(warnings), 1)
- self.assertEqual(warnings[0]["code"], "missing_external_source")
- self.assertEqual(warnings[0]["source_id"], "missing")
- def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- review = temp / "review"
- for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
- root.mkdir()
- subprocess.run([git, "init", "-q", str(root)], check=True)
- subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
- subprocess.run(
- [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
- check=True,
- )
- write_file(root, tracked_name, tracked_name.encode("ascii"))
- subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
- subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
- write_file(repo, "td/build/current/design.bit", b"bitstream")
- write_file(review, "notes/untracked.txt", b"review notes")
- config = analyzer.HandoffConfig(
- max_zip_bytes=380_000_000,
- target_zip_bytes=350_000_000,
- external_sources=(
- analyzer.ExternalSource(
- id="review-worktree",
- category="core",
- kind="git_worktree",
- path_candidates=(review,),
- archive_policy="inspect",
- ),
- analyzer.ExternalSource(
- id="missing-docs",
- category="td-docs",
- kind="directory",
- path_candidates=(temp / "missing",),
- archive_policy="inspect",
- ),
- ),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- )
- item_paths = {item.candidate.relative for item in collection.items}
- self.assertNotIn("workspace-current/td/build/current/design.bit", item_paths)
- self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
- self.assertIn("git-history/workspace-current.bundle", item_paths)
- self.assertIn("git-history/review-worktree.bundle", item_paths)
- self.assertEqual(collection.status, "pass_with_warnings")
- self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
- sources_by_id = {item["id"]: item for item in collection.sources}
- self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
- self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
- for item in collection.items:
- if item.candidate.relative.startswith("git-history/"):
- # Verify inside a real Git repo cwd — never mis-blame tool
- # behavior when cwd is a non-repository (detached extract).
- result = subprocess.run(
- [git, "bundle", "verify", str(item.candidate.absolute)],
- cwd=str(repo),
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
- def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- repo.mkdir()
- 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,
- )
- write_file(repo, "tracked.txt", b"tracked")
- subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- invalid = temp / "invalid-worktree"
- write_file(invalid, "notes.txt", b"not a Git repository")
- config = analyzer.HandoffConfig(
- max_zip_bytes=380_000_000,
- target_zip_bytes=350_000_000,
- external_sources=(
- analyzer.ExternalSource(
- id="invalid-worktree",
- category="core",
- kind="git_worktree",
- path_candidates=(invalid,),
- archive_policy="inspect",
- ),
- ),
- extra_exclusions=(),
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
- analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- )
- def test_archive_with_generated_members_keeps_only_sanitized_expansion(self) -> None:
- analyzer = load_analyzer(self)
- seven_zip = analyzer.find_7z()
- if seven_zip is None:
- self.skipTest("7-Zip is required")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- def make_archive(name: str, entries: dict[str, bytes]) -> Path:
- source = temp / f"{name}-source"
- for relative, data in entries.items():
- write_file(source, relative, data)
- archive = temp / f"{name}.7z"
- result = subprocess.run(
- [str(seven_zip), "a", "-t7z", "-r", str(archive), "*"],
- cwd=source,
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
- return archive
- safe_archive = make_archive(
- "safe",
- {
- "docs/readme.txt": b"safe\n",
- "td_project/demo_Runs/demo.bit": b"bitstream\n",
- },
- )
- sensitive_archive = make_archive(
- "sensitive",
- {
- "docs/readme.txt": b"safe\n",
- "private/Anlogic.lic": b"license\n",
- },
- )
- items = (
- analyzer.make_package_item(
- safe_archive,
- relative="external/hardware/safe.7z",
- category="hardware",
- source_id="hardware",
- ),
- analyzer.make_package_item(
- sensitive_archive,
- relative="external/hardware/sensitive.7z",
- category="hardware",
- source_id="hardware",
- ),
- )
- prepared = analyzer.prepare_unsupported_archives(
- items,
- temp_root=temp / "expanded",
- seven_zip=seven_zip,
- extra_exclusions=(),
- )
- paths = {item.candidate.relative for item in prepared.items}
- self.assertNotIn("external/hardware/safe.7z", paths)
- self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
- self.assertNotIn("external/hardware/safe.7z.expanded/td_project/demo_Runs/demo.bit", paths)
- self.assertNotIn("external/hardware/sensitive.7z", paths)
- self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
- self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
- self.assertTrue(
- any(
- item["path"] == "external/hardware/sensitive.7z"
- and item["rule"] == "unsupported_archive_contains_sensitive_content"
- for item in prepared.excluded
- )
- )
- self.assertTrue(
- any(
- item["path"] == "external/hardware/safe.7z"
- and item["rule"] == "archive_contains_excluded_members"
- for item in prepared.excluded
- )
- )
- def test_supported_archive_rejects_license_member_by_path(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- archive_path = temp / "vendor.zip"
- with zipfile.ZipFile(archive_path, "w") as archive:
- archive.writestr("docs/readme.txt", b"safe\n")
- archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
- item = analyzer.make_package_item(
- archive_path,
- relative="external/vendor/vendor.zip",
- category="hardware",
- source_id="vendor",
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
- analyzer._audit_package_items((item,))
- def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- external = temp / "board-viewer"
- board = write_file(external, "board.cad", b"board")
- cached = write_file(external, ".venv/cache.bin", b"cache")
- config_path = temp / "sources.json"
- config_path.write_text(
- json.dumps(
- {
- "schema": "cpld-agent-analysis-sources-v1",
- "max_zip_bytes": 380_000_000,
- "target_zip_bytes": 350_000_000,
- "external_sources": [
- {
- "id": "board-viewer",
- "category": "hardware",
- "kind": "directory",
- "path_candidates": [str(external)],
- "archive_policy": "inspect",
- }
- ],
- "extra_exclusions": [],
- }
- ),
- encoding="utf-8",
- )
- help_result = subprocess.run(
- [sys.executable, str(MODULE_PATH), "--help"],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(help_result.returncode, 0, help_result.stderr)
- for option in (
- "--audit-only",
- "--explain",
- "--config",
- "--output-dir",
- "--package-name",
- "--force-overwrite",
- ):
- self.assertIn(option, help_result.stdout)
- included_result = subprocess.run(
- [
- sys.executable,
- str(MODULE_PATH),
- "--config",
- str(config_path),
- "--explain",
- str(board),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(included_result.returncode, 0, included_result.stderr)
- included = json.loads(included_result.stdout)
- self.assertEqual(included["decision"], "include")
- self.assertEqual(included["source_id"], "board-viewer")
- excluded_result = subprocess.run(
- [
- sys.executable,
- str(MODULE_PATH),
- "--config",
- str(config_path),
- "--explain",
- str(cached),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
- excluded = json.loads(excluded_result.stdout)
- self.assertEqual(excluded["decision"], "exclude")
- self.assertEqual(excluded["reason"], "virtual_environment")
- def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- first = write_file(source, "src/core.v", b"module core; endmodule\n")
- second = write_file(source, "reference/original/main.brd", b"board\n")
- collection = analyzer.AnalysisCollection(
- status="pass_with_warnings",
- items=(
- analyzer.make_package_item(
- first,
- relative="workspace-current/src/core.v",
- category="core",
- source_id="workspace-current",
- ),
- analyzer.make_package_item(
- second,
- relative="workspace-current/reference/original/main.brd",
- category="hardware",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(
- {
- "code": "missing_external_source",
- "source_id": "td-docs",
- "message": "missing",
- },
- ),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="single-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertEqual(result["status"], "pass_with_warnings")
- self.assertEqual(len(result["volumes"]), 1)
- volume = package_dir / result["volumes"][0]["file"]
- self.assertLess(volume.stat().st_size, 1_000_000)
- self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
- self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
- self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
- with zipfile.ZipFile(volume) as archive:
- self.assertIsNone(archive.testzip())
- self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
- self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
- self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(index["status"], "pass_with_warnings")
- self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
- def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- randomizer = random.Random(7)
- items = []
- for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
- path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
- items.append(
- analyzer.make_package_item(
- path,
- relative=f"workspace-current/data/file-{index}.bin",
- category=category,
- source_id="workspace-current",
- )
- )
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=tuple(items),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="multi-fixture",
- max_zip_bytes=30_000,
- target_zip_bytes=20_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertGreaterEqual(len(result["volumes"]), 2)
- seen_entries: set[str] = set()
- for volume_info in result["volumes"]:
- volume = package_dir / volume_info["file"]
- self.assertLess(volume.stat().st_size, 30_000)
- with zipfile.ZipFile(volume) as archive:
- self.assertIsNone(archive.testzip())
- self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
- seen_entries.update(
- name
- for name in archive.namelist()
- if name.startswith("CPLD/workspace-current/data/") and not name.endswith("/")
- )
- self.assertEqual(len(seen_entries), 4)
- def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- payload = random.Random(19).randbytes(55_000)
- large = write_file(source, "data/large.db", payload)
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- large,
- relative="workspace-current/data/large.db",
- category="evidence",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="large-fixture",
- max_zip_bytes=30_000,
- target_zip_bytes=20_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- for volume_info in result["volumes"]:
- self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(len(index["large_files"]), 1)
- large_info = index["large_files"][0]
- self.assertEqual(large_info["path"], "workspace-current/data/large.db")
- self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
- self.assertGreaterEqual(len(large_info["chunks"]), 2)
- reassembler = package_dir / "reassemble_large_files.py"
- self.assertTrue(reassembler.is_file())
- reconstructed = temp / "reconstructed"
- completed = subprocess.run(
- [
- sys.executable,
- str(reassembler),
- "--package-dir",
- str(package_dir),
- "--output-dir",
- str(reconstructed),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
- rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
- self.assertEqual(rebuilt.read_bytes(), payload)
- def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"replacement")
- output_root = temp / "output"
- final_dir = output_root / "atomic-fixture"
- final_dir.mkdir(parents=True)
- marker = write_file(final_dir, "old-marker.txt", b"old package")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- real_replace = analyzer.os.replace
- def fail_new_directory(source_path: object, target_path: object) -> None:
- source_name = Path(source_path).name
- if (
- source_name != "atomic-fixture"
- and not source_name.endswith(".backup")
- and Path(target_path).name == "atomic-fixture"
- ):
- raise OSError("injected publication failure")
- real_replace(source_path, target_path)
- with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
- with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
- analyzer.create_analysis_package(
- collection=collection,
- output_root=output_root,
- package_name="atomic-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=True,
- )
- self.assertEqual(marker.read_bytes(), b"old package")
- self.assertEqual(
- [path.name for path in output_root.iterdir()],
- ["atomic-fixture"],
- )
- def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"replacement")
- output_root = temp / "output"
- final_dir = output_root / "backup-failure-fixture"
- final_dir.mkdir(parents=True)
- marker = write_file(final_dir, "old-marker.txt", b"old package")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- real_replace = analyzer.os.replace
- def fail_backup_move(source_path: object, target_path: object) -> None:
- if Path(source_path).name == "backup-failure-fixture":
- raise OSError("injected backup move failure")
- real_replace(source_path, target_path)
- with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
- with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
- analyzer.create_analysis_package(
- collection=collection,
- output_root=output_root,
- package_name="backup-failure-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=True,
- )
- self.assertEqual(marker.read_bytes(), b"old package")
- self.assertEqual(
- [path.name for path in output_root.iterdir()],
- ["backup-failure-fixture"],
- )
- def test_package_layout_writes_exclusions_tar_zst_and_checksums(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- source,
- relative="workspace-current/src/core.v",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(
- {"path": ".venv", "rule": "virtual_environment"},
- {"path": "tmp", "rule": "temporary_workspace_directory"},
- ),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="layout-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
- self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
- self.assertTrue((package_dir / "EXCLUSIONS.txt").is_file())
- self.assertTrue((package_dir / "layout-fixture.tar.zst").is_file())
- exclusions = (package_dir / "EXCLUSIONS.txt").read_text(encoding="utf-8")
- self.assertIn(".venv\tvirtual_environment", exclusions)
- sums = (package_dir / "SHA256SUMS.txt").read_text(encoding="ascii")
- self.assertIn("layout-fixture.tar.zst", sums)
- self.assertIn("EXCLUSIONS.txt", sums)
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(index["formats"]["tar_zst"], "layout-fixture.tar.zst")
- replay = analyzer.replay_analysis_package(
- package_dir,
- extract_root=temp / "replay",
- )
- self.assertEqual(replay["status"], "pass")
- self.assertTrue(replay["exclusions_present"])
- self.assertEqual(replay["tar_zst"], "layout-fixture.tar.zst")
- def test_chinese_and_spaces_path_round_trip(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- relative = "workspace-current/docs/中文目录/file with spaces.txt"
- source = write_file(
- temp / "source",
- "docs/中文目录/file with spaces.txt",
- "中文内容与 spaces\n".encode("utf-8"),
- )
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- source,
- relative=relative,
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="unicode-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- volume = package_dir / result["volumes"][0]["file"]
- with zipfile.ZipFile(volume) as archive:
- names = archive.namelist()
- self.assertIn(f"CPLD/{relative}", names)
- info = archive.getinfo(f"CPLD/{relative}")
- self.assertTrue(info.flag_bits & 0x800)
- self.assertEqual(
- archive.read(f"CPLD/{relative}"),
- "中文内容与 spaces\n".encode("utf-8"),
- )
- replay = analyzer.replay_analysis_package(
- package_dir,
- extract_root=temp / "replay-unicode",
- )
- self.assertEqual(replay["status"], "pass")
- self.assertEqual(replay["checked_files"], 1)
- def test_full_profile_requires_git_bundle(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- repo.mkdir()
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- 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,
- )
- write_file(repo, "src/core.v", b"module core; endmodule\n")
- subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- config = analyzer.HandoffConfig(
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- external_sources=(),
- extra_exclusions=(),
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "git bundle"):
- analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- include_git_bundle=False,
- profile="full",
- )
- class ReviewCompactProfileSmokeTests(unittest.TestCase):
- maxDiff = None
- def _init_repo(self, repo: Path) -> str:
- git = shutil.which("git")
- if not git:
- self.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,
- )
- write_file(repo, "src/core.v", b"module core; endmodule\n")
- write_file(
- repo,
- "receipts/verification-matrix-final.json",
- b'{"status":"pass","schema":"fixture"}\n',
- )
- write_file(repo, "reference/original/board/main.brd", b"BOARD")
- write_file(repo, "reference/original/schematics/main.pdf", b"%PDF")
- write_file(repo, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
- write_file(repo, ".run_id_stale", b"stale\n")
- write_file(repo, "node_modules/pkg/index.js", b"nope\n")
- subprocess.run(
- [git, "-C", str(repo), "add", "src/core.v", "receipts/verification-matrix-final.json"],
- check=True,
- )
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- return git
- def test_review_compact_excludes_heavy_originals_keeps_fixtures(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- write_file(root, "src/core.v", b"module core; endmodule\n")
- write_file(root, "reference/original/board/main.brd", b"BOARD")
- write_file(root, "reference/original/schematics/main.pdf", b"%PDF")
- write_file(root, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
- write_file(root, ".run_id_stale", b"stale\n")
- candidates, excluded, _ = analyzer.scan_analysis_root(root, profile="review-compact")
- included = {item.relative for item in candidates}
- self.assertIn("src/core.v", included)
- self.assertIn("tests/board_viewer/fixtures/tiny.dsn", included)
- self.assertNotIn("reference/original/board/main.brd", included)
- self.assertNotIn("reference/original/schematics/main.pdf", included)
- self.assertNotIn(".run_id_stale", included)
- rules = {item["path"]: item["rule"] for item in excluded}
- self.assertEqual(rules.get("reference/original/board"), "reference_original_board")
- def test_review_compact_unified_layout_and_no_git_bundle(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- self._init_repo(repo)
- generated = temp / "generated"
- write_file(generated, "board-data.json", b'{"ok":true}\n')
- write_file(generated, "build-info.json", b'{"ok":true}\n')
- write_file(generated, "import-report.json", b'{"ok":true}\n')
- write_file(generated, "board-copper.svg", b"<svg/>\n")
- write_file(generated, "board-silkscreen.svg", b"<svg/>\n")
- write_file(generated, "board-mask-edge.svg", b"<svg/>\n")
- write_file(generated, "board-copper-back.svg", b"<svg/>\n")
- write_file(generated, "board-silkscreen-back.svg", b"<svg/>\n")
- write_file(generated, "board-mask-edge-back.svg", b"<svg/>\n")
- config = analyzer.HandoffConfig(
- max_zip_bytes=5_000_000,
- target_zip_bytes=4_000_000,
- external_sources=(
- analyzer.ExternalSource(
- id="board-viewer-generated",
- category="hardware",
- kind="directory",
- path_candidates=(generated,),
- archive_policy="copy",
- ),
- ),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- include_git_bundle=True, # must be forced off for review-compact
- profile="review-compact",
- package_name="smoke-review-compact",
- )
- paths = {item.candidate.relative for item in collection.items}
- self.assertTrue(any(path.startswith("source/") for path in paths))
- self.assertIn("source/src/core.v", paths)
- self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
- self.assertIn("evidence/board-viewer/board-data.json", paths)
- self.assertTrue(any(path.startswith("meta/git/") for path in paths))
- self.assertFalse(any(path.endswith(".bundle") for path in paths))
- self.assertFalse(any("reference/original/board" in path for path in paths))
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="smoke-review-compact",
- max_zip_bytes=5_000_000,
- target_zip_bytes=4_000_000,
- force=False,
- profile="review-compact",
- )
- package_dir = Path(result["output_dir"])
- self.assertEqual(result["delivery_policy"], "review-compact")
- self.assertTrue((package_dir / "PACKAGE-PURPOSE.txt").is_file())
- self.assertTrue((package_dir / "size-budget.json").is_file())
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(index["profile"], "review-compact")
- self.assertIn("member_count", index)
- self.assertIn("self_reference_control_files", index["member_count"])
- self.assertIn("size_budget", index)
- volume = package_dir / result["volumes"][0]["file"]
- with zipfile.ZipFile(volume) as archive:
- names = set(archive.namelist())
- self.assertIn("CPLD/source/src/core.v", names)
- self.assertIn("CPLD/evidence/matrix/verification-matrix-final.json", names)
- self.assertIn("CPLD/meta/git/log-20.txt", names)
- self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
- self.assertFalse(any(name.endswith(".bundle") for name in names))
- index_schema = json.loads(
- (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
- encoding="utf-8"
- )
- )
- jsonschema.validate(index, index_schema)
- def test_review_debug_and_archive_local_profiles_are_registered(self) -> None:
- analyzer = load_analyzer(self)
- self.assertIn("review-debug", analyzer.handoff.HANDOFF_PROFILES)
- self.assertIn("archive-local", analyzer.handoff.HANDOFF_PROFILES)
- self.assertEqual(analyzer.handoff.DEFAULT_HANDOFF_PROFILE, "review-compact")
- self.assertTrue(analyzer.handoff.uses_unified_layout("review-debug"))
- self.assertEqual(
- analyzer.handoff.delivery_policy_for_profile("archive-local"),
- "archive-local",
- )
- if __name__ == "__main__":
- unittest.main()
|