#!/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) self.assertEqual( {item["id"] for item in config_payload["external_sources"]}, {"td-docs", "board-viewer", "p4-review-worktree", "codegraph"}, ) 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_keeps_unknown_and_generated_files(self) -> None: analyzer = load_analyzer(self) with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) write_file(root, "src/rtl/core.v") write_file(root, "reference/original/board/main.brd", b"board") write_file(root, "td/build/current/design.bit", b"bitstream") write_file(root, ".codegraph/codegraph.db", b"graph") write_file(root, "tmp/formal/result.vvp", b"simulation") write_file(root, "unknown/evidence.bin", b"unknown") write_file(root, ".venv/Scripts/python.exe", b"venv") write_file(root, "pkg/__pycache__/cache.pyc", b"cache") 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/board/main.brd", included) self.assertIn("td/build/current/design.bit", included) self.assertIn(".codegraph/codegraph.db", included) self.assertIn("tmp/formal/result.vvp", included) self.assertIn("unknown/evidence.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/__pycache__"], "python_bytecode_cache") self.assertEqual( excluded_by_path["reference/original/local_archives/Anlogic.lic"], "credential_or_license_file", ) self.assertEqual( excluded_by_path["tmp/sysinternals-handle-test"], "external_tool_cache", ) 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.assertIn("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/"): result = subprocess.run( [git, "bundle", "verify", str(item.candidate.absolute)], 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_unsupported_archive_keeps_safe_raw_and_sanitizes_license_archive(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", 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"}) 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.assertIn("external/hardware/safe.7z", paths) self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", 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 ) ) raw_safe = next( item for item in prepared.items if item.candidate.relative == "external/hardware/safe.7z" ) self.assertFalse(raw_safe.scan_archive) 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/") ) 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"], ) if __name__ == "__main__": unittest.main()