test_package_for_agent_analysis.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. external_ids = {item["id"] for item in config_payload["external_sources"]}
  104. self.assertIn("board-viewer-generated", external_ids)
  105. self.assertEqual(len(external_ids), len(config_payload["external_sources"]))
  106. for item in config_payload["external_sources"]:
  107. self.assertTrue(item["id"])
  108. self.assertIn(item["kind"], {"directory", "file", "archive"})
  109. self.assertTrue(item["path_candidates"])
  110. self.assertIn(
  111. {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
  112. config_payload["extra_exclusions"],
  113. )
  114. with tempfile.TemporaryDirectory() as tmp:
  115. temp = Path(tmp)
  116. source = temp / "source"
  117. item = write_file(source, "data/file.bin", b"fixture")
  118. collection = analyzer.AnalysisCollection(
  119. status="pass",
  120. items=(
  121. analyzer.make_package_item(
  122. item,
  123. relative="workspace-current/data/file.bin",
  124. category="core",
  125. source_id="workspace-current",
  126. ),
  127. ),
  128. excluded=(),
  129. warnings=(),
  130. sources=({"id": "workspace-current", "status": "pass"},),
  131. git=(),
  132. )
  133. result = analyzer.create_analysis_package(
  134. collection=collection,
  135. output_root=temp / "output",
  136. package_name="schema-fixture",
  137. max_zip_bytes=1_000_000,
  138. target_zip_bytes=800_000,
  139. force=False,
  140. )
  141. index = json.loads(
  142. (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
  143. )
  144. index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
  145. jsonschema.validate(index, index_schema)
  146. def test_analysis_scan_recursively_excludes_generated_files_and_keeps_analysis_evidence(self) -> None:
  147. analyzer = load_analyzer(self)
  148. with tempfile.TemporaryDirectory() as tmp:
  149. root = Path(tmp)
  150. write_file(root, "src/rtl/core.v")
  151. write_file(root, "src/main.brd", b"board")
  152. write_file(root, "reference/original/board/main.brd", b"board")
  153. write_file(root, "reference/original/schematics/main.pdf", b"schematic")
  154. write_file(root, "td/build/current/design.bit", b"bitstream")
  155. write_file(root, ".codegraph/codegraph.db", b"graph")
  156. write_file(root, "tmp/formal/result.vvp", b"simulation")
  157. write_file(root, "tmp/formal/result.vcd", b"formal trace")
  158. write_file(root, "unknown/evidence.bin", b"unknown")
  159. write_file(root, ".venv/Scripts/python.exe", b"venv")
  160. write_file(root, "pkg/nested/__pycache__/cache.pyc", b"cache")
  161. write_file(root, "pkg/nested/.pytest_cache/v/cache/nodeids", b"cache")
  162. write_file(root, "pkg/nested/.venv/Scripts/python.exe", b"venv")
  163. write_file(root, "pkg/nested/build/design.db", b"database")
  164. write_file(root, "pkg/nested/build/design.vvp", b"simulation")
  165. write_file(root, "pkg/not__pycache__/keep.bin", b"keep")
  166. write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
  167. write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
  168. candidates, excluded, _ = analyzer.scan_analysis_root(root)
  169. included = {item.relative for item in candidates}
  170. self.assertIn("src/rtl/core.v", included)
  171. self.assertIn("reference/original/schematics/main.pdf", included)
  172. self.assertIn("reference/original/board/main.brd", included)
  173. self.assertNotIn("src/main.brd", included)
  174. self.assertNotIn("td/build/current/design.bit", included)
  175. self.assertNotIn(".codegraph/codegraph.db", included)
  176. self.assertNotIn("tmp/formal/result.vvp", included)
  177. self.assertNotIn("tmp/formal/result.vcd", included)
  178. self.assertNotIn("unknown/evidence.bin", included)
  179. self.assertNotIn("pkg/not__pycache__/keep.bin", included)
  180. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  181. self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
  182. self.assertEqual(excluded_by_path["pkg/nested/__pycache__"], "python_bytecode_cache")
  183. self.assertEqual(excluded_by_path["pkg/nested/.pytest_cache"], "pytest_cache")
  184. self.assertEqual(excluded_by_path["pkg/nested/.venv"], "virtual_environment")
  185. self.assertEqual(excluded_by_path["pkg/nested/build"], "build_output")
  186. self.assertEqual(excluded_by_path["td/build"], "td_build_output")
  187. self.assertEqual(excluded_by_path[".codegraph"], "declared_external_reparse_alias")
  188. self.assertEqual(excluded_by_path["tmp"], "temporary_workspace_directory")
  189. self.assertEqual(excluded_by_path["src/main.brd"], "board_design_file")
  190. self.assertEqual(
  191. excluded_by_path["reference/original/local_archives/Anlogic.lic"],
  192. "credential_or_license_file",
  193. )
  194. self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
  195. def test_package_builds_without_7zip(self) -> None:
  196. analyzer = load_analyzer(self)
  197. with tempfile.TemporaryDirectory() as tmp:
  198. temp = Path(tmp)
  199. source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
  200. collection = analyzer.AnalysisCollection(
  201. status="pass",
  202. items=(
  203. analyzer.make_package_item(
  204. source,
  205. relative="workspace-current/src/core.v",
  206. category="core",
  207. source_id="workspace-current",
  208. ),
  209. ),
  210. excluded=(),
  211. warnings=(),
  212. sources=({"id": "workspace-current", "status": "pass"},),
  213. git=(),
  214. )
  215. with mock.patch.object(analyzer, "find_7z", return_value=None):
  216. result = analyzer.create_analysis_package(
  217. collection=collection,
  218. output_root=temp / "output",
  219. package_name="no-7z-fixture",
  220. max_zip_bytes=1_000_000,
  221. target_zip_bytes=800_000,
  222. force=False,
  223. )
  224. package_dir = Path(result["output_dir"])
  225. self.assertEqual(result["status"], "pass")
  226. self.assertEqual(len(result["volumes"]), 1)
  227. volume = package_dir / result["volumes"][0]["file"]
  228. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  229. self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
  230. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  231. with zipfile.ZipFile(volume) as archive:
  232. self.assertIsNone(archive.testzip())
  233. names = archive.namelist()
  234. self.assertIn("CPLD/workspace-current/src/core.v", names)
  235. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", names)
  236. self.assertEqual(
  237. archive.read("CPLD/workspace-current/src/core.v"),
  238. b"module core; endmodule\n",
  239. )
  240. def test_zip_archive_expands_without_7zip(self) -> None:
  241. analyzer = load_analyzer(self)
  242. with tempfile.TemporaryDirectory() as tmp:
  243. temp = Path(tmp)
  244. archive = temp / "vendor.zip"
  245. with zipfile.ZipFile(archive, "w") as zf:
  246. zf.writestr("docs/readme.txt", b"safe\n")
  247. zf.writestr("build/demo.bit", b"bitstream\n")
  248. item = analyzer.make_package_item(
  249. archive,
  250. relative="external/vendor/vendor.zip",
  251. category="hardware",
  252. source_id="vendor",
  253. )
  254. prepared = analyzer.prepare_unsupported_archives(
  255. (item,),
  256. temp_root=temp / "expanded",
  257. seven_zip=None,
  258. extra_exclusions=(),
  259. )
  260. paths = {it.candidate.relative for it in prepared.items}
  261. self.assertIn("external/vendor/vendor.zip.expanded/docs/readme.txt", paths)
  262. self.assertNotIn("external/vendor/vendor.zip.expanded/build/demo.bit", paths)
  263. self.assertTrue(
  264. any(
  265. entry["path"] == "external/vendor/vendor.zip"
  266. and entry["rule"] == "archive_contains_excluded_members"
  267. for entry in prepared.excluded
  268. )
  269. )
  270. def test_unsupported_reference_archive_warns_without_7zip(self) -> None:
  271. analyzer = load_analyzer(self)
  272. with tempfile.TemporaryDirectory() as tmp:
  273. temp = Path(tmp)
  274. archive = temp / "ref.7z"
  275. archive.write_bytes(b"dummy")
  276. item = analyzer.make_package_item(
  277. archive,
  278. relative="reference/original/ref.7z",
  279. category="core",
  280. source_id="ref",
  281. )
  282. prepared = analyzer.prepare_unsupported_archives(
  283. (item,),
  284. temp_root=temp / "expanded",
  285. seven_zip=None,
  286. extra_exclusions=(),
  287. )
  288. self.assertEqual(len(prepared.items), 1)
  289. self.assertEqual(prepared.items[0].candidate.relative, "reference/original/ref.7z")
  290. self.assertFalse(prepared.items[0].scan_archive)
  291. self.assertTrue(
  292. any(
  293. warning["code"] == "unsupported_archive_without_7zip"
  294. for warning in prepared.warnings
  295. )
  296. )
  297. def test_unsupported_core_archive_raises_without_7zip(self) -> None:
  298. analyzer = load_analyzer(self)
  299. with tempfile.TemporaryDirectory() as tmp:
  300. temp = Path(tmp)
  301. archive = temp / "core.7z"
  302. archive.write_bytes(b"dummy")
  303. item = analyzer.make_package_item(
  304. archive,
  305. relative="core/archive.7z",
  306. category="core",
  307. source_id="core",
  308. )
  309. with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
  310. analyzer.prepare_unsupported_archives(
  311. (item,),
  312. temp_root=temp / "expanded",
  313. seven_zip=None,
  314. extra_exclusions=(),
  315. )
  316. def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
  317. analyzer = load_analyzer(self)
  318. command = analyzer.build_7zip_create_command(
  319. analyzer.Path("package.zip"),
  320. analyzer.Path("staging"),
  321. )
  322. self.assertEqual(command[:4], ["a", "-tzip", "-mm=Deflate", "-mx=9"])
  323. self.assertNotIn("LZMA", " ".join(command).upper())
  324. def test_package_rejects_source_file_added_after_collection(self) -> None:
  325. git = shutil.which("git")
  326. if not git:
  327. self.skipTest("Git is required")
  328. analyzer = load_analyzer(self)
  329. with tempfile.TemporaryDirectory() as tmp:
  330. temp = Path(tmp)
  331. repo = temp / "repo"
  332. repo.mkdir()
  333. subprocess.run([git, "init", "-q", str(repo)], check=True)
  334. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  335. subprocess.run(
  336. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  337. check=True,
  338. )
  339. write_file(repo, "src/core.v", b"module core; endmodule\n")
  340. subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
  341. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  342. config = analyzer.HandoffConfig(
  343. max_zip_bytes=1_000_000,
  344. target_zip_bytes=800_000,
  345. external_sources=(),
  346. extra_exclusions=(),
  347. )
  348. collection = analyzer.collect_analysis_inputs(
  349. repo_root=repo,
  350. config=config,
  351. temp_root=temp / "run",
  352. )
  353. real_write_volume = analyzer._write_volume
  354. added = False
  355. def write_then_add(*args: object, **kwargs: object) -> dict[str, object]:
  356. nonlocal added
  357. result = real_write_volume(*args, **kwargs)
  358. if not added:
  359. write_file(repo, "new-after-scan.txt", b"late file\n")
  360. added = True
  361. return result
  362. with mock.patch.object(analyzer, "_write_volume", side_effect=write_then_add):
  363. with self.assertRaisesRegex(analyzer.PackagingError, "source tree changed"):
  364. analyzer.create_analysis_package(
  365. collection=collection,
  366. output_root=temp / "output",
  367. package_name="source-snapshot",
  368. max_zip_bytes=1_000_000,
  369. target_zip_bytes=800_000,
  370. force=False,
  371. )
  372. def test_missing_external_sources_are_warnings(self) -> None:
  373. analyzer = load_analyzer(self)
  374. with tempfile.TemporaryDirectory() as tmp:
  375. temp = Path(tmp)
  376. existing = temp / "existing"
  377. write_file(existing, "board.xml", b"board")
  378. source_type = analyzer.ExternalSource
  379. sources = (
  380. source_type(
  381. id="existing",
  382. category="hardware",
  383. kind="directory",
  384. path_candidates=(existing,),
  385. archive_policy="inspect",
  386. ),
  387. source_type(
  388. id="missing",
  389. category="td-docs",
  390. kind="directory",
  391. path_candidates=(temp / "missing",),
  392. archive_policy="inspect",
  393. ),
  394. )
  395. resolved, warnings = analyzer.resolve_external_sources(sources)
  396. self.assertEqual([item.id for item in resolved], ["existing"])
  397. self.assertEqual(len(warnings), 1)
  398. self.assertEqual(warnings[0]["code"], "missing_external_source")
  399. self.assertEqual(warnings[0]["source_id"], "missing")
  400. def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
  401. git = shutil.which("git")
  402. if not git:
  403. self.skipTest("Git is required")
  404. analyzer = load_analyzer(self)
  405. with tempfile.TemporaryDirectory() as tmp:
  406. temp = Path(tmp)
  407. repo = temp / "repo"
  408. review = temp / "review"
  409. for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
  410. root.mkdir()
  411. subprocess.run([git, "init", "-q", str(root)], check=True)
  412. subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
  413. subprocess.run(
  414. [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
  415. check=True,
  416. )
  417. write_file(root, tracked_name, tracked_name.encode("ascii"))
  418. subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
  419. subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
  420. write_file(repo, "td/build/current/design.bit", b"bitstream")
  421. write_file(review, "notes/untracked.txt", b"review notes")
  422. config = analyzer.HandoffConfig(
  423. max_zip_bytes=380_000_000,
  424. target_zip_bytes=350_000_000,
  425. external_sources=(
  426. analyzer.ExternalSource(
  427. id="review-worktree",
  428. category="core",
  429. kind="git_worktree",
  430. path_candidates=(review,),
  431. archive_policy="inspect",
  432. ),
  433. analyzer.ExternalSource(
  434. id="missing-docs",
  435. category="td-docs",
  436. kind="directory",
  437. path_candidates=(temp / "missing",),
  438. archive_policy="inspect",
  439. ),
  440. ),
  441. extra_exclusions=(),
  442. )
  443. collection = analyzer.collect_analysis_inputs(
  444. repo_root=repo,
  445. config=config,
  446. temp_root=temp / "run",
  447. )
  448. item_paths = {item.candidate.relative for item in collection.items}
  449. self.assertNotIn("workspace-current/td/build/current/design.bit", item_paths)
  450. self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
  451. self.assertIn("git-history/workspace-current.bundle", item_paths)
  452. self.assertIn("git-history/review-worktree.bundle", item_paths)
  453. self.assertEqual(collection.status, "pass_with_warnings")
  454. self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
  455. sources_by_id = {item["id"]: item for item in collection.sources}
  456. self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
  457. self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
  458. for item in collection.items:
  459. if item.candidate.relative.startswith("git-history/"):
  460. result = subprocess.run(
  461. [git, "bundle", "verify", str(item.candidate.absolute)],
  462. capture_output=True,
  463. text=True,
  464. check=False,
  465. )
  466. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  467. def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
  468. git = shutil.which("git")
  469. if not git:
  470. self.skipTest("Git is required")
  471. analyzer = load_analyzer(self)
  472. with tempfile.TemporaryDirectory() as tmp:
  473. temp = Path(tmp)
  474. repo = temp / "repo"
  475. repo.mkdir()
  476. subprocess.run([git, "init", "-q", str(repo)], check=True)
  477. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  478. subprocess.run(
  479. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  480. check=True,
  481. )
  482. write_file(repo, "tracked.txt", b"tracked")
  483. subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
  484. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  485. invalid = temp / "invalid-worktree"
  486. write_file(invalid, "notes.txt", b"not a Git repository")
  487. config = analyzer.HandoffConfig(
  488. max_zip_bytes=380_000_000,
  489. target_zip_bytes=350_000_000,
  490. external_sources=(
  491. analyzer.ExternalSource(
  492. id="invalid-worktree",
  493. category="core",
  494. kind="git_worktree",
  495. path_candidates=(invalid,),
  496. archive_policy="inspect",
  497. ),
  498. ),
  499. extra_exclusions=(),
  500. )
  501. with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
  502. analyzer.collect_analysis_inputs(
  503. repo_root=repo,
  504. config=config,
  505. temp_root=temp / "run",
  506. )
  507. def test_archive_with_generated_members_keeps_only_sanitized_expansion(self) -> None:
  508. analyzer = load_analyzer(self)
  509. seven_zip = analyzer.find_7z()
  510. if seven_zip is None:
  511. self.skipTest("7-Zip is required")
  512. with tempfile.TemporaryDirectory() as tmp:
  513. temp = Path(tmp)
  514. def make_archive(name: str, entries: dict[str, bytes]) -> Path:
  515. source = temp / f"{name}-source"
  516. for relative, data in entries.items():
  517. write_file(source, relative, data)
  518. archive = temp / f"{name}.7z"
  519. result = subprocess.run(
  520. [str(seven_zip), "a", "-t7z", str(archive), ".\\*"],
  521. cwd=source,
  522. capture_output=True,
  523. text=True,
  524. check=False,
  525. )
  526. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  527. return archive
  528. safe_archive = make_archive(
  529. "safe",
  530. {
  531. "docs/readme.txt": b"safe\n",
  532. "td_project/demo_Runs/demo.bit": b"bitstream\n",
  533. },
  534. )
  535. sensitive_archive = make_archive(
  536. "sensitive",
  537. {
  538. "docs/readme.txt": b"safe\n",
  539. "private/Anlogic.lic": b"license\n",
  540. },
  541. )
  542. items = (
  543. analyzer.make_package_item(
  544. safe_archive,
  545. relative="external/hardware/safe.7z",
  546. category="hardware",
  547. source_id="hardware",
  548. ),
  549. analyzer.make_package_item(
  550. sensitive_archive,
  551. relative="external/hardware/sensitive.7z",
  552. category="hardware",
  553. source_id="hardware",
  554. ),
  555. )
  556. prepared = analyzer.prepare_unsupported_archives(
  557. items,
  558. temp_root=temp / "expanded",
  559. seven_zip=seven_zip,
  560. extra_exclusions=(),
  561. )
  562. paths = {item.candidate.relative for item in prepared.items}
  563. self.assertNotIn("external/hardware/safe.7z", paths)
  564. self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
  565. self.assertNotIn("external/hardware/safe.7z.expanded/td_project/demo_Runs/demo.bit", paths)
  566. self.assertNotIn("external/hardware/sensitive.7z", paths)
  567. self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
  568. self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
  569. self.assertTrue(
  570. any(
  571. item["path"] == "external/hardware/sensitive.7z"
  572. and item["rule"] == "unsupported_archive_contains_sensitive_content"
  573. for item in prepared.excluded
  574. )
  575. )
  576. self.assertTrue(
  577. any(
  578. item["path"] == "external/hardware/safe.7z"
  579. and item["rule"] == "archive_contains_excluded_members"
  580. for item in prepared.excluded
  581. )
  582. )
  583. def test_supported_archive_rejects_license_member_by_path(self) -> None:
  584. analyzer = load_analyzer(self)
  585. with tempfile.TemporaryDirectory() as tmp:
  586. temp = Path(tmp)
  587. archive_path = temp / "vendor.zip"
  588. with zipfile.ZipFile(archive_path, "w") as archive:
  589. archive.writestr("docs/readme.txt", b"safe\n")
  590. archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
  591. item = analyzer.make_package_item(
  592. archive_path,
  593. relative="external/vendor/vendor.zip",
  594. category="hardware",
  595. source_id="vendor",
  596. )
  597. with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
  598. analyzer._audit_package_items((item,))
  599. def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
  600. with tempfile.TemporaryDirectory() as tmp:
  601. temp = Path(tmp)
  602. external = temp / "board-viewer"
  603. board = write_file(external, "board.cad", b"board")
  604. cached = write_file(external, ".venv/cache.bin", b"cache")
  605. config_path = temp / "sources.json"
  606. config_path.write_text(
  607. json.dumps(
  608. {
  609. "schema": "cpld-agent-analysis-sources-v1",
  610. "max_zip_bytes": 380_000_000,
  611. "target_zip_bytes": 350_000_000,
  612. "external_sources": [
  613. {
  614. "id": "board-viewer",
  615. "category": "hardware",
  616. "kind": "directory",
  617. "path_candidates": [str(external)],
  618. "archive_policy": "inspect",
  619. }
  620. ],
  621. "extra_exclusions": [],
  622. }
  623. ),
  624. encoding="utf-8",
  625. )
  626. help_result = subprocess.run(
  627. [sys.executable, str(MODULE_PATH), "--help"],
  628. capture_output=True,
  629. text=True,
  630. check=False,
  631. )
  632. self.assertEqual(help_result.returncode, 0, help_result.stderr)
  633. for option in (
  634. "--audit-only",
  635. "--explain",
  636. "--config",
  637. "--output-dir",
  638. "--package-name",
  639. "--force-overwrite",
  640. ):
  641. self.assertIn(option, help_result.stdout)
  642. included_result = subprocess.run(
  643. [
  644. sys.executable,
  645. str(MODULE_PATH),
  646. "--config",
  647. str(config_path),
  648. "--explain",
  649. str(board),
  650. ],
  651. capture_output=True,
  652. text=True,
  653. check=False,
  654. )
  655. self.assertEqual(included_result.returncode, 0, included_result.stderr)
  656. included = json.loads(included_result.stdout)
  657. self.assertEqual(included["decision"], "include")
  658. self.assertEqual(included["source_id"], "board-viewer")
  659. excluded_result = subprocess.run(
  660. [
  661. sys.executable,
  662. str(MODULE_PATH),
  663. "--config",
  664. str(config_path),
  665. "--explain",
  666. str(cached),
  667. ],
  668. capture_output=True,
  669. text=True,
  670. check=False,
  671. )
  672. self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
  673. excluded = json.loads(excluded_result.stdout)
  674. self.assertEqual(excluded["decision"], "exclude")
  675. self.assertEqual(excluded["reason"], "virtual_environment")
  676. def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
  677. analyzer = load_analyzer(self)
  678. with tempfile.TemporaryDirectory() as tmp:
  679. temp = Path(tmp)
  680. source = temp / "source"
  681. first = write_file(source, "src/core.v", b"module core; endmodule\n")
  682. second = write_file(source, "reference/original/main.brd", b"board\n")
  683. collection = analyzer.AnalysisCollection(
  684. status="pass_with_warnings",
  685. items=(
  686. analyzer.make_package_item(
  687. first,
  688. relative="workspace-current/src/core.v",
  689. category="core",
  690. source_id="workspace-current",
  691. ),
  692. analyzer.make_package_item(
  693. second,
  694. relative="workspace-current/reference/original/main.brd",
  695. category="hardware",
  696. source_id="workspace-current",
  697. ),
  698. ),
  699. excluded=(),
  700. warnings=(
  701. {
  702. "code": "missing_external_source",
  703. "source_id": "td-docs",
  704. "message": "missing",
  705. },
  706. ),
  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="single-fixture",
  714. max_zip_bytes=1_000_000,
  715. target_zip_bytes=800_000,
  716. force=False,
  717. )
  718. package_dir = Path(result["output_dir"])
  719. self.assertEqual(result["status"], "pass_with_warnings")
  720. self.assertEqual(len(result["volumes"]), 1)
  721. volume = package_dir / result["volumes"][0]["file"]
  722. self.assertLess(volume.stat().st_size, 1_000_000)
  723. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  724. self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
  725. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  726. with zipfile.ZipFile(volume) as archive:
  727. self.assertIsNone(archive.testzip())
  728. self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
  729. self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
  730. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  731. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  732. self.assertEqual(index["status"], "pass_with_warnings")
  733. self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
  734. def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
  735. analyzer = load_analyzer(self)
  736. with tempfile.TemporaryDirectory() as tmp:
  737. temp = Path(tmp)
  738. source = temp / "source"
  739. randomizer = random.Random(7)
  740. items = []
  741. for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
  742. path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
  743. items.append(
  744. analyzer.make_package_item(
  745. path,
  746. relative=f"workspace-current/data/file-{index}.bin",
  747. category=category,
  748. source_id="workspace-current",
  749. )
  750. )
  751. collection = analyzer.AnalysisCollection(
  752. status="pass",
  753. items=tuple(items),
  754. excluded=(),
  755. warnings=(),
  756. sources=({"id": "workspace-current", "status": "pass"},),
  757. git=(),
  758. )
  759. result = analyzer.create_analysis_package(
  760. collection=collection,
  761. output_root=temp / "output",
  762. package_name="multi-fixture",
  763. max_zip_bytes=30_000,
  764. target_zip_bytes=20_000,
  765. force=False,
  766. )
  767. package_dir = Path(result["output_dir"])
  768. self.assertGreaterEqual(len(result["volumes"]), 2)
  769. seen_entries: set[str] = set()
  770. for volume_info in result["volumes"]:
  771. volume = package_dir / volume_info["file"]
  772. self.assertLess(volume.stat().st_size, 30_000)
  773. with zipfile.ZipFile(volume) as archive:
  774. self.assertIsNone(archive.testzip())
  775. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  776. seen_entries.update(
  777. name
  778. for name in archive.namelist()
  779. if name.startswith("CPLD/workspace-current/data/") and not name.endswith("/")
  780. )
  781. self.assertEqual(len(seen_entries), 4)
  782. def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
  783. analyzer = load_analyzer(self)
  784. with tempfile.TemporaryDirectory() as tmp:
  785. temp = Path(tmp)
  786. source = temp / "source"
  787. payload = random.Random(19).randbytes(55_000)
  788. large = write_file(source, "data/large.db", payload)
  789. collection = analyzer.AnalysisCollection(
  790. status="pass",
  791. items=(
  792. analyzer.make_package_item(
  793. large,
  794. relative="workspace-current/data/large.db",
  795. category="evidence",
  796. source_id="workspace-current",
  797. ),
  798. ),
  799. excluded=(),
  800. warnings=(),
  801. sources=({"id": "workspace-current", "status": "pass"},),
  802. git=(),
  803. )
  804. result = analyzer.create_analysis_package(
  805. collection=collection,
  806. output_root=temp / "output",
  807. package_name="large-fixture",
  808. max_zip_bytes=30_000,
  809. target_zip_bytes=20_000,
  810. force=False,
  811. )
  812. package_dir = Path(result["output_dir"])
  813. for volume_info in result["volumes"]:
  814. self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
  815. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  816. self.assertEqual(len(index["large_files"]), 1)
  817. large_info = index["large_files"][0]
  818. self.assertEqual(large_info["path"], "workspace-current/data/large.db")
  819. self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
  820. self.assertGreaterEqual(len(large_info["chunks"]), 2)
  821. reassembler = package_dir / "reassemble_large_files.py"
  822. self.assertTrue(reassembler.is_file())
  823. reconstructed = temp / "reconstructed"
  824. completed = subprocess.run(
  825. [
  826. sys.executable,
  827. str(reassembler),
  828. "--package-dir",
  829. str(package_dir),
  830. "--output-dir",
  831. str(reconstructed),
  832. ],
  833. capture_output=True,
  834. text=True,
  835. check=False,
  836. )
  837. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  838. rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
  839. self.assertEqual(rebuilt.read_bytes(), payload)
  840. def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
  841. analyzer = load_analyzer(self)
  842. with tempfile.TemporaryDirectory() as tmp:
  843. temp = Path(tmp)
  844. source = temp / "source"
  845. item = write_file(source, "data/file.bin", b"replacement")
  846. output_root = temp / "output"
  847. final_dir = output_root / "atomic-fixture"
  848. final_dir.mkdir(parents=True)
  849. marker = write_file(final_dir, "old-marker.txt", b"old package")
  850. collection = analyzer.AnalysisCollection(
  851. status="pass",
  852. items=(
  853. analyzer.make_package_item(
  854. item,
  855. relative="workspace-current/data/file.bin",
  856. category="core",
  857. source_id="workspace-current",
  858. ),
  859. ),
  860. excluded=(),
  861. warnings=(),
  862. sources=({"id": "workspace-current", "status": "pass"},),
  863. git=(),
  864. )
  865. real_replace = analyzer.os.replace
  866. def fail_new_directory(source_path: object, target_path: object) -> None:
  867. source_name = Path(source_path).name
  868. if (
  869. source_name != "atomic-fixture"
  870. and not source_name.endswith(".backup")
  871. and Path(target_path).name == "atomic-fixture"
  872. ):
  873. raise OSError("injected publication failure")
  874. real_replace(source_path, target_path)
  875. with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
  876. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  877. analyzer.create_analysis_package(
  878. collection=collection,
  879. output_root=output_root,
  880. package_name="atomic-fixture",
  881. max_zip_bytes=1_000_000,
  882. target_zip_bytes=800_000,
  883. force=True,
  884. )
  885. self.assertEqual(marker.read_bytes(), b"old package")
  886. self.assertEqual(
  887. [path.name for path in output_root.iterdir()],
  888. ["atomic-fixture"],
  889. )
  890. def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
  891. analyzer = load_analyzer(self)
  892. with tempfile.TemporaryDirectory() as tmp:
  893. temp = Path(tmp)
  894. source = temp / "source"
  895. item = write_file(source, "data/file.bin", b"replacement")
  896. output_root = temp / "output"
  897. final_dir = output_root / "backup-failure-fixture"
  898. final_dir.mkdir(parents=True)
  899. marker = write_file(final_dir, "old-marker.txt", b"old package")
  900. collection = analyzer.AnalysisCollection(
  901. status="pass",
  902. items=(
  903. analyzer.make_package_item(
  904. item,
  905. relative="workspace-current/data/file.bin",
  906. category="core",
  907. source_id="workspace-current",
  908. ),
  909. ),
  910. excluded=(),
  911. warnings=(),
  912. sources=({"id": "workspace-current", "status": "pass"},),
  913. git=(),
  914. )
  915. real_replace = analyzer.os.replace
  916. def fail_backup_move(source_path: object, target_path: object) -> None:
  917. if Path(source_path).name == "backup-failure-fixture":
  918. raise OSError("injected backup move failure")
  919. real_replace(source_path, target_path)
  920. with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
  921. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  922. analyzer.create_analysis_package(
  923. collection=collection,
  924. output_root=output_root,
  925. package_name="backup-failure-fixture",
  926. max_zip_bytes=1_000_000,
  927. target_zip_bytes=800_000,
  928. force=True,
  929. )
  930. self.assertEqual(marker.read_bytes(), b"old package")
  931. self.assertEqual(
  932. [path.name for path in output_root.iterdir()],
  933. ["backup-failure-fixture"],
  934. )
  935. def test_package_layout_writes_exclusions_tar_zst_and_checksums(self) -> None:
  936. analyzer = load_analyzer(self)
  937. with tempfile.TemporaryDirectory() as tmp:
  938. temp = Path(tmp)
  939. source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
  940. collection = analyzer.AnalysisCollection(
  941. status="pass",
  942. items=(
  943. analyzer.make_package_item(
  944. source,
  945. relative="workspace-current/src/core.v",
  946. category="core",
  947. source_id="workspace-current",
  948. ),
  949. ),
  950. excluded=(
  951. {"path": ".venv", "rule": "virtual_environment"},
  952. {"path": "tmp", "rule": "temporary_workspace_directory"},
  953. ),
  954. warnings=(),
  955. sources=({"id": "workspace-current", "status": "pass"},),
  956. git=(),
  957. )
  958. result = analyzer.create_analysis_package(
  959. collection=collection,
  960. output_root=temp / "output",
  961. package_name="layout-fixture",
  962. max_zip_bytes=1_000_000,
  963. target_zip_bytes=800_000,
  964. force=False,
  965. )
  966. package_dir = Path(result["output_dir"])
  967. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  968. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  969. self.assertTrue((package_dir / "EXCLUSIONS.txt").is_file())
  970. self.assertTrue((package_dir / "layout-fixture.tar.zst").is_file())
  971. exclusions = (package_dir / "EXCLUSIONS.txt").read_text(encoding="utf-8")
  972. self.assertIn(".venv\tvirtual_environment", exclusions)
  973. sums = (package_dir / "SHA256SUMS.txt").read_text(encoding="ascii")
  974. self.assertIn("layout-fixture.tar.zst", sums)
  975. self.assertIn("EXCLUSIONS.txt", sums)
  976. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  977. self.assertEqual(index["formats"]["tar_zst"], "layout-fixture.tar.zst")
  978. replay = analyzer.replay_analysis_package(
  979. package_dir,
  980. extract_root=temp / "replay",
  981. )
  982. self.assertEqual(replay["status"], "pass")
  983. self.assertTrue(replay["exclusions_present"])
  984. self.assertEqual(replay["tar_zst"], "layout-fixture.tar.zst")
  985. def test_chinese_and_spaces_path_round_trip(self) -> None:
  986. analyzer = load_analyzer(self)
  987. with tempfile.TemporaryDirectory() as tmp:
  988. temp = Path(tmp)
  989. relative = "workspace-current/docs/中文目录/file with spaces.txt"
  990. source = write_file(
  991. temp / "source",
  992. "docs/中文目录/file with spaces.txt",
  993. "中文内容与 spaces\n".encode("utf-8"),
  994. )
  995. collection = analyzer.AnalysisCollection(
  996. status="pass",
  997. items=(
  998. analyzer.make_package_item(
  999. source,
  1000. relative=relative,
  1001. category="core",
  1002. source_id="workspace-current",
  1003. ),
  1004. ),
  1005. excluded=(),
  1006. warnings=(),
  1007. sources=({"id": "workspace-current", "status": "pass"},),
  1008. git=(),
  1009. )
  1010. result = analyzer.create_analysis_package(
  1011. collection=collection,
  1012. output_root=temp / "output",
  1013. package_name="unicode-fixture",
  1014. max_zip_bytes=1_000_000,
  1015. target_zip_bytes=800_000,
  1016. force=False,
  1017. )
  1018. package_dir = Path(result["output_dir"])
  1019. volume = package_dir / result["volumes"][0]["file"]
  1020. with zipfile.ZipFile(volume) as archive:
  1021. names = archive.namelist()
  1022. self.assertIn(f"CPLD/{relative}", names)
  1023. info = archive.getinfo(f"CPLD/{relative}")
  1024. self.assertTrue(info.flag_bits & 0x800)
  1025. self.assertEqual(
  1026. archive.read(f"CPLD/{relative}"),
  1027. "中文内容与 spaces\n".encode("utf-8"),
  1028. )
  1029. replay = analyzer.replay_analysis_package(
  1030. package_dir,
  1031. extract_root=temp / "replay-unicode",
  1032. )
  1033. self.assertEqual(replay["status"], "pass")
  1034. self.assertEqual(replay["checked_files"], 1)
  1035. def test_full_profile_requires_git_bundle(self) -> None:
  1036. analyzer = load_analyzer(self)
  1037. with tempfile.TemporaryDirectory() as tmp:
  1038. temp = Path(tmp)
  1039. repo = temp / "repo"
  1040. repo.mkdir()
  1041. git = shutil.which("git")
  1042. if not git:
  1043. self.skipTest("Git is required")
  1044. subprocess.run([git, "init", "-q", str(repo)], check=True)
  1045. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  1046. subprocess.run(
  1047. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  1048. check=True,
  1049. )
  1050. write_file(repo, "src/core.v", b"module core; endmodule\n")
  1051. subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
  1052. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  1053. config = analyzer.HandoffConfig(
  1054. max_zip_bytes=1_000_000,
  1055. target_zip_bytes=800_000,
  1056. external_sources=(),
  1057. extra_exclusions=(),
  1058. )
  1059. with self.assertRaisesRegex(analyzer.PackagingError, "git bundle"):
  1060. analyzer.collect_analysis_inputs(
  1061. repo_root=repo,
  1062. config=config,
  1063. temp_root=temp / "run",
  1064. include_git_bundle=False,
  1065. profile="full",
  1066. )
  1067. class ReviewCompactProfileSmokeTests(unittest.TestCase):
  1068. maxDiff = None
  1069. def _init_repo(self, repo: Path) -> str:
  1070. git = shutil.which("git")
  1071. if not git:
  1072. self.skipTest("Git is required")
  1073. repo.mkdir(parents=True, exist_ok=True)
  1074. subprocess.run([git, "init", "-q", str(repo)], check=True)
  1075. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  1076. subprocess.run(
  1077. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  1078. check=True,
  1079. )
  1080. write_file(repo, "src/core.v", b"module core; endmodule\n")
  1081. write_file(
  1082. repo,
  1083. "receipts/verification-matrix-final.json",
  1084. b'{"status":"pass","schema":"fixture"}\n',
  1085. )
  1086. write_file(repo, "reference/original/board/main.brd", b"BOARD")
  1087. write_file(repo, "reference/original/schematics/main.pdf", b"%PDF")
  1088. write_file(repo, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
  1089. write_file(repo, ".run_id_stale", b"stale\n")
  1090. write_file(repo, "node_modules/pkg/index.js", b"nope\n")
  1091. subprocess.run(
  1092. [git, "-C", str(repo), "add", "src/core.v", "receipts/verification-matrix-final.json"],
  1093. check=True,
  1094. )
  1095. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  1096. return git
  1097. def test_review_compact_excludes_heavy_originals_keeps_fixtures(self) -> None:
  1098. analyzer = load_analyzer(self)
  1099. with tempfile.TemporaryDirectory() as tmp:
  1100. root = Path(tmp)
  1101. write_file(root, "src/core.v", b"module core; endmodule\n")
  1102. write_file(root, "reference/original/board/main.brd", b"BOARD")
  1103. write_file(root, "reference/original/schematics/main.pdf", b"%PDF")
  1104. write_file(root, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
  1105. write_file(root, ".run_id_stale", b"stale\n")
  1106. candidates, excluded, _ = analyzer.scan_analysis_root(root, profile="review-compact")
  1107. included = {item.relative for item in candidates}
  1108. self.assertIn("src/core.v", included)
  1109. self.assertIn("tests/board_viewer/fixtures/tiny.dsn", included)
  1110. self.assertNotIn("reference/original/board/main.brd", included)
  1111. self.assertNotIn("reference/original/schematics/main.pdf", included)
  1112. self.assertNotIn(".run_id_stale", included)
  1113. rules = {item["path"]: item["rule"] for item in excluded}
  1114. self.assertEqual(rules.get("reference/original/board"), "reference_original_board")
  1115. def test_review_compact_unified_layout_and_no_git_bundle(self) -> None:
  1116. analyzer = load_analyzer(self)
  1117. with tempfile.TemporaryDirectory() as tmp:
  1118. temp = Path(tmp)
  1119. repo = temp / "repo"
  1120. self._init_repo(repo)
  1121. generated = temp / "generated"
  1122. write_file(generated, "board-data.json", b'{"ok":true}\n')
  1123. write_file(generated, "build-info.json", b'{"ok":true}\n')
  1124. write_file(generated, "import-report.json", b'{"ok":true}\n')
  1125. write_file(generated, "board-copper.svg", b"<svg/>\n")
  1126. write_file(generated, "board-silkscreen.svg", b"<svg/>\n")
  1127. write_file(generated, "board-mask-edge.svg", b"<svg/>\n")
  1128. config = analyzer.HandoffConfig(
  1129. max_zip_bytes=5_000_000,
  1130. target_zip_bytes=4_000_000,
  1131. external_sources=(
  1132. analyzer.ExternalSource(
  1133. id="board-viewer-generated",
  1134. category="hardware",
  1135. kind="directory",
  1136. path_candidates=(generated,),
  1137. archive_policy="copy",
  1138. ),
  1139. ),
  1140. extra_exclusions=(),
  1141. )
  1142. collection = analyzer.collect_analysis_inputs(
  1143. repo_root=repo,
  1144. config=config,
  1145. temp_root=temp / "run",
  1146. include_git_bundle=True, # must be forced off for review-compact
  1147. profile="review-compact",
  1148. package_name="smoke-review-compact",
  1149. )
  1150. paths = {item.candidate.relative for item in collection.items}
  1151. self.assertTrue(any(path.startswith("source/") for path in paths))
  1152. self.assertIn("source/src/core.v", paths)
  1153. self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
  1154. self.assertIn("evidence/board-viewer/board-data.json", paths)
  1155. self.assertTrue(any(path.startswith("meta/git/") for path in paths))
  1156. self.assertFalse(any(path.endswith(".bundle") for path in paths))
  1157. self.assertFalse(any("reference/original/board" in path for path in paths))
  1158. result = analyzer.create_analysis_package(
  1159. collection=collection,
  1160. output_root=temp / "output",
  1161. package_name="smoke-review-compact",
  1162. max_zip_bytes=5_000_000,
  1163. target_zip_bytes=4_000_000,
  1164. force=False,
  1165. profile="review-compact",
  1166. )
  1167. package_dir = Path(result["output_dir"])
  1168. self.assertEqual(result["delivery_policy"], "review-compact")
  1169. self.assertTrue((package_dir / "PACKAGE-PURPOSE.txt").is_file())
  1170. self.assertTrue((package_dir / "size-budget.json").is_file())
  1171. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  1172. self.assertEqual(index["profile"], "review-compact")
  1173. self.assertIn("member_count", index)
  1174. self.assertIn("self_reference_control_files", index["member_count"])
  1175. self.assertIn("size_budget", index)
  1176. volume = package_dir / result["volumes"][0]["file"]
  1177. with zipfile.ZipFile(volume) as archive:
  1178. names = set(archive.namelist())
  1179. self.assertIn("CPLD/source/src/core.v", names)
  1180. self.assertIn("CPLD/evidence/matrix/verification-matrix-final.json", names)
  1181. self.assertIn("CPLD/meta/git/log-20.txt", names)
  1182. self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
  1183. self.assertFalse(any(name.endswith(".bundle") for name in names))
  1184. index_schema = json.loads(
  1185. (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
  1186. encoding="utf-8"
  1187. )
  1188. )
  1189. jsonschema.validate(index, index_schema)
  1190. def test_review_debug_and_archive_local_profiles_are_registered(self) -> None:
  1191. analyzer = load_analyzer(self)
  1192. self.assertIn("review-debug", analyzer.handoff.HANDOFF_PROFILES)
  1193. self.assertIn("archive-local", analyzer.handoff.HANDOFF_PROFILES)
  1194. self.assertEqual(analyzer.handoff.DEFAULT_HANDOFF_PROFILE, "review-compact")
  1195. self.assertTrue(analyzer.handoff.uses_unified_layout("review-debug"))
  1196. self.assertEqual(
  1197. analyzer.handoff.delivery_policy_for_profile("archive-local"),
  1198. "archive-local",
  1199. )
  1200. if __name__ == "__main__":
  1201. unittest.main()