test_package_for_agent_analysis.py 57 KB

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