test_package_for_agent_analysis.py 56 KB

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