test_package_for_agent_analysis.py 43 KB

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