| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007 |
- #!/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"]},
- set(),
- )
- 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, ".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.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/"):
- 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_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", 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"],
- )
- if __name__ == "__main__":
- unittest.main()
|