#!/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"\n") write_file(generated, "board-silkscreen.svg", b"\n") write_file(generated, "board-mask-edge.svg", b"\n") write_file(generated, "board-copper-back.svg", b"\n") write_file(generated, "board-silkscreen-back.svg", b"\n") write_file(generated, "board-mask-edge-back.svg", b"\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()