test_package_for_agent_analysis.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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. # Verify inside a real Git repo cwd — never mis-blame tool
  461. # behavior when cwd is a non-repository (detached extract).
  462. result = subprocess.run(
  463. [git, "bundle", "verify", str(item.candidate.absolute)],
  464. cwd=str(repo),
  465. capture_output=True,
  466. text=True,
  467. check=False,
  468. )
  469. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  470. def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
  471. git = shutil.which("git")
  472. if not git:
  473. self.skipTest("Git is required")
  474. analyzer = load_analyzer(self)
  475. with tempfile.TemporaryDirectory() as tmp:
  476. temp = Path(tmp)
  477. repo = temp / "repo"
  478. repo.mkdir()
  479. subprocess.run([git, "init", "-q", str(repo)], check=True)
  480. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  481. subprocess.run(
  482. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  483. check=True,
  484. )
  485. write_file(repo, "tracked.txt", b"tracked")
  486. subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
  487. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  488. invalid = temp / "invalid-worktree"
  489. write_file(invalid, "notes.txt", b"not a Git repository")
  490. config = analyzer.HandoffConfig(
  491. max_zip_bytes=380_000_000,
  492. target_zip_bytes=350_000_000,
  493. external_sources=(
  494. analyzer.ExternalSource(
  495. id="invalid-worktree",
  496. category="core",
  497. kind="git_worktree",
  498. path_candidates=(invalid,),
  499. archive_policy="inspect",
  500. ),
  501. ),
  502. extra_exclusions=(),
  503. )
  504. with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
  505. analyzer.collect_analysis_inputs(
  506. repo_root=repo,
  507. config=config,
  508. temp_root=temp / "run",
  509. )
  510. def test_archive_with_generated_members_keeps_only_sanitized_expansion(self) -> None:
  511. analyzer = load_analyzer(self)
  512. seven_zip = analyzer.find_7z()
  513. if seven_zip is None:
  514. self.skipTest("7-Zip is required")
  515. with tempfile.TemporaryDirectory() as tmp:
  516. temp = Path(tmp)
  517. def make_archive(name: str, entries: dict[str, bytes]) -> Path:
  518. source = temp / f"{name}-source"
  519. for relative, data in entries.items():
  520. write_file(source, relative, data)
  521. archive = temp / f"{name}.7z"
  522. result = subprocess.run(
  523. [str(seven_zip), "a", "-t7z", "-r", str(archive), "*"],
  524. cwd=source,
  525. capture_output=True,
  526. text=True,
  527. check=False,
  528. )
  529. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  530. return archive
  531. safe_archive = make_archive(
  532. "safe",
  533. {
  534. "docs/readme.txt": b"safe\n",
  535. "td_project/demo_Runs/demo.bit": b"bitstream\n",
  536. },
  537. )
  538. sensitive_archive = make_archive(
  539. "sensitive",
  540. {
  541. "docs/readme.txt": b"safe\n",
  542. "private/Anlogic.lic": b"license\n",
  543. },
  544. )
  545. items = (
  546. analyzer.make_package_item(
  547. safe_archive,
  548. relative="external/hardware/safe.7z",
  549. category="hardware",
  550. source_id="hardware",
  551. ),
  552. analyzer.make_package_item(
  553. sensitive_archive,
  554. relative="external/hardware/sensitive.7z",
  555. category="hardware",
  556. source_id="hardware",
  557. ),
  558. )
  559. prepared = analyzer.prepare_unsupported_archives(
  560. items,
  561. temp_root=temp / "expanded",
  562. seven_zip=seven_zip,
  563. extra_exclusions=(),
  564. )
  565. paths = {item.candidate.relative for item in prepared.items}
  566. self.assertNotIn("external/hardware/safe.7z", paths)
  567. self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
  568. self.assertNotIn("external/hardware/safe.7z.expanded/td_project/demo_Runs/demo.bit", paths)
  569. self.assertNotIn("external/hardware/sensitive.7z", paths)
  570. self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
  571. self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
  572. self.assertTrue(
  573. any(
  574. item["path"] == "external/hardware/sensitive.7z"
  575. and item["rule"] == "unsupported_archive_contains_sensitive_content"
  576. for item in prepared.excluded
  577. )
  578. )
  579. self.assertTrue(
  580. any(
  581. item["path"] == "external/hardware/safe.7z"
  582. and item["rule"] == "archive_contains_excluded_members"
  583. for item in prepared.excluded
  584. )
  585. )
  586. def test_supported_archive_rejects_license_member_by_path(self) -> None:
  587. analyzer = load_analyzer(self)
  588. with tempfile.TemporaryDirectory() as tmp:
  589. temp = Path(tmp)
  590. archive_path = temp / "vendor.zip"
  591. with zipfile.ZipFile(archive_path, "w") as archive:
  592. archive.writestr("docs/readme.txt", b"safe\n")
  593. archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
  594. item = analyzer.make_package_item(
  595. archive_path,
  596. relative="external/vendor/vendor.zip",
  597. category="hardware",
  598. source_id="vendor",
  599. )
  600. with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
  601. analyzer._audit_package_items((item,))
  602. def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
  603. with tempfile.TemporaryDirectory() as tmp:
  604. temp = Path(tmp)
  605. external = temp / "board-viewer"
  606. board = write_file(external, "board.cad", b"board")
  607. cached = write_file(external, ".venv/cache.bin", b"cache")
  608. config_path = temp / "sources.json"
  609. config_path.write_text(
  610. json.dumps(
  611. {
  612. "schema": "cpld-agent-analysis-sources-v1",
  613. "max_zip_bytes": 380_000_000,
  614. "target_zip_bytes": 350_000_000,
  615. "external_sources": [
  616. {
  617. "id": "board-viewer",
  618. "category": "hardware",
  619. "kind": "directory",
  620. "path_candidates": [str(external)],
  621. "archive_policy": "inspect",
  622. }
  623. ],
  624. "extra_exclusions": [],
  625. }
  626. ),
  627. encoding="utf-8",
  628. )
  629. help_result = subprocess.run(
  630. [sys.executable, str(MODULE_PATH), "--help"],
  631. capture_output=True,
  632. text=True,
  633. check=False,
  634. )
  635. self.assertEqual(help_result.returncode, 0, help_result.stderr)
  636. for option in (
  637. "--audit-only",
  638. "--explain",
  639. "--config",
  640. "--output-dir",
  641. "--package-name",
  642. "--force-overwrite",
  643. ):
  644. self.assertIn(option, help_result.stdout)
  645. included_result = subprocess.run(
  646. [
  647. sys.executable,
  648. str(MODULE_PATH),
  649. "--config",
  650. str(config_path),
  651. "--explain",
  652. str(board),
  653. ],
  654. capture_output=True,
  655. text=True,
  656. check=False,
  657. )
  658. self.assertEqual(included_result.returncode, 0, included_result.stderr)
  659. included = json.loads(included_result.stdout)
  660. self.assertEqual(included["decision"], "include")
  661. self.assertEqual(included["source_id"], "board-viewer")
  662. excluded_result = subprocess.run(
  663. [
  664. sys.executable,
  665. str(MODULE_PATH),
  666. "--config",
  667. str(config_path),
  668. "--explain",
  669. str(cached),
  670. ],
  671. capture_output=True,
  672. text=True,
  673. check=False,
  674. )
  675. self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
  676. excluded = json.loads(excluded_result.stdout)
  677. self.assertEqual(excluded["decision"], "exclude")
  678. self.assertEqual(excluded["reason"], "virtual_environment")
  679. def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
  680. analyzer = load_analyzer(self)
  681. with tempfile.TemporaryDirectory() as tmp:
  682. temp = Path(tmp)
  683. source = temp / "source"
  684. first = write_file(source, "src/core.v", b"module core; endmodule\n")
  685. second = write_file(source, "reference/original/main.brd", b"board\n")
  686. collection = analyzer.AnalysisCollection(
  687. status="pass_with_warnings",
  688. items=(
  689. analyzer.make_package_item(
  690. first,
  691. relative="workspace-current/src/core.v",
  692. category="core",
  693. source_id="workspace-current",
  694. ),
  695. analyzer.make_package_item(
  696. second,
  697. relative="workspace-current/reference/original/main.brd",
  698. category="hardware",
  699. source_id="workspace-current",
  700. ),
  701. ),
  702. excluded=(),
  703. warnings=(
  704. {
  705. "code": "missing_external_source",
  706. "source_id": "td-docs",
  707. "message": "missing",
  708. },
  709. ),
  710. sources=({"id": "workspace-current", "status": "pass"},),
  711. git=(),
  712. )
  713. result = analyzer.create_analysis_package(
  714. collection=collection,
  715. output_root=temp / "output",
  716. package_name="single-fixture",
  717. max_zip_bytes=1_000_000,
  718. target_zip_bytes=800_000,
  719. force=False,
  720. )
  721. package_dir = Path(result["output_dir"])
  722. self.assertEqual(result["status"], "pass_with_warnings")
  723. self.assertEqual(len(result["volumes"]), 1)
  724. volume = package_dir / result["volumes"][0]["file"]
  725. self.assertLess(volume.stat().st_size, 1_000_000)
  726. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  727. self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
  728. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  729. with zipfile.ZipFile(volume) as archive:
  730. self.assertIsNone(archive.testzip())
  731. self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
  732. self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
  733. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  734. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  735. self.assertEqual(index["status"], "pass_with_warnings")
  736. self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
  737. def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
  738. analyzer = load_analyzer(self)
  739. with tempfile.TemporaryDirectory() as tmp:
  740. temp = Path(tmp)
  741. source = temp / "source"
  742. randomizer = random.Random(7)
  743. items = []
  744. for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
  745. path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
  746. items.append(
  747. analyzer.make_package_item(
  748. path,
  749. relative=f"workspace-current/data/file-{index}.bin",
  750. category=category,
  751. source_id="workspace-current",
  752. )
  753. )
  754. collection = analyzer.AnalysisCollection(
  755. status="pass",
  756. items=tuple(items),
  757. excluded=(),
  758. warnings=(),
  759. sources=({"id": "workspace-current", "status": "pass"},),
  760. git=(),
  761. )
  762. result = analyzer.create_analysis_package(
  763. collection=collection,
  764. output_root=temp / "output",
  765. package_name="multi-fixture",
  766. max_zip_bytes=30_000,
  767. target_zip_bytes=20_000,
  768. force=False,
  769. )
  770. package_dir = Path(result["output_dir"])
  771. self.assertGreaterEqual(len(result["volumes"]), 2)
  772. seen_entries: set[str] = set()
  773. for volume_info in result["volumes"]:
  774. volume = package_dir / volume_info["file"]
  775. self.assertLess(volume.stat().st_size, 30_000)
  776. with zipfile.ZipFile(volume) as archive:
  777. self.assertIsNone(archive.testzip())
  778. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  779. seen_entries.update(
  780. name
  781. for name in archive.namelist()
  782. if name.startswith("CPLD/workspace-current/data/") and not name.endswith("/")
  783. )
  784. self.assertEqual(len(seen_entries), 4)
  785. def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
  786. analyzer = load_analyzer(self)
  787. with tempfile.TemporaryDirectory() as tmp:
  788. temp = Path(tmp)
  789. source = temp / "source"
  790. payload = random.Random(19).randbytes(55_000)
  791. large = write_file(source, "data/large.db", payload)
  792. collection = analyzer.AnalysisCollection(
  793. status="pass",
  794. items=(
  795. analyzer.make_package_item(
  796. large,
  797. relative="workspace-current/data/large.db",
  798. category="evidence",
  799. source_id="workspace-current",
  800. ),
  801. ),
  802. excluded=(),
  803. warnings=(),
  804. sources=({"id": "workspace-current", "status": "pass"},),
  805. git=(),
  806. )
  807. result = analyzer.create_analysis_package(
  808. collection=collection,
  809. output_root=temp / "output",
  810. package_name="large-fixture",
  811. max_zip_bytes=30_000,
  812. target_zip_bytes=20_000,
  813. force=False,
  814. )
  815. package_dir = Path(result["output_dir"])
  816. for volume_info in result["volumes"]:
  817. self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
  818. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  819. self.assertEqual(len(index["large_files"]), 1)
  820. large_info = index["large_files"][0]
  821. self.assertEqual(large_info["path"], "workspace-current/data/large.db")
  822. self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
  823. self.assertGreaterEqual(len(large_info["chunks"]), 2)
  824. reassembler = package_dir / "reassemble_large_files.py"
  825. self.assertTrue(reassembler.is_file())
  826. reconstructed = temp / "reconstructed"
  827. completed = subprocess.run(
  828. [
  829. sys.executable,
  830. str(reassembler),
  831. "--package-dir",
  832. str(package_dir),
  833. "--output-dir",
  834. str(reconstructed),
  835. ],
  836. capture_output=True,
  837. text=True,
  838. check=False,
  839. )
  840. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  841. rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
  842. self.assertEqual(rebuilt.read_bytes(), payload)
  843. def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
  844. analyzer = load_analyzer(self)
  845. with tempfile.TemporaryDirectory() as tmp:
  846. temp = Path(tmp)
  847. source = temp / "source"
  848. item = write_file(source, "data/file.bin", b"replacement")
  849. output_root = temp / "output"
  850. final_dir = output_root / "atomic-fixture"
  851. final_dir.mkdir(parents=True)
  852. marker = write_file(final_dir, "old-marker.txt", b"old package")
  853. collection = analyzer.AnalysisCollection(
  854. status="pass",
  855. items=(
  856. analyzer.make_package_item(
  857. item,
  858. relative="workspace-current/data/file.bin",
  859. category="core",
  860. source_id="workspace-current",
  861. ),
  862. ),
  863. excluded=(),
  864. warnings=(),
  865. sources=({"id": "workspace-current", "status": "pass"},),
  866. git=(),
  867. )
  868. real_replace = analyzer.os.replace
  869. def fail_new_directory(source_path: object, target_path: object) -> None:
  870. source_name = Path(source_path).name
  871. if (
  872. source_name != "atomic-fixture"
  873. and not source_name.endswith(".backup")
  874. and Path(target_path).name == "atomic-fixture"
  875. ):
  876. raise OSError("injected publication failure")
  877. real_replace(source_path, target_path)
  878. with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
  879. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  880. analyzer.create_analysis_package(
  881. collection=collection,
  882. output_root=output_root,
  883. package_name="atomic-fixture",
  884. max_zip_bytes=1_000_000,
  885. target_zip_bytes=800_000,
  886. force=True,
  887. )
  888. self.assertEqual(marker.read_bytes(), b"old package")
  889. self.assertEqual(
  890. [path.name for path in output_root.iterdir()],
  891. ["atomic-fixture"],
  892. )
  893. def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
  894. analyzer = load_analyzer(self)
  895. with tempfile.TemporaryDirectory() as tmp:
  896. temp = Path(tmp)
  897. source = temp / "source"
  898. item = write_file(source, "data/file.bin", b"replacement")
  899. output_root = temp / "output"
  900. final_dir = output_root / "backup-failure-fixture"
  901. final_dir.mkdir(parents=True)
  902. marker = write_file(final_dir, "old-marker.txt", b"old package")
  903. collection = analyzer.AnalysisCollection(
  904. status="pass",
  905. items=(
  906. analyzer.make_package_item(
  907. item,
  908. relative="workspace-current/data/file.bin",
  909. category="core",
  910. source_id="workspace-current",
  911. ),
  912. ),
  913. excluded=(),
  914. warnings=(),
  915. sources=({"id": "workspace-current", "status": "pass"},),
  916. git=(),
  917. )
  918. real_replace = analyzer.os.replace
  919. def fail_backup_move(source_path: object, target_path: object) -> None:
  920. if Path(source_path).name == "backup-failure-fixture":
  921. raise OSError("injected backup move failure")
  922. real_replace(source_path, target_path)
  923. with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
  924. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  925. analyzer.create_analysis_package(
  926. collection=collection,
  927. output_root=output_root,
  928. package_name="backup-failure-fixture",
  929. max_zip_bytes=1_000_000,
  930. target_zip_bytes=800_000,
  931. force=True,
  932. )
  933. self.assertEqual(marker.read_bytes(), b"old package")
  934. self.assertEqual(
  935. [path.name for path in output_root.iterdir()],
  936. ["backup-failure-fixture"],
  937. )
  938. def test_package_layout_writes_exclusions_tar_zst_and_checksums(self) -> None:
  939. analyzer = load_analyzer(self)
  940. with tempfile.TemporaryDirectory() as tmp:
  941. temp = Path(tmp)
  942. source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
  943. collection = analyzer.AnalysisCollection(
  944. status="pass",
  945. items=(
  946. analyzer.make_package_item(
  947. source,
  948. relative="workspace-current/src/core.v",
  949. category="core",
  950. source_id="workspace-current",
  951. ),
  952. ),
  953. excluded=(
  954. {"path": ".venv", "rule": "virtual_environment"},
  955. {"path": "tmp", "rule": "temporary_workspace_directory"},
  956. ),
  957. warnings=(),
  958. sources=({"id": "workspace-current", "status": "pass"},),
  959. git=(),
  960. )
  961. result = analyzer.create_analysis_package(
  962. collection=collection,
  963. output_root=temp / "output",
  964. package_name="layout-fixture",
  965. max_zip_bytes=1_000_000,
  966. target_zip_bytes=800_000,
  967. force=False,
  968. )
  969. package_dir = Path(result["output_dir"])
  970. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  971. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  972. self.assertTrue((package_dir / "EXCLUSIONS.txt").is_file())
  973. self.assertTrue((package_dir / "layout-fixture.tar.zst").is_file())
  974. exclusions = (package_dir / "EXCLUSIONS.txt").read_text(encoding="utf-8")
  975. self.assertIn(".venv\tvirtual_environment", exclusions)
  976. sums = (package_dir / "SHA256SUMS.txt").read_text(encoding="ascii")
  977. self.assertIn("layout-fixture.tar.zst", sums)
  978. self.assertIn("EXCLUSIONS.txt", sums)
  979. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  980. self.assertEqual(index["formats"]["tar_zst"], "layout-fixture.tar.zst")
  981. replay = analyzer.replay_analysis_package(
  982. package_dir,
  983. extract_root=temp / "replay",
  984. )
  985. self.assertEqual(replay["status"], "pass")
  986. self.assertTrue(replay["exclusions_present"])
  987. self.assertEqual(replay["tar_zst"], "layout-fixture.tar.zst")
  988. def test_chinese_and_spaces_path_round_trip(self) -> None:
  989. analyzer = load_analyzer(self)
  990. with tempfile.TemporaryDirectory() as tmp:
  991. temp = Path(tmp)
  992. relative = "workspace-current/docs/中文目录/file with spaces.txt"
  993. source = write_file(
  994. temp / "source",
  995. "docs/中文目录/file with spaces.txt",
  996. "中文内容与 spaces\n".encode("utf-8"),
  997. )
  998. collection = analyzer.AnalysisCollection(
  999. status="pass",
  1000. items=(
  1001. analyzer.make_package_item(
  1002. source,
  1003. relative=relative,
  1004. category="core",
  1005. source_id="workspace-current",
  1006. ),
  1007. ),
  1008. excluded=(),
  1009. warnings=(),
  1010. sources=({"id": "workspace-current", "status": "pass"},),
  1011. git=(),
  1012. )
  1013. result = analyzer.create_analysis_package(
  1014. collection=collection,
  1015. output_root=temp / "output",
  1016. package_name="unicode-fixture",
  1017. max_zip_bytes=1_000_000,
  1018. target_zip_bytes=800_000,
  1019. force=False,
  1020. )
  1021. package_dir = Path(result["output_dir"])
  1022. volume = package_dir / result["volumes"][0]["file"]
  1023. with zipfile.ZipFile(volume) as archive:
  1024. names = archive.namelist()
  1025. self.assertIn(f"CPLD/{relative}", names)
  1026. info = archive.getinfo(f"CPLD/{relative}")
  1027. self.assertTrue(info.flag_bits & 0x800)
  1028. self.assertEqual(
  1029. archive.read(f"CPLD/{relative}"),
  1030. "中文内容与 spaces\n".encode("utf-8"),
  1031. )
  1032. replay = analyzer.replay_analysis_package(
  1033. package_dir,
  1034. extract_root=temp / "replay-unicode",
  1035. )
  1036. self.assertEqual(replay["status"], "pass")
  1037. self.assertEqual(replay["checked_files"], 1)
  1038. def test_full_profile_requires_git_bundle(self) -> None:
  1039. analyzer = load_analyzer(self)
  1040. with tempfile.TemporaryDirectory() as tmp:
  1041. temp = Path(tmp)
  1042. repo = temp / "repo"
  1043. repo.mkdir()
  1044. git = shutil.which("git")
  1045. if not git:
  1046. self.skipTest("Git is required")
  1047. subprocess.run([git, "init", "-q", str(repo)], check=True)
  1048. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  1049. subprocess.run(
  1050. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  1051. check=True,
  1052. )
  1053. write_file(repo, "src/core.v", b"module core; endmodule\n")
  1054. subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
  1055. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  1056. config = analyzer.HandoffConfig(
  1057. max_zip_bytes=1_000_000,
  1058. target_zip_bytes=800_000,
  1059. external_sources=(),
  1060. extra_exclusions=(),
  1061. )
  1062. with self.assertRaisesRegex(analyzer.PackagingError, "git bundle"):
  1063. analyzer.collect_analysis_inputs(
  1064. repo_root=repo,
  1065. config=config,
  1066. temp_root=temp / "run",
  1067. include_git_bundle=False,
  1068. profile="full",
  1069. )
  1070. class ReviewCompactProfileSmokeTests(unittest.TestCase):
  1071. maxDiff = None
  1072. def _init_repo(self, repo: Path) -> str:
  1073. git = shutil.which("git")
  1074. if not git:
  1075. self.skipTest("Git is required")
  1076. repo.mkdir(parents=True, exist_ok=True)
  1077. subprocess.run([git, "init", "-q", str(repo)], check=True)
  1078. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  1079. subprocess.run(
  1080. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  1081. check=True,
  1082. )
  1083. write_file(repo, "src/core.v", b"module core; endmodule\n")
  1084. write_file(
  1085. repo,
  1086. "receipts/verification-matrix-final.json",
  1087. b'{"status":"pass","schema":"fixture"}\n',
  1088. )
  1089. write_file(repo, "reference/original/board/main.brd", b"BOARD")
  1090. write_file(repo, "reference/original/schematics/main.pdf", b"%PDF")
  1091. write_file(repo, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
  1092. write_file(repo, ".run_id_stale", b"stale\n")
  1093. write_file(repo, "node_modules/pkg/index.js", b"nope\n")
  1094. subprocess.run(
  1095. [git, "-C", str(repo), "add", "src/core.v", "receipts/verification-matrix-final.json"],
  1096. check=True,
  1097. )
  1098. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  1099. return git
  1100. def test_review_compact_excludes_heavy_originals_keeps_fixtures(self) -> None:
  1101. analyzer = load_analyzer(self)
  1102. with tempfile.TemporaryDirectory() as tmp:
  1103. root = Path(tmp)
  1104. write_file(root, "src/core.v", b"module core; endmodule\n")
  1105. write_file(root, "reference/original/board/main.brd", b"BOARD")
  1106. write_file(root, "reference/original/schematics/main.pdf", b"%PDF")
  1107. write_file(root, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
  1108. write_file(root, ".run_id_stale", b"stale\n")
  1109. candidates, excluded, _ = analyzer.scan_analysis_root(root, profile="review-compact")
  1110. included = {item.relative for item in candidates}
  1111. self.assertIn("src/core.v", included)
  1112. self.assertIn("tests/board_viewer/fixtures/tiny.dsn", included)
  1113. self.assertNotIn("reference/original/board/main.brd", included)
  1114. self.assertNotIn("reference/original/schematics/main.pdf", included)
  1115. self.assertNotIn(".run_id_stale", included)
  1116. rules = {item["path"]: item["rule"] for item in excluded}
  1117. self.assertEqual(rules.get("reference/original/board"), "reference_original_board")
  1118. def test_review_compact_unified_layout_and_no_git_bundle(self) -> None:
  1119. analyzer = load_analyzer(self)
  1120. with tempfile.TemporaryDirectory() as tmp:
  1121. temp = Path(tmp)
  1122. repo = temp / "repo"
  1123. self._init_repo(repo)
  1124. generated = temp / "generated"
  1125. write_file(generated, "board-data.json", b'{"ok":true}\n')
  1126. write_file(generated, "build-info.json", b'{"ok":true}\n')
  1127. write_file(generated, "import-report.json", b'{"ok":true}\n')
  1128. write_file(generated, "board-copper.svg", b"<svg/>\n")
  1129. write_file(generated, "board-silkscreen.svg", b"<svg/>\n")
  1130. write_file(generated, "board-mask-edge.svg", b"<svg/>\n")
  1131. write_file(generated, "board-copper-back.svg", b"<svg/>\n")
  1132. write_file(generated, "board-silkscreen-back.svg", b"<svg/>\n")
  1133. write_file(generated, "board-mask-edge-back.svg", b"<svg/>\n")
  1134. config = analyzer.HandoffConfig(
  1135. max_zip_bytes=5_000_000,
  1136. target_zip_bytes=4_000_000,
  1137. external_sources=(
  1138. analyzer.ExternalSource(
  1139. id="board-viewer-generated",
  1140. category="hardware",
  1141. kind="directory",
  1142. path_candidates=(generated,),
  1143. archive_policy="copy",
  1144. ),
  1145. ),
  1146. extra_exclusions=(),
  1147. )
  1148. collection = analyzer.collect_analysis_inputs(
  1149. repo_root=repo,
  1150. config=config,
  1151. temp_root=temp / "run",
  1152. include_git_bundle=True, # must be forced off for review-compact
  1153. profile="review-compact",
  1154. package_name="smoke-review-compact",
  1155. )
  1156. paths = {item.candidate.relative for item in collection.items}
  1157. self.assertTrue(any(path.startswith("source/") for path in paths))
  1158. self.assertIn("source/src/core.v", paths)
  1159. self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
  1160. self.assertIn("evidence/board-viewer/board-data.json", paths)
  1161. self.assertTrue(any(path.startswith("meta/git/") for path in paths))
  1162. self.assertFalse(any(path.endswith(".bundle") for path in paths))
  1163. self.assertFalse(any("reference/original/board" in path for path in paths))
  1164. result = analyzer.create_analysis_package(
  1165. collection=collection,
  1166. output_root=temp / "output",
  1167. package_name="smoke-review-compact",
  1168. max_zip_bytes=5_000_000,
  1169. target_zip_bytes=4_000_000,
  1170. force=False,
  1171. profile="review-compact",
  1172. )
  1173. package_dir = Path(result["output_dir"])
  1174. self.assertEqual(result["delivery_policy"], "review-compact")
  1175. self.assertTrue((package_dir / "PACKAGE-PURPOSE.txt").is_file())
  1176. self.assertTrue((package_dir / "size-budget.json").is_file())
  1177. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  1178. self.assertEqual(index["profile"], "review-compact")
  1179. self.assertIn("member_count", index)
  1180. self.assertIn("self_reference_control_files", index["member_count"])
  1181. self.assertIn("size_budget", index)
  1182. volume = package_dir / result["volumes"][0]["file"]
  1183. with zipfile.ZipFile(volume) as archive:
  1184. names = set(archive.namelist())
  1185. self.assertIn("CPLD/source/src/core.v", names)
  1186. self.assertIn("CPLD/evidence/matrix/verification-matrix-final.json", names)
  1187. self.assertIn("CPLD/meta/git/log-20.txt", names)
  1188. self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
  1189. self.assertFalse(any(name.endswith(".bundle") for name in names))
  1190. index_schema = json.loads(
  1191. (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
  1192. encoding="utf-8"
  1193. )
  1194. )
  1195. jsonschema.validate(index, index_schema)
  1196. def test_review_debug_and_archive_local_profiles_are_registered(self) -> None:
  1197. analyzer = load_analyzer(self)
  1198. self.assertIn("review-debug", analyzer.handoff.HANDOFF_PROFILES)
  1199. self.assertIn("archive-local", analyzer.handoff.HANDOFF_PROFILES)
  1200. self.assertEqual(analyzer.handoff.DEFAULT_HANDOFF_PROFILE, "review-compact")
  1201. self.assertTrue(analyzer.handoff.uses_unified_layout("review-debug"))
  1202. self.assertEqual(
  1203. analyzer.handoff.delivery_policy_for_profile("archive-local"),
  1204. "archive-local",
  1205. )
  1206. if __name__ == "__main__":
  1207. unittest.main()