test_package_for_agent_analysis.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. #!/usr/bin/env python3
  2. """Tests for the root-level complete agent analysis packager."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import hashlib
  6. import json
  7. import random
  8. import shutil
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import unittest
  13. import zipfile
  14. from pathlib import Path
  15. from types import ModuleType
  16. from unittest import mock
  17. import jsonschema
  18. ROOT = Path(__file__).resolve().parents[2]
  19. MODULE_PATH = ROOT / "package_for_agent_analysis.py"
  20. def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
  21. path = root / Path(relative)
  22. path.parent.mkdir(parents=True, exist_ok=True)
  23. path.write_bytes(data)
  24. return path
  25. def load_analyzer(testcase: unittest.TestCase) -> ModuleType:
  26. testcase.assertTrue(MODULE_PATH.is_file(), "root analysis packager is missing")
  27. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", MODULE_PATH)
  28. testcase.assertIsNotNone(spec)
  29. testcase.assertIsNotNone(spec.loader)
  30. module = importlib.util.module_from_spec(spec)
  31. spec.loader.exec_module(module)
  32. return module
  33. class PackageForAgentAnalysisTests(unittest.TestCase):
  34. maxDiff = None
  35. def test_config_expands_source_roots_and_rejects_positive_include_rules(self) -> None:
  36. analyzer = load_analyzer(self)
  37. with tempfile.TemporaryDirectory() as tmp:
  38. temp = Path(tmp)
  39. config_path = temp / "sources.json"
  40. config_path.write_text(
  41. json.dumps(
  42. {
  43. "schema": "cpld-agent-analysis-sources-v1",
  44. "max_zip_bytes": 380_000_000,
  45. "target_zip_bytes": 350_000_000,
  46. "external_sources": [
  47. {
  48. "id": "board-viewer",
  49. "category": "hardware",
  50. "kind": "directory",
  51. "path_candidates": ["{user_profile}/board-viewer"],
  52. "archive_policy": "inspect",
  53. }
  54. ],
  55. "extra_exclusions": [],
  56. }
  57. ),
  58. encoding="utf-8",
  59. )
  60. config = analyzer.load_config(
  61. config_path,
  62. repo_root=temp / "repo",
  63. user_profile=temp / "user",
  64. )
  65. self.assertEqual(config.max_zip_bytes, 380_000_000)
  66. self.assertEqual(config.target_zip_bytes, 350_000_000)
  67. self.assertEqual(
  68. config.external_sources[0].path_candidates,
  69. (temp / "user" / "board-viewer",),
  70. )
  71. payload = json.loads(config_path.read_text(encoding="utf-8"))
  72. payload["external_sources"][0]["include_globs"] = ["*.brd"]
  73. config_path.write_text(json.dumps(payload), encoding="utf-8")
  74. with self.assertRaisesRegex(analyzer.PackagingError, "include"):
  75. analyzer.load_config(
  76. config_path,
  77. repo_root=temp / "repo",
  78. user_profile=temp / "user",
  79. )
  80. del payload["external_sources"][0]["include_globs"]
  81. payload["extra_exclusions"] = [
  82. {
  83. "path": "generated/cache",
  84. "reason": "known_rebuildable_cache",
  85. "include_globs": ["*.brd"],
  86. }
  87. ]
  88. config_path.write_text(json.dumps(payload), encoding="utf-8")
  89. with self.assertRaisesRegex(analyzer.PackagingError, "include"):
  90. analyzer.load_config(
  91. config_path,
  92. repo_root=temp / "repo",
  93. user_profile=temp / "user",
  94. )
  95. def test_default_config_and_output_index_match_versioned_schemas(self) -> None:
  96. analyzer = load_analyzer(self)
  97. config_path = ROOT / "config" / "agent_analysis_handoff_sources.json"
  98. config_schema_path = ROOT / "schemas" / "agent_analysis_handoff_sources.schema.json"
  99. index_schema_path = ROOT / "schemas" / "agent_analysis_handoff_index.schema.json"
  100. config_payload = json.loads(config_path.read_text(encoding="utf-8"))
  101. config_schema = json.loads(config_schema_path.read_text(encoding="utf-8"))
  102. jsonschema.validate(config_payload, config_schema)
  103. self.assertEqual(
  104. {item["id"] for item in config_payload["external_sources"]},
  105. set(),
  106. )
  107. self.assertIn(
  108. {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
  109. config_payload["extra_exclusions"],
  110. )
  111. with tempfile.TemporaryDirectory() as tmp:
  112. temp = Path(tmp)
  113. source = temp / "source"
  114. item = write_file(source, "data/file.bin", b"fixture")
  115. collection = analyzer.AnalysisCollection(
  116. status="pass",
  117. items=(
  118. analyzer.make_package_item(
  119. item,
  120. relative="workspace-current/data/file.bin",
  121. category="core",
  122. source_id="workspace-current",
  123. ),
  124. ),
  125. excluded=(),
  126. warnings=(),
  127. sources=({"id": "workspace-current", "status": "pass"},),
  128. git=(),
  129. )
  130. result = analyzer.create_analysis_package(
  131. collection=collection,
  132. output_root=temp / "output",
  133. package_name="schema-fixture",
  134. max_zip_bytes=1_000_000,
  135. target_zip_bytes=800_000,
  136. force=False,
  137. )
  138. index = json.loads(
  139. (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
  140. )
  141. index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
  142. jsonschema.validate(index, index_schema)
  143. def test_analysis_scan_recursively_excludes_generated_files_and_keeps_analysis_evidence(self) -> None:
  144. analyzer = load_analyzer(self)
  145. with tempfile.TemporaryDirectory() as tmp:
  146. root = Path(tmp)
  147. write_file(root, "src/rtl/core.v")
  148. write_file(root, "src/main.brd", b"board")
  149. write_file(root, "reference/original/board/main.brd", b"board")
  150. write_file(root, "reference/original/schematics/main.pdf", b"schematic")
  151. write_file(root, "td/build/current/design.bit", b"bitstream")
  152. write_file(root, ".codegraph/codegraph.db", b"graph")
  153. write_file(root, "tmp/formal/result.vvp", b"simulation")
  154. write_file(root, "tmp/formal/result.vcd", b"formal trace")
  155. write_file(root, "unknown/evidence.bin", b"unknown")
  156. write_file(root, ".venv/Scripts/python.exe", b"venv")
  157. write_file(root, "pkg/nested/__pycache__/cache.pyc", b"cache")
  158. write_file(root, "pkg/nested/.pytest_cache/v/cache/nodeids", b"cache")
  159. write_file(root, "pkg/nested/.venv/Scripts/python.exe", b"venv")
  160. write_file(root, "pkg/nested/build/design.db", b"database")
  161. write_file(root, "pkg/nested/build/design.vvp", b"simulation")
  162. write_file(root, "pkg/not__pycache__/keep.bin", b"keep")
  163. write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
  164. write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
  165. candidates, excluded, _ = analyzer.scan_analysis_root(root)
  166. included = {item.relative for item in candidates}
  167. self.assertIn("src/rtl/core.v", included)
  168. self.assertIn("reference/original/schematics/main.pdf", included)
  169. self.assertIn("reference/original/board/main.brd", included)
  170. self.assertNotIn("src/main.brd", included)
  171. self.assertNotIn("td/build/current/design.bit", included)
  172. self.assertNotIn(".codegraph/codegraph.db", included)
  173. self.assertNotIn("tmp/formal/result.vvp", included)
  174. self.assertNotIn("tmp/formal/result.vcd", included)
  175. self.assertNotIn("unknown/evidence.bin", included)
  176. self.assertNotIn("pkg/not__pycache__/keep.bin", included)
  177. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  178. self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
  179. self.assertEqual(excluded_by_path["pkg/nested/__pycache__"], "python_bytecode_cache")
  180. self.assertEqual(excluded_by_path["pkg/nested/.pytest_cache"], "pytest_cache")
  181. self.assertEqual(excluded_by_path["pkg/nested/.venv"], "virtual_environment")
  182. self.assertEqual(excluded_by_path["pkg/nested/build"], "build_output")
  183. self.assertEqual(excluded_by_path["td/build"], "td_build_output")
  184. self.assertEqual(excluded_by_path[".codegraph"], "declared_external_reparse_alias")
  185. self.assertEqual(excluded_by_path["tmp"], "temporary_workspace_directory")
  186. self.assertEqual(excluded_by_path["src/main.brd"], "board_design_file")
  187. self.assertEqual(
  188. excluded_by_path["reference/original/local_archives/Anlogic.lic"],
  189. "credential_or_license_file",
  190. )
  191. self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
  192. def test_7zip_is_required_for_package_creation(self) -> None:
  193. analyzer = load_analyzer(self)
  194. with tempfile.TemporaryDirectory() as tmp:
  195. temp = Path(tmp)
  196. source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
  197. collection = analyzer.AnalysisCollection(
  198. status="pass",
  199. items=(
  200. analyzer.make_package_item(
  201. source,
  202. relative="workspace-current/src/core.v",
  203. category="core",
  204. source_id="workspace-current",
  205. ),
  206. ),
  207. excluded=(),
  208. warnings=(),
  209. sources=({"id": "workspace-current", "status": "pass"},),
  210. git=(),
  211. )
  212. with mock.patch.object(analyzer, "find_7z", return_value=None):
  213. with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
  214. analyzer.create_analysis_package(
  215. collection=collection,
  216. output_root=temp / "output",
  217. package_name="requires-7z",
  218. max_zip_bytes=1_000_000,
  219. target_zip_bytes=800_000,
  220. force=False,
  221. )
  222. def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
  223. analyzer = load_analyzer(self)
  224. command = analyzer.build_7zip_create_command(
  225. analyzer.Path("package.zip"),
  226. analyzer.Path("staging"),
  227. )
  228. self.assertEqual(command[:4], ["a", "-tzip", "-mm=Deflate", "-mx=9"])
  229. self.assertNotIn("LZMA", " ".join(command).upper())
  230. def test_package_rejects_source_file_added_after_collection(self) -> None:
  231. git = shutil.which("git")
  232. if not git:
  233. self.skipTest("Git is required")
  234. analyzer = load_analyzer(self)
  235. with tempfile.TemporaryDirectory() as tmp:
  236. temp = Path(tmp)
  237. repo = temp / "repo"
  238. repo.mkdir()
  239. subprocess.run([git, "init", "-q", str(repo)], check=True)
  240. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  241. subprocess.run(
  242. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  243. check=True,
  244. )
  245. write_file(repo, "src/core.v", b"module core; endmodule\n")
  246. subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
  247. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  248. config = analyzer.HandoffConfig(
  249. max_zip_bytes=1_000_000,
  250. target_zip_bytes=800_000,
  251. external_sources=(),
  252. extra_exclusions=(),
  253. )
  254. collection = analyzer.collect_analysis_inputs(
  255. repo_root=repo,
  256. config=config,
  257. temp_root=temp / "run",
  258. )
  259. real_write_volume = analyzer._write_volume
  260. added = False
  261. def write_then_add(*args: object, **kwargs: object) -> dict[str, object]:
  262. nonlocal added
  263. result = real_write_volume(*args, **kwargs)
  264. if not added:
  265. write_file(repo, "new-after-scan.txt", b"late file\n")
  266. added = True
  267. return result
  268. with mock.patch.object(analyzer, "_write_volume", side_effect=write_then_add):
  269. with self.assertRaisesRegex(analyzer.PackagingError, "source tree changed"):
  270. analyzer.create_analysis_package(
  271. collection=collection,
  272. output_root=temp / "output",
  273. package_name="source-snapshot",
  274. max_zip_bytes=1_000_000,
  275. target_zip_bytes=800_000,
  276. force=False,
  277. )
  278. def test_missing_external_sources_are_warnings(self) -> None:
  279. analyzer = load_analyzer(self)
  280. with tempfile.TemporaryDirectory() as tmp:
  281. temp = Path(tmp)
  282. existing = temp / "existing"
  283. write_file(existing, "board.xml", b"board")
  284. source_type = analyzer.ExternalSource
  285. sources = (
  286. source_type(
  287. id="existing",
  288. category="hardware",
  289. kind="directory",
  290. path_candidates=(existing,),
  291. archive_policy="inspect",
  292. ),
  293. source_type(
  294. id="missing",
  295. category="td-docs",
  296. kind="directory",
  297. path_candidates=(temp / "missing",),
  298. archive_policy="inspect",
  299. ),
  300. )
  301. resolved, warnings = analyzer.resolve_external_sources(sources)
  302. self.assertEqual([item.id for item in resolved], ["existing"])
  303. self.assertEqual(len(warnings), 1)
  304. self.assertEqual(warnings[0]["code"], "missing_external_source")
  305. self.assertEqual(warnings[0]["source_id"], "missing")
  306. def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
  307. git = shutil.which("git")
  308. if not git:
  309. self.skipTest("Git is required")
  310. analyzer = load_analyzer(self)
  311. with tempfile.TemporaryDirectory() as tmp:
  312. temp = Path(tmp)
  313. repo = temp / "repo"
  314. review = temp / "review"
  315. for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
  316. root.mkdir()
  317. subprocess.run([git, "init", "-q", str(root)], check=True)
  318. subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
  319. subprocess.run(
  320. [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
  321. check=True,
  322. )
  323. write_file(root, tracked_name, tracked_name.encode("ascii"))
  324. subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
  325. subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
  326. write_file(repo, "td/build/current/design.bit", b"bitstream")
  327. write_file(review, "notes/untracked.txt", b"review notes")
  328. config = analyzer.HandoffConfig(
  329. max_zip_bytes=380_000_000,
  330. target_zip_bytes=350_000_000,
  331. external_sources=(
  332. analyzer.ExternalSource(
  333. id="review-worktree",
  334. category="core",
  335. kind="git_worktree",
  336. path_candidates=(review,),
  337. archive_policy="inspect",
  338. ),
  339. analyzer.ExternalSource(
  340. id="missing-docs",
  341. category="td-docs",
  342. kind="directory",
  343. path_candidates=(temp / "missing",),
  344. archive_policy="inspect",
  345. ),
  346. ),
  347. extra_exclusions=(),
  348. )
  349. collection = analyzer.collect_analysis_inputs(
  350. repo_root=repo,
  351. config=config,
  352. temp_root=temp / "run",
  353. )
  354. item_paths = {item.candidate.relative for item in collection.items}
  355. self.assertNotIn("workspace-current/td/build/current/design.bit", item_paths)
  356. self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
  357. self.assertIn("git-history/workspace-current.bundle", item_paths)
  358. self.assertIn("git-history/review-worktree.bundle", item_paths)
  359. self.assertEqual(collection.status, "pass_with_warnings")
  360. self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
  361. sources_by_id = {item["id"]: item for item in collection.sources}
  362. self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
  363. self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
  364. for item in collection.items:
  365. if item.candidate.relative.startswith("git-history/"):
  366. result = subprocess.run(
  367. [git, "bundle", "verify", str(item.candidate.absolute)],
  368. capture_output=True,
  369. text=True,
  370. check=False,
  371. )
  372. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  373. def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
  374. git = shutil.which("git")
  375. if not git:
  376. self.skipTest("Git is required")
  377. analyzer = load_analyzer(self)
  378. with tempfile.TemporaryDirectory() as tmp:
  379. temp = Path(tmp)
  380. repo = temp / "repo"
  381. repo.mkdir()
  382. subprocess.run([git, "init", "-q", str(repo)], check=True)
  383. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  384. subprocess.run(
  385. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  386. check=True,
  387. )
  388. write_file(repo, "tracked.txt", b"tracked")
  389. subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
  390. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  391. invalid = temp / "invalid-worktree"
  392. write_file(invalid, "notes.txt", b"not a Git repository")
  393. config = analyzer.HandoffConfig(
  394. max_zip_bytes=380_000_000,
  395. target_zip_bytes=350_000_000,
  396. external_sources=(
  397. analyzer.ExternalSource(
  398. id="invalid-worktree",
  399. category="core",
  400. kind="git_worktree",
  401. path_candidates=(invalid,),
  402. archive_policy="inspect",
  403. ),
  404. ),
  405. extra_exclusions=(),
  406. )
  407. with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
  408. analyzer.collect_analysis_inputs(
  409. repo_root=repo,
  410. config=config,
  411. temp_root=temp / "run",
  412. )
  413. def test_archive_with_generated_members_keeps_only_sanitized_expansion(self) -> None:
  414. analyzer = load_analyzer(self)
  415. seven_zip = analyzer.find_7z()
  416. if seven_zip is None:
  417. self.skipTest("7-Zip is required")
  418. with tempfile.TemporaryDirectory() as tmp:
  419. temp = Path(tmp)
  420. def make_archive(name: str, entries: dict[str, bytes]) -> Path:
  421. source = temp / f"{name}-source"
  422. for relative, data in entries.items():
  423. write_file(source, relative, data)
  424. archive = temp / f"{name}.7z"
  425. result = subprocess.run(
  426. [str(seven_zip), "a", "-t7z", str(archive), ".\\*"],
  427. cwd=source,
  428. capture_output=True,
  429. text=True,
  430. check=False,
  431. )
  432. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  433. return archive
  434. safe_archive = make_archive(
  435. "safe",
  436. {
  437. "docs/readme.txt": b"safe\n",
  438. "td_project/demo_Runs/demo.bit": b"bitstream\n",
  439. },
  440. )
  441. sensitive_archive = make_archive(
  442. "sensitive",
  443. {
  444. "docs/readme.txt": b"safe\n",
  445. "private/Anlogic.lic": b"license\n",
  446. },
  447. )
  448. items = (
  449. analyzer.make_package_item(
  450. safe_archive,
  451. relative="external/hardware/safe.7z",
  452. category="hardware",
  453. source_id="hardware",
  454. ),
  455. analyzer.make_package_item(
  456. sensitive_archive,
  457. relative="external/hardware/sensitive.7z",
  458. category="hardware",
  459. source_id="hardware",
  460. ),
  461. )
  462. prepared = analyzer.prepare_unsupported_archives(
  463. items,
  464. temp_root=temp / "expanded",
  465. seven_zip=seven_zip,
  466. extra_exclusions=(),
  467. )
  468. paths = {item.candidate.relative for item in prepared.items}
  469. self.assertNotIn("external/hardware/safe.7z", paths)
  470. self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
  471. self.assertNotIn("external/hardware/safe.7z.expanded/td_project/demo_Runs/demo.bit", paths)
  472. self.assertNotIn("external/hardware/sensitive.7z", paths)
  473. self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
  474. self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
  475. self.assertTrue(
  476. any(
  477. item["path"] == "external/hardware/sensitive.7z"
  478. and item["rule"] == "unsupported_archive_contains_sensitive_content"
  479. for item in prepared.excluded
  480. )
  481. )
  482. self.assertTrue(
  483. any(
  484. item["path"] == "external/hardware/safe.7z"
  485. and item["rule"] == "archive_contains_excluded_members"
  486. for item in prepared.excluded
  487. )
  488. )
  489. def test_supported_archive_rejects_license_member_by_path(self) -> None:
  490. analyzer = load_analyzer(self)
  491. with tempfile.TemporaryDirectory() as tmp:
  492. temp = Path(tmp)
  493. archive_path = temp / "vendor.zip"
  494. with zipfile.ZipFile(archive_path, "w") as archive:
  495. archive.writestr("docs/readme.txt", b"safe\n")
  496. archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
  497. item = analyzer.make_package_item(
  498. archive_path,
  499. relative="external/vendor/vendor.zip",
  500. category="hardware",
  501. source_id="vendor",
  502. )
  503. with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
  504. analyzer._audit_package_items((item,))
  505. def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
  506. with tempfile.TemporaryDirectory() as tmp:
  507. temp = Path(tmp)
  508. external = temp / "board-viewer"
  509. board = write_file(external, "board.cad", b"board")
  510. cached = write_file(external, ".venv/cache.bin", b"cache")
  511. config_path = temp / "sources.json"
  512. config_path.write_text(
  513. json.dumps(
  514. {
  515. "schema": "cpld-agent-analysis-sources-v1",
  516. "max_zip_bytes": 380_000_000,
  517. "target_zip_bytes": 350_000_000,
  518. "external_sources": [
  519. {
  520. "id": "board-viewer",
  521. "category": "hardware",
  522. "kind": "directory",
  523. "path_candidates": [str(external)],
  524. "archive_policy": "inspect",
  525. }
  526. ],
  527. "extra_exclusions": [],
  528. }
  529. ),
  530. encoding="utf-8",
  531. )
  532. help_result = subprocess.run(
  533. [sys.executable, str(MODULE_PATH), "--help"],
  534. capture_output=True,
  535. text=True,
  536. check=False,
  537. )
  538. self.assertEqual(help_result.returncode, 0, help_result.stderr)
  539. for option in (
  540. "--audit-only",
  541. "--explain",
  542. "--config",
  543. "--output-dir",
  544. "--package-name",
  545. "--force-overwrite",
  546. ):
  547. self.assertIn(option, help_result.stdout)
  548. included_result = subprocess.run(
  549. [
  550. sys.executable,
  551. str(MODULE_PATH),
  552. "--config",
  553. str(config_path),
  554. "--explain",
  555. str(board),
  556. ],
  557. capture_output=True,
  558. text=True,
  559. check=False,
  560. )
  561. self.assertEqual(included_result.returncode, 0, included_result.stderr)
  562. included = json.loads(included_result.stdout)
  563. self.assertEqual(included["decision"], "include")
  564. self.assertEqual(included["source_id"], "board-viewer")
  565. excluded_result = subprocess.run(
  566. [
  567. sys.executable,
  568. str(MODULE_PATH),
  569. "--config",
  570. str(config_path),
  571. "--explain",
  572. str(cached),
  573. ],
  574. capture_output=True,
  575. text=True,
  576. check=False,
  577. )
  578. self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
  579. excluded = json.loads(excluded_result.stdout)
  580. self.assertEqual(excluded["decision"], "exclude")
  581. self.assertEqual(excluded["reason"], "virtual_environment")
  582. def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
  583. analyzer = load_analyzer(self)
  584. with tempfile.TemporaryDirectory() as tmp:
  585. temp = Path(tmp)
  586. source = temp / "source"
  587. first = write_file(source, "src/core.v", b"module core; endmodule\n")
  588. second = write_file(source, "reference/original/main.brd", b"board\n")
  589. collection = analyzer.AnalysisCollection(
  590. status="pass_with_warnings",
  591. items=(
  592. analyzer.make_package_item(
  593. first,
  594. relative="workspace-current/src/core.v",
  595. category="core",
  596. source_id="workspace-current",
  597. ),
  598. analyzer.make_package_item(
  599. second,
  600. relative="workspace-current/reference/original/main.brd",
  601. category="hardware",
  602. source_id="workspace-current",
  603. ),
  604. ),
  605. excluded=(),
  606. warnings=(
  607. {
  608. "code": "missing_external_source",
  609. "source_id": "td-docs",
  610. "message": "missing",
  611. },
  612. ),
  613. sources=({"id": "workspace-current", "status": "pass"},),
  614. git=(),
  615. )
  616. result = analyzer.create_analysis_package(
  617. collection=collection,
  618. output_root=temp / "output",
  619. package_name="single-fixture",
  620. max_zip_bytes=1_000_000,
  621. target_zip_bytes=800_000,
  622. force=False,
  623. )
  624. package_dir = Path(result["output_dir"])
  625. self.assertEqual(result["status"], "pass_with_warnings")
  626. self.assertEqual(len(result["volumes"]), 1)
  627. volume = package_dir / result["volumes"][0]["file"]
  628. self.assertLess(volume.stat().st_size, 1_000_000)
  629. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  630. self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
  631. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  632. with zipfile.ZipFile(volume) as archive:
  633. self.assertIsNone(archive.testzip())
  634. self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
  635. self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
  636. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  637. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  638. self.assertEqual(index["status"], "pass_with_warnings")
  639. self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
  640. def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
  641. analyzer = load_analyzer(self)
  642. with tempfile.TemporaryDirectory() as tmp:
  643. temp = Path(tmp)
  644. source = temp / "source"
  645. randomizer = random.Random(7)
  646. items = []
  647. for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
  648. path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
  649. items.append(
  650. analyzer.make_package_item(
  651. path,
  652. relative=f"workspace-current/data/file-{index}.bin",
  653. category=category,
  654. source_id="workspace-current",
  655. )
  656. )
  657. collection = analyzer.AnalysisCollection(
  658. status="pass",
  659. items=tuple(items),
  660. excluded=(),
  661. warnings=(),
  662. sources=({"id": "workspace-current", "status": "pass"},),
  663. git=(),
  664. )
  665. result = analyzer.create_analysis_package(
  666. collection=collection,
  667. output_root=temp / "output",
  668. package_name="multi-fixture",
  669. max_zip_bytes=30_000,
  670. target_zip_bytes=20_000,
  671. force=False,
  672. )
  673. package_dir = Path(result["output_dir"])
  674. self.assertGreaterEqual(len(result["volumes"]), 2)
  675. seen_entries: set[str] = set()
  676. for volume_info in result["volumes"]:
  677. volume = package_dir / volume_info["file"]
  678. self.assertLess(volume.stat().st_size, 30_000)
  679. with zipfile.ZipFile(volume) as archive:
  680. self.assertIsNone(archive.testzip())
  681. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  682. seen_entries.update(
  683. name
  684. for name in archive.namelist()
  685. if name.startswith("CPLD/workspace-current/data/") and not name.endswith("/")
  686. )
  687. self.assertEqual(len(seen_entries), 4)
  688. def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
  689. analyzer = load_analyzer(self)
  690. with tempfile.TemporaryDirectory() as tmp:
  691. temp = Path(tmp)
  692. source = temp / "source"
  693. payload = random.Random(19).randbytes(55_000)
  694. large = write_file(source, "data/large.db", payload)
  695. collection = analyzer.AnalysisCollection(
  696. status="pass",
  697. items=(
  698. analyzer.make_package_item(
  699. large,
  700. relative="workspace-current/data/large.db",
  701. category="evidence",
  702. source_id="workspace-current",
  703. ),
  704. ),
  705. excluded=(),
  706. warnings=(),
  707. sources=({"id": "workspace-current", "status": "pass"},),
  708. git=(),
  709. )
  710. result = analyzer.create_analysis_package(
  711. collection=collection,
  712. output_root=temp / "output",
  713. package_name="large-fixture",
  714. max_zip_bytes=30_000,
  715. target_zip_bytes=20_000,
  716. force=False,
  717. )
  718. package_dir = Path(result["output_dir"])
  719. for volume_info in result["volumes"]:
  720. self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
  721. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  722. self.assertEqual(len(index["large_files"]), 1)
  723. large_info = index["large_files"][0]
  724. self.assertEqual(large_info["path"], "workspace-current/data/large.db")
  725. self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
  726. self.assertGreaterEqual(len(large_info["chunks"]), 2)
  727. reassembler = package_dir / "reassemble_large_files.py"
  728. self.assertTrue(reassembler.is_file())
  729. reconstructed = temp / "reconstructed"
  730. completed = subprocess.run(
  731. [
  732. sys.executable,
  733. str(reassembler),
  734. "--package-dir",
  735. str(package_dir),
  736. "--output-dir",
  737. str(reconstructed),
  738. ],
  739. capture_output=True,
  740. text=True,
  741. check=False,
  742. )
  743. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  744. rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
  745. self.assertEqual(rebuilt.read_bytes(), payload)
  746. def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
  747. analyzer = load_analyzer(self)
  748. with tempfile.TemporaryDirectory() as tmp:
  749. temp = Path(tmp)
  750. source = temp / "source"
  751. item = write_file(source, "data/file.bin", b"replacement")
  752. output_root = temp / "output"
  753. final_dir = output_root / "atomic-fixture"
  754. final_dir.mkdir(parents=True)
  755. marker = write_file(final_dir, "old-marker.txt", b"old package")
  756. collection = analyzer.AnalysisCollection(
  757. status="pass",
  758. items=(
  759. analyzer.make_package_item(
  760. item,
  761. relative="workspace-current/data/file.bin",
  762. category="core",
  763. source_id="workspace-current",
  764. ),
  765. ),
  766. excluded=(),
  767. warnings=(),
  768. sources=({"id": "workspace-current", "status": "pass"},),
  769. git=(),
  770. )
  771. real_replace = analyzer.os.replace
  772. def fail_new_directory(source_path: object, target_path: object) -> None:
  773. source_name = Path(source_path).name
  774. if (
  775. source_name != "atomic-fixture"
  776. and not source_name.endswith(".backup")
  777. and Path(target_path).name == "atomic-fixture"
  778. ):
  779. raise OSError("injected publication failure")
  780. real_replace(source_path, target_path)
  781. with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
  782. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  783. analyzer.create_analysis_package(
  784. collection=collection,
  785. output_root=output_root,
  786. package_name="atomic-fixture",
  787. max_zip_bytes=1_000_000,
  788. target_zip_bytes=800_000,
  789. force=True,
  790. )
  791. self.assertEqual(marker.read_bytes(), b"old package")
  792. self.assertEqual(
  793. [path.name for path in output_root.iterdir()],
  794. ["atomic-fixture"],
  795. )
  796. def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
  797. analyzer = load_analyzer(self)
  798. with tempfile.TemporaryDirectory() as tmp:
  799. temp = Path(tmp)
  800. source = temp / "source"
  801. item = write_file(source, "data/file.bin", b"replacement")
  802. output_root = temp / "output"
  803. final_dir = output_root / "backup-failure-fixture"
  804. final_dir.mkdir(parents=True)
  805. marker = write_file(final_dir, "old-marker.txt", b"old package")
  806. collection = analyzer.AnalysisCollection(
  807. status="pass",
  808. items=(
  809. analyzer.make_package_item(
  810. item,
  811. relative="workspace-current/data/file.bin",
  812. category="core",
  813. source_id="workspace-current",
  814. ),
  815. ),
  816. excluded=(),
  817. warnings=(),
  818. sources=({"id": "workspace-current", "status": "pass"},),
  819. git=(),
  820. )
  821. real_replace = analyzer.os.replace
  822. def fail_backup_move(source_path: object, target_path: object) -> None:
  823. if Path(source_path).name == "backup-failure-fixture":
  824. raise OSError("injected backup move failure")
  825. real_replace(source_path, target_path)
  826. with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
  827. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  828. analyzer.create_analysis_package(
  829. collection=collection,
  830. output_root=output_root,
  831. package_name="backup-failure-fixture",
  832. max_zip_bytes=1_000_000,
  833. target_zip_bytes=800_000,
  834. force=True,
  835. )
  836. self.assertEqual(marker.read_bytes(), b"old package")
  837. self.assertEqual(
  838. [path.name for path in output_root.iterdir()],
  839. ["backup-failure-fixture"],
  840. )
  841. if __name__ == "__main__":
  842. unittest.main()