test_agent_handoff_package.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. #!/usr/bin/env python3
  2. """Integration tests for the agent analysis handoff packager."""
  3. from __future__ import annotations
  4. import hashlib
  5. import io
  6. import json
  7. import os
  8. import shutil
  9. import stat
  10. import subprocess
  11. import sys
  12. import tarfile
  13. import tempfile
  14. import unittest
  15. import zipfile
  16. from contextlib import contextmanager
  17. from pathlib import Path
  18. from types import SimpleNamespace
  19. from unittest import mock
  20. ROOT = Path(__file__).resolve().parents[2]
  21. PACKAGER = ROOT / "tools" / "package_agent_handoff.ps1"
  22. PACKAGER_CORE = ROOT / "tools" / "package_agent_handoff.py"
  23. sys.path.insert(0, str(ROOT / "tools"))
  24. import package_agent_handoff as handoff # noqa: E402
  25. def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
  26. path = root / Path(relative)
  27. path.parent.mkdir(parents=True, exist_ok=True)
  28. path.write_bytes(data)
  29. return path
  30. def zip_bytes(entries: dict[str, bytes]) -> bytes:
  31. payload = io.BytesIO()
  32. with zipfile.ZipFile(payload, "w", compression=zipfile.ZIP_DEFLATED) as archive:
  33. for name, data in entries.items():
  34. archive.writestr(name, data)
  35. return payload.getvalue()
  36. def stored_zip_bytes(entries: dict[str, bytes]) -> bytes:
  37. payload = io.BytesIO()
  38. with zipfile.ZipFile(payload, "w", compression=zipfile.ZIP_STORED) as archive:
  39. for name, data in entries.items():
  40. archive.writestr(name, data)
  41. return payload.getvalue()
  42. def tar_gz_bytes(entries: dict[str, bytes]) -> bytes:
  43. payload = io.BytesIO()
  44. with tarfile.open(fileobj=payload, mode="w:gz") as archive:
  45. for name, data in entries.items():
  46. info = tarfile.TarInfo(name)
  47. info.size = len(data)
  48. info.mtime = 0
  49. archive.addfile(info, io.BytesIO(data))
  50. return payload.getvalue()
  51. def run_packager(
  52. source_root: Path,
  53. output_dir: Path,
  54. package_name: str,
  55. *extra: str,
  56. env: dict[str, str] | None = None,
  57. ) -> subprocess.CompletedProcess[str]:
  58. powershell = shutil.which("powershell.exe")
  59. if powershell:
  60. command = [
  61. powershell,
  62. "-NoProfile",
  63. "-ExecutionPolicy",
  64. "Bypass",
  65. "-File",
  66. str(PACKAGER),
  67. "-SourceRoot",
  68. str(source_root),
  69. "-OutputDir",
  70. str(output_dir),
  71. "-PackageName",
  72. package_name,
  73. *extra,
  74. ]
  75. else:
  76. option_map = {
  77. "-AuditOnly": "--audit-only",
  78. "-ForceOverwrite": "--force-overwrite",
  79. }
  80. # Legacy fixture tests assert inclusion-first "full" behavior; default
  81. # CLI profile is review-compact which excludes reference/original/board.
  82. profile_args: list[str] = []
  83. mapped_extra: list[str] = []
  84. i = 0
  85. extras = list(extra)
  86. while i < len(extras):
  87. item = extras[i]
  88. if item == "--profile" and i + 1 < len(extras):
  89. profile_args = ["--profile", extras[i + 1]]
  90. i += 2
  91. continue
  92. if item in option_map:
  93. mapped_extra.append(option_map[item])
  94. i += 1
  95. continue
  96. # Pass through unknown flags (e.g. already-mapped forms)
  97. mapped_extra.append(item)
  98. i += 1
  99. if not profile_args:
  100. profile_args = ["--profile", "full"]
  101. command = [
  102. sys.executable,
  103. str(PACKAGER_CORE),
  104. "--source-root",
  105. str(source_root),
  106. "--output-dir",
  107. str(output_dir),
  108. "--package-name",
  109. package_name,
  110. *profile_args,
  111. *mapped_extra,
  112. ]
  113. return subprocess.run(
  114. command,
  115. cwd=ROOT,
  116. capture_output=True,
  117. text=True,
  118. check=False,
  119. env=env,
  120. )
  121. class AgentHandoffPackageTests(unittest.TestCase):
  122. maxDiff = None
  123. def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
  124. command = handoff.build_7zip_create_command(
  125. Path("package.zip"),
  126. Path("staging"),
  127. )
  128. self.assertEqual(command[:4], ["a", "-tzip", "-mm=Deflate", "-mx=9"])
  129. self.assertNotIn("LZMA", " ".join(command).upper())
  130. def test_create_package_falls_back_to_zipfile_without_7zip(self) -> None:
  131. with tempfile.TemporaryDirectory() as tmp:
  132. temp = Path(tmp)
  133. source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
  134. file_stat = os.lstat(source)
  135. candidate = handoff.Candidate(
  136. absolute=source,
  137. relative="src/core.v",
  138. size=file_stat.st_size,
  139. mtime_ns=file_stat.st_mtime_ns,
  140. device=int(file_stat.st_dev),
  141. inode=int(file_stat.st_ino),
  142. mode=int(file_stat.st_mode),
  143. )
  144. with mock.patch.object(handoff, "find_7z", return_value=None):
  145. result = handoff.create_package(
  146. root=temp / "source",
  147. output_dir=temp / "output",
  148. package_name="no-7z",
  149. force=False,
  150. candidates=[candidate],
  151. excluded=[],
  152. context=handoff.ScanContext(None),
  153. )
  154. self.assertEqual(result["status"], "pass")
  155. zip_path = Path(result["package_zip"])
  156. self.assertTrue(zip_path.is_file())
  157. with zipfile.ZipFile(zip_path, "r") as archive:
  158. names = set(archive.namelist())
  159. self.assertIn(f"{handoff.ARCHIVE_ROOT}/src/core.v", names)
  160. self.assertIn(f"{handoff.METADATA_ROOT}/manifest.json", names)
  161. @unittest.skipUnless(os.name == "nt", "Windows executable mode semantics are required")
  162. def test_open_candidate_accepts_windows_executable_mode_disagreement(self) -> None:
  163. with tempfile.TemporaryDirectory() as tmp:
  164. source = Path(tmp)
  165. path = write_file(source, "run.bat", b"@echo off\r\n")
  166. file_stat = os.lstat(path)
  167. candidate = handoff.Candidate(
  168. absolute=path,
  169. relative="run.bat",
  170. size=file_stat.st_size,
  171. mtime_ns=file_stat.st_mtime_ns,
  172. device=int(file_stat.st_dev),
  173. inode=int(file_stat.st_ino),
  174. mode=int(file_stat.st_mode),
  175. )
  176. with handoff.open_candidate(candidate) as source_stream:
  177. self.assertEqual(source_stream.read(), b"@echo off\r\n")
  178. def test_wrapper_ignores_python_startup_hooks(self) -> None:
  179. powershell = shutil.which("powershell.exe")
  180. if not powershell:
  181. self.skipTest("Windows PowerShell is unavailable")
  182. with tempfile.TemporaryDirectory() as tmp:
  183. temp = Path(tmp)
  184. source = temp / "source"
  185. output = temp / "output"
  186. hooks = temp / "python-hooks"
  187. marker = temp / "sitecustomize-executed.txt"
  188. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  189. write_file(
  190. hooks,
  191. "sitecustomize.py",
  192. (
  193. "from pathlib import Path\n"
  194. f"Path({str(marker)!r}).write_text('executed', encoding='utf-8')\n"
  195. ).encode("utf-8"),
  196. )
  197. env = os.environ.copy()
  198. env["PYTHONPATH"] = str(hooks)
  199. env["PYTHONSTARTUP"] = str(hooks / "sitecustomize.py")
  200. result = run_packager(
  201. source,
  202. output,
  203. "startup-isolation-fixture",
  204. "-AuditOnly",
  205. env=env,
  206. )
  207. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  208. self.assertFalse(marker.exists(), "wrapper executed source-controlled startup code")
  209. payload = json.loads(result.stdout)
  210. self.assertEqual(payload["status"], "pass")
  211. self.assertEqual(payload["mode"], "audit_only")
  212. def test_wrapper_skips_python_candidates_inside_repo_or_source_root(self) -> None:
  213. powershell = shutil.which("powershell.exe")
  214. py_launcher = shutil.which("py.exe") or shutil.which("py")
  215. if not powershell or not py_launcher:
  216. self.skipTest("Windows PowerShell and the external Python launcher are required")
  217. with tempfile.TemporaryDirectory() as tmp:
  218. temp = Path(tmp)
  219. wrapper_repo = temp / "wrapper-repo"
  220. tools = wrapper_repo / "tools"
  221. tools.mkdir(parents=True)
  222. shutil.copy2(PACKAGER, tools / PACKAGER.name)
  223. shutil.copy2(PACKAGER_CORE, tools / PACKAGER_CORE.name)
  224. source = temp / "source"
  225. output = temp / "output"
  226. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  227. for candidate_scope in ("repo", "source"):
  228. with self.subTest(candidate_scope=candidate_scope):
  229. candidate_root = wrapper_repo if candidate_scope == "repo" else source
  230. candidate_dir = (
  231. candidate_root / "candidate-bin"
  232. if candidate_scope == "repo"
  233. else candidate_root / ".venv" / "Scripts"
  234. )
  235. candidate_dir.mkdir(parents=True, exist_ok=True)
  236. marker = temp / f"{candidate_scope}-python-executed.txt"
  237. fake_python = candidate_dir / "python.cmd"
  238. fake_python.write_text(
  239. f'@echo invoked>>"{marker}"\n@exit /b 0\n',
  240. encoding="ascii",
  241. )
  242. env = os.environ.copy()
  243. env["PATH"] = os.pathsep.join(
  244. (
  245. str(candidate_dir),
  246. str(Path(py_launcher).parent),
  247. str(Path(powershell).parent),
  248. )
  249. )
  250. result = subprocess.run(
  251. [
  252. powershell,
  253. "-NoProfile",
  254. "-ExecutionPolicy",
  255. "Bypass",
  256. "-File",
  257. str(tools / PACKAGER.name),
  258. "-SourceRoot",
  259. str(source),
  260. "-OutputDir",
  261. str(output),
  262. "-PackageName",
  263. f"{candidate_scope}-candidate-fixture",
  264. "-AuditOnly",
  265. ],
  266. cwd=wrapper_repo,
  267. capture_output=True,
  268. text=True,
  269. check=False,
  270. env=env,
  271. )
  272. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  273. self.assertFalse(
  274. marker.exists(),
  275. f"wrapper executed Python candidate inside {candidate_scope}",
  276. )
  277. payload = json.loads(result.stdout)
  278. self.assertEqual(payload["status"], "pass")
  279. self.assertEqual(payload["mode"], "audit_only")
  280. def test_wrapper_resolves_junction_source_root_before_python_selection(self) -> None:
  281. powershell = shutil.which("powershell.exe")
  282. py_launcher = shutil.which("py.exe") or shutil.which("py")
  283. command_prompt = shutil.which("cmd.exe")
  284. if not powershell or not py_launcher or not command_prompt:
  285. self.skipTest("Windows PowerShell, cmd, and the external Python launcher are required")
  286. with tempfile.TemporaryDirectory() as tmp:
  287. temp = Path(tmp)
  288. wrapper_repo = temp / "wrapper-repo"
  289. tools = wrapper_repo / "tools"
  290. tools.mkdir(parents=True)
  291. shutil.copy2(PACKAGER, tools / PACKAGER.name)
  292. shutil.copy2(PACKAGER_CORE, tools / PACKAGER_CORE.name)
  293. source = temp / "actual-source"
  294. source_alias = temp / "source-alias"
  295. output = temp / "output"
  296. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  297. candidate_dir = source / ".venv" / "Scripts"
  298. candidate_dir.mkdir(parents=True)
  299. marker = temp / "junction-python-executed.txt"
  300. (candidate_dir / "python.cmd").write_text(
  301. f'@echo invoked>>"{marker}"\n@exit /b 0\n',
  302. encoding="ascii",
  303. )
  304. junction = subprocess.run(
  305. [command_prompt, "/d", "/c", "mklink", "/J", str(source_alias), str(source)],
  306. capture_output=True,
  307. text=True,
  308. check=False,
  309. )
  310. if junction.returncode != 0:
  311. self.skipTest(f"unable to create a directory junction: {junction.stderr}")
  312. try:
  313. env = os.environ.copy()
  314. env["PATH"] = os.pathsep.join(
  315. (
  316. str(candidate_dir),
  317. str(Path(py_launcher).parent),
  318. str(Path(powershell).parent),
  319. )
  320. )
  321. result = subprocess.run(
  322. [
  323. powershell,
  324. "-NoProfile",
  325. "-ExecutionPolicy",
  326. "Bypass",
  327. "-File",
  328. str(tools / PACKAGER.name),
  329. "-SourceRoot",
  330. str(source_alias),
  331. "-OutputDir",
  332. str(output),
  333. "-PackageName",
  334. "junction-source-fixture",
  335. "-AuditOnly",
  336. ],
  337. cwd=wrapper_repo,
  338. capture_output=True,
  339. text=True,
  340. check=False,
  341. env=env,
  342. )
  343. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  344. self.assertFalse(marker.exists(), "wrapper executed Python inside junction target")
  345. payload = json.loads(result.stdout)
  346. self.assertEqual(payload["status"], "pass")
  347. self.assertEqual(payload["mode"], "audit_only")
  348. finally:
  349. if os.path.lexists(source_alias):
  350. os.rmdir(source_alias)
  351. def test_packager_keeps_analysis_inputs_and_removes_only_declared_runtime_content(self) -> None:
  352. self.assertTrue(PACKAGER.is_file(), PACKAGER)
  353. with tempfile.TemporaryDirectory() as tmp:
  354. temp = Path(tmp)
  355. source = temp / "source"
  356. output = temp / "output"
  357. included = {
  358. "AGENTS.md": b"project contract\n",
  359. ".gitignore": b"tmp/\n",
  360. "config/.env.template": b"DEVICE_PORT=COM3\n",
  361. "src/rtl/core.v": b"module core; endmodule\n",
  362. "docs/需求说明.md": "完整需求\n".encode("utf-8"),
  363. "tests/fixtures/failure.log": b"expected failure fixture\n",
  364. "receipts/programmer/bitwriter-stdout.log": b"evidence\n",
  365. "receipts/fail.json": b'{"status":"fail"}\n',
  366. "reference/original/board/vendor-original.zip": zip_bytes(
  367. {"vendor/readme.txt": b"raw original archive\n"}
  368. ),
  369. "reference/original/board/public-ca.pem": b"-----BEGIN CERTIFICATE-----\npublic\n-----END CERTIFICATE-----\n",
  370. "reference/original/local_archives/private.zip": zip_bytes(
  371. {"private/readme.txt": b"original archive\n"}
  372. ),
  373. "td/project/active_project.al": b"active TD project input\n",
  374. "td/project/active_project.cwc": b"active ChipWatcher project input\n",
  375. "td/project/assets/test_runs/keep.al": b"nested active project input\n",
  376. "tools/computer_use/README.md": b"future active verification tool\n",
  377. "tmp/mutation/remove_force_off.json": b'{"mutation":"remove_force_off"}\n',
  378. "tmp/mutation/remove_force_off.patch": b"mutation patch evidence\n",
  379. "tmp/resource_audit/profile/probe.v": b"module probe; endmodule\n",
  380. "tmp/resource_audit/profile/generated.f": b"rtl/core.v\n",
  381. "tmp/resource_audit/profile/generated.tsm": b"generated timing model\n",
  382. "tmp/pwm_executor_probe/profile/run.tcl": b"# probe definition\n",
  383. "tmp/pwm_executor_probe/profile/generated.f": b"rtl/pwm.v\n",
  384. "tmp/pwm_executor_probe/profile/generated.tsm": b"generated timing model\n",
  385. "tmp/debug_bundle/offline/agent_context.md": b"debug context\n",
  386. "tmp/formal_runs/fault/trace.vcd": b"$date\n",
  387. "tmp/formal_runs/fault/config.sby": b"[options]\nmode prove\n",
  388. "tmp/formal_runs/fault/model/design.json": b'{"formal":"model"}\n',
  389. "tmp/formal_runs/fault/logfile.txt": b"formal proof log\n",
  390. "tmp/formal_runs/fault/PASS": b"pass\n",
  391. "tmp/photos/board-connectors.jpg": b"real board photo\n",
  392. "tmp/pdfs/schematic-page.png": b"schematic crop\n",
  393. "tmp/new-analysis/evidence.json": b'{"status":"observed"}\n',
  394. "tools/changxin-temp-uart/pyproject.toml": b'[project]\nname="changxin-temp-uart"\nversion="0.1.9"\n',
  395. "notes/build-notes.txt": b"not a build directory\n",
  396. "mytmp/keep.txt": b"not the top-level tmp directory\n",
  397. }
  398. for relative, data in included.items():
  399. write_file(source, relative, data)
  400. hidden = write_file(source, "docs/hidden-contract.txt", b"hidden but required\n")
  401. attrib = shutil.which("attrib.exe")
  402. if attrib:
  403. subprocess.run([attrib, "+H", str(hidden)], capture_output=True, check=True)
  404. included["docs/hidden-contract.txt"] = b"hidden but required\n"
  405. deprecated_workspace_path = "/".join(("workspace", "old-study.v"))
  406. excluded = [
  407. ".git/objects/dead-secret",
  408. ".codegraph/codegraph.db",
  409. ".codex/venv/Lib/site-packages/cache.py",
  410. ".codex/session-state.json",
  411. ".codex/cleanup_manifests/cleanup.json",
  412. ".codex/reports/report.tmp",
  413. ".omo/run-continuation/session.json",
  414. ".hypothesis/constants/cache",
  415. ".pytest_cache/v/cache/nodeids",
  416. "src/rtl/__pycache__/core.cpython-312.pyc",
  417. "tmp/rtl_sim/core.vvp",
  418. "tmp/cocotb/pid_core_smoke/sim.vvp",
  419. "tmp/detector_selftest/bad_icarus.vvp",
  420. "tmp/toolchain_probe/td_probe.log",
  421. "tmp/resource_audit/profile/stale.db",
  422. "tmp/resource_audit/profile/postgate.area",
  423. "tmp/pwm_executor_probe/profile/gate.qor",
  424. "tmp/resource_audit/profile/td_user_env/temp/state.bin",
  425. "tmp/pwm_executor_probe/profile/td_user_env/temp/state.bin",
  426. "tmp/debug_bundle/offline/fw.bit",
  427. "td/build/profile/syn/profile_gate.db",
  428. "td/build/profile/syn/gate.qor",
  429. "td/build/profile/phy/final_timing.rpt",
  430. "td/build/profile/syn/td_20260711_120000.log",
  431. "td/build/profile/syn/source-manifest.json",
  432. "td/build/profile/syn/profile_elaboration_plan.json",
  433. "td/build/profile/phy/profile.bit",
  434. "td/build/profile/syn/src/rtl/core.v",
  435. "td/build/profile/syn/constraints/pins.adc",
  436. "td/build/profile/syn/profile.prj",
  437. "td/build/profile/syn/profile.tcl",
  438. "td/build/profile/syn/td_user_env/temp/state.bin",
  439. "td/project/profile_Runs/run.log",
  440. "td/project/log/runtime.log",
  441. "td/project/.lock.f",
  442. "td/project/.recent_user_depot.ini",
  443. "td/td_20260711_120000.log",
  444. "td/td_20260711_120000.logw",
  445. "receipts/local/live.json",
  446. "reference/original/local_archives/Anlogic.lic",
  447. "reference/original/vendor/installer.exe",
  448. deprecated_workspace_path,
  449. "dist/old-package.zip",
  450. "_archive/old-source.v",
  451. "ANLOGIC_CD/setup.exe",
  452. "log/bw_runtime.log",
  453. "unused/note.txt",
  454. "tools/changxin-temp-uart/build/lib/copy.py",
  455. "tools/changxin-temp-uart/changxin_temp_uart.egg-info/PKG-INFO",
  456. "tools/changxin-temp-uart/pyinstaller-build/cache.bin",
  457. "tools/changxin-temp-uart/pyinstaller-spec/app.spec",
  458. "tools/changxin-temp-uart/pyinstaller-entry.py",
  459. "tools/changxin-temp-uart/linux-onefile-build.json",
  460. "tools/changxin-temp-uart/changxin-temp-uart-static",
  461. "atomic-receipt.json.tmp",
  462. "download.part",
  463. "minidump-123.dmp",
  464. "tmp_last_pkg1.txt",
  465. "a.out",
  466. ".env",
  467. "id_rsa",
  468. "signing.key",
  469. "certificate.pfx",
  470. ".netrc",
  471. ".pypirc",
  472. ".npmrc",
  473. ".git-credentials",
  474. ".aws/credentials",
  475. ".docker/config.json",
  476. "receipts/incomplete.json",
  477. "tests/cocotb/results.xml",
  478. ".codex/reports/chipwatcher.json",
  479. "tmp/new-analysis/host-crash.dmp",
  480. "tmp/new-analysis/interrupted.partial",
  481. "tools/changxin-temp-uart/dist/changxin-temp-uart-0.1.2-release.zip",
  482. "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.8-py3-none-any.whl",
  483. "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.9-py3-none-any.whl",
  484. "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.9.tar.gz",
  485. "tools/changxin-temp-uart/dist/changxin-temp-uart-0.1.9-deploy.zip",
  486. "tools/changxin-temp-uart/dist/pyserial-3.5-py2.py3-none-any.whl",
  487. ]
  488. for relative in excluded:
  489. data = b"null\r\n" if relative == "receipts/incomplete.json" else b"fixture\n"
  490. write_file(source, relative, data)
  491. result = run_packager(source, output, "fixture-handoff")
  492. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  493. zip_path = output / "fixture-handoff.zip"
  494. sidecar = output / "fixture-handoff.zip.sha256.txt"
  495. self.assertTrue(zip_path.is_file())
  496. self.assertTrue(sidecar.is_file())
  497. self.assertEqual(
  498. sidecar.read_text(encoding="ascii").split()[0],
  499. hashlib.sha256(zip_path.read_bytes()).hexdigest(),
  500. )
  501. with zipfile.ZipFile(zip_path) as archive:
  502. names = archive.namelist()
  503. name_set = set(names)
  504. self.assertEqual(len(names), len(name_set))
  505. self.assertTrue(all("\\" not in name for name in names))
  506. for relative, data in included.items():
  507. entry = f"CPLD/{relative}"
  508. self.assertIn(entry, name_set)
  509. self.assertEqual(archive.read(entry), data)
  510. for relative in excluded:
  511. self.assertNotIn(f"CPLD/{relative}", name_set)
  512. metadata_root = "CPLD/HANDOFF-METADATA"
  513. manifest = json.loads(archive.read(f"{metadata_root}/manifest.json").decode("utf-8"))
  514. exclusions = json.loads(archive.read(f"{metadata_root}/exclusions.json").decode("utf-8"))
  515. inventory = json.loads(archive.read(f"{metadata_root}/sha256-inventory.json").decode("utf-8"))
  516. self.assertEqual(manifest["schema"], "cpld-agent-handoff-v1")
  517. self.assertEqual(manifest["status"], "pass")
  518. self.assertEqual(manifest["package_name"], "fixture-handoff")
  519. self.assertEqual(
  520. manifest["archive_scan_limits"],
  521. {
  522. "max_depth": 3,
  523. "max_members": 100_000,
  524. "max_uncompressed_bytes": 8 * 1024 * 1024 * 1024,
  525. "source_file_size_limit": None,
  526. },
  527. )
  528. self.assertNotIn(str(source), json.dumps(manifest, ensure_ascii=False))
  529. self.assertEqual(
  530. [item["path"] for item in inventory["inventory"]],
  531. sorted(included, key=handoff.windows_collision_key),
  532. )
  533. for item in inventory["inventory"]:
  534. self.assertEqual(item["sha256"], hashlib.sha256(included[item["path"]]).hexdigest())
  535. self.assertEqual(item["size"], len(included[item["path"]]))
  536. excluded_paths = {item["path"] for item in exclusions["excluded"]}
  537. excluded_rules = {item["rule"] for item in exclusions["excluded"]}
  538. self.assertIn("tmp/rtl_sim", excluded_paths)
  539. self.assertIn("td/build", excluded_paths)
  540. self.assertNotIn("reference/original/local_archives", excluded_paths)
  541. self.assertIn(".codex", excluded_paths)
  542. self.assertNotIn("tmp_runtime_non_evidence", excluded_rules)
  543. self.assertNotIn("obsolete_or_third_party_changxin_release", excluded_rules)
  544. def test_generated_metadata_rejects_private_key_content(self) -> None:
  545. with tempfile.TemporaryDirectory() as tmp:
  546. archive_path = Path(tmp) / "metadata.zip"
  547. marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
  548. with zipfile.ZipFile(archive_path, "w") as archive:
  549. with self.assertRaises(handoff.PackagingError):
  550. handoff.write_bytes_entry(
  551. archive,
  552. "CPLD/HANDOFF-METADATA/working-tree.patch",
  553. marker,
  554. )
  555. def test_generated_metadata_rejects_high_confidence_token(self) -> None:
  556. with tempfile.TemporaryDirectory() as tmp:
  557. archive_path = Path(tmp) / "metadata.zip"
  558. token = b"aws_" + b"secret_access_key=" + (b"A" * 40)
  559. with zipfile.ZipFile(archive_path, "w") as archive:
  560. with self.assertRaises(handoff.PackagingError):
  561. handoff.write_bytes_entry(
  562. archive,
  563. "CPLD/HANDOFF-METADATA/git-status.txt",
  564. b"M docs/" + token + b".txt\n",
  565. )
  566. def test_secret_scanner_covers_supported_tokens_and_chunk_boundaries(self) -> None:
  567. tokens = {
  568. "github_classic": b"gh" + b"p_" + (b"A" * 36),
  569. "github_fine_grained": b"github_" + b"pat_" + (b"A" * 22) + b"_" + (b"B" * 59),
  570. "aws_secret_access_key": b"aws_" + b"secret_access_key = " + (b"A" * 40),
  571. "aws_session_token": b"aws_" + b"session_token: " + (b"A" * 80),
  572. "openai_project": b"sk-" + b"proj-" + (b"A" * 48),
  573. "slack_bot": b"xox" + b"b-" + b"123456789012-" + (b"A" * 32),
  574. }
  575. for name, token in tokens.items():
  576. with self.subTest(name=name):
  577. with self.assertRaises(handoff.PackagingError):
  578. handoff.scan_secret_markers(token, b"", f"docs/{name}.txt")
  579. token = b"gh" + b"o_" + (b"C" * 36)
  580. first = b"prefix:" + token[:9]
  581. tail = handoff.scan_secret_markers(first, b"", "docs/chunked.txt")
  582. with self.assertRaises(handoff.PackagingError):
  583. handoff.scan_secret_markers(token[9:] + b":suffix", tail, "docs/chunked.txt")
  584. handoff.scan_secret_markers(b"ghp_EXAMPLE", b"", "docs/example.txt")
  585. handoff.scan_secret_markers(b"AK" + b"IAIOSFODNN7EXAMPLE", b"", "docs/aws-example.txt")
  586. def test_audit_only_rejects_private_key_content(self) -> None:
  587. with tempfile.TemporaryDirectory() as tmp:
  588. temp = Path(tmp)
  589. source = temp / "source"
  590. output = temp / "output"
  591. marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
  592. write_file(source, "docs/leak.txt", marker)
  593. result = run_packager(source, output, "audit-secret", "-AuditOnly")
  594. self.assertNotEqual(result.returncode, 0)
  595. self.assertIn("private key", (result.stderr + result.stdout).lower())
  596. self.assertFalse(output.exists())
  597. def test_high_confidence_token_is_rejected_without_archive(self) -> None:
  598. with tempfile.TemporaryDirectory() as tmp:
  599. temp = Path(tmp)
  600. source = temp / "source"
  601. output = temp / "output"
  602. token = b"ghp_" + (b"A" * 36)
  603. write_file(source, "docs/leak.txt", token + b"\n")
  604. result = run_packager(source, output, "token-secret")
  605. self.assertNotEqual(result.returncode, 0)
  606. self.assertIn("secret", (result.stderr + result.stdout).lower())
  607. self.assertFalse((output / "token-secret.zip").exists())
  608. self.assertNotIn(token.decode("ascii"), result.stderr + result.stdout)
  609. def test_audit_only_rejects_high_confidence_token(self) -> None:
  610. with tempfile.TemporaryDirectory() as tmp:
  611. temp = Path(tmp)
  612. source = temp / "source"
  613. output = temp / "output"
  614. token = b"aws_" + b"secret_access_key=" + (b"A" * 40)
  615. write_file(source, "docs/leak.txt", token + b"\n")
  616. result = run_packager(source, output, "audit-token", "-AuditOnly")
  617. self.assertNotEqual(result.returncode, 0)
  618. self.assertIn("secret", (result.stderr + result.stdout).lower())
  619. self.assertFalse(output.exists())
  620. self.assertNotIn(token.decode("ascii"), result.stderr + result.stdout)
  621. def test_audit_rejects_secrets_inside_nested_archives(self) -> None:
  622. marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
  623. inner_wheel = zip_bytes({"package/secret.pem": marker})
  624. payloads = {
  625. "test-archives/secret.whl": inner_wheel,
  626. "reference/original/board/secret.tar.gz": tar_gz_bytes({"secret.txt": marker}),
  627. "test-archives/deploy.zip": zip_bytes(
  628. {"wheels/nested-secret.whl": inner_wheel}
  629. ),
  630. }
  631. for relative, payload in payloads.items():
  632. with self.subTest(relative=relative), tempfile.TemporaryDirectory() as tmp:
  633. temp = Path(tmp)
  634. source = temp / "source"
  635. output = temp / "output"
  636. self.assertNotIn(marker, payload)
  637. write_file(source, relative, payload)
  638. result = run_packager(source, output, "archive-secret", "-AuditOnly")
  639. self.assertNotEqual(result.returncode, 0)
  640. self.assertIn("secret", (result.stderr + result.stdout).lower())
  641. self.assertFalse(output.exists())
  642. def test_audit_rejects_secret_zip_renamed_without_archive_extension(self) -> None:
  643. with tempfile.TemporaryDirectory() as tmp:
  644. temp = Path(tmp)
  645. source = temp / "source"
  646. output = temp / "output"
  647. marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
  648. write_file(
  649. source,
  650. "test-archives/release.bin",
  651. zip_bytes({"payload/secret.pem": marker}),
  652. )
  653. result = run_packager(source, output, "renamed-secret", "-AuditOnly")
  654. self.assertNotEqual(result.returncode, 0)
  655. self.assertIn("secret", (result.stderr + result.stdout).lower())
  656. self.assertFalse(output.exists())
  657. def test_write_candidate_never_packages_bytes_swapped_after_archive_scan(self) -> None:
  658. with tempfile.TemporaryDirectory() as tmp:
  659. temp = Path(tmp)
  660. source = temp / "source"
  661. marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
  662. safe = zip_bytes({"payload/data.txt": b"S" * len(marker)})
  663. secret = zip_bytes({"payload/data.txt": marker})
  664. target_size = max(len(safe), len(secret))
  665. def pad_comment(payload: bytes) -> bytes:
  666. buffer = io.BytesIO(payload)
  667. with zipfile.ZipFile(buffer, "a") as archive:
  668. archive.comment = b"P" * (target_size - len(payload))
  669. return buffer.getvalue()
  670. safe = pad_comment(safe)
  671. secret = pad_comment(secret)
  672. self.assertEqual(len(safe), len(secret))
  673. self.assertNotIn(marker, secret)
  674. archive_source = write_file(source, "test-archives/release.zip", safe)
  675. candidates, _, _ = handoff.scan_tree(source)
  676. candidate = next(item for item in candidates if item.absolute == archive_source)
  677. real_snapshot = handoff.snapshot_candidate
  678. swapped = False
  679. @contextmanager
  680. def snapshot_then_swap(
  681. item: handoff.Candidate,
  682. *,
  683. allow_disk: bool,
  684. ) -> object:
  685. nonlocal swapped
  686. with real_snapshot(item, allow_disk=allow_disk) as snapshot:
  687. item.absolute.write_bytes(secret)
  688. os.utime(item.absolute, ns=(item.mtime_ns, item.mtime_ns))
  689. swapped = True
  690. yield snapshot
  691. outer_path = temp / "outer.zip"
  692. caught: handoff.PackagingError | None = None
  693. with mock.patch.object(handoff, "snapshot_candidate", side_effect=snapshot_then_swap):
  694. try:
  695. with zipfile.ZipFile(outer_path, "w") as outer:
  696. handoff.write_candidate(outer, candidate)
  697. except handoff.PackagingError as exc:
  698. caught = exc
  699. self.assertTrue(swapped)
  700. if caught is None:
  701. with zipfile.ZipFile(outer_path) as outer:
  702. embedded = outer.read("CPLD/test-archives/release.zip")
  703. with zipfile.ZipFile(io.BytesIO(embedded)) as nested:
  704. self.assertNotIn(marker, nested.read("payload/data.txt"))
  705. def test_archive_scan_rejects_data_bearing_directories_and_special_zip_types(self) -> None:
  706. cases: list[tuple[str, zipfile.ZipInfo, bytes]] = []
  707. directory = zipfile.ZipInfo("hidden/")
  708. directory.create_system = 3
  709. directory.external_attr = (stat.S_IFDIR | 0o755) << 16
  710. cases.append(("directory", directory, b"hidden data"))
  711. fifo = zipfile.ZipInfo("hidden-fifo")
  712. fifo.create_system = 3
  713. fifo.external_attr = (stat.S_IFIFO | 0o600) << 16
  714. cases.append(("fifo", fifo, b""))
  715. absolute_root = zipfile.ZipInfo("/")
  716. absolute_root.create_system = 3
  717. absolute_root.external_attr = (stat.S_IFDIR | 0o755) << 16
  718. cases.append(("absolute-root", absolute_root, b""))
  719. for label, member, data in cases:
  720. with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp:
  721. source = Path(tmp) / "source"
  722. payload = io.BytesIO()
  723. with zipfile.ZipFile(payload, "w") as archive:
  724. archive.writestr(member, data)
  725. path = write_file(
  726. source,
  727. "test-archives/unsafe.zip",
  728. payload.getvalue(),
  729. )
  730. candidates, _, _ = handoff.scan_tree(source)
  731. candidate = next(item for item in candidates if item.absolute == path)
  732. with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"):
  733. handoff.scan_candidate_archive(candidate)
  734. def test_audit_rejects_secrets_in_tar_metadata(self) -> None:
  735. with tempfile.TemporaryDirectory() as tmp:
  736. temp = Path(tmp)
  737. source = temp / "source"
  738. output = temp / "output"
  739. marker = "-----BEGIN " + "PRIVATE KEY-----\nsecret\n"
  740. payload = io.BytesIO()
  741. with tarfile.open(fileobj=payload, mode="w:gz", format=tarfile.PAX_FORMAT) as archive:
  742. member = tarfile.TarInfo("safe.txt")
  743. member.size = 4
  744. member.pax_headers = {"comment": marker}
  745. archive.addfile(member, io.BytesIO(b"safe"))
  746. self.assertNotIn(marker.encode(), payload.getvalue())
  747. write_file(
  748. source,
  749. "test-archives/metadata.tar.gz",
  750. payload.getvalue(),
  751. )
  752. result = run_packager(source, output, "tar-metadata-secret", "-AuditOnly")
  753. self.assertNotEqual(result.returncode, 0)
  754. self.assertIn("secret", (result.stderr + result.stdout).lower())
  755. self.assertFalse(output.exists())
  756. def test_archive_scan_rejects_unsafe_members_and_resource_exhaustion(self) -> None:
  757. with tempfile.TemporaryDirectory() as tmp:
  758. source = Path(tmp) / "source"
  759. unsafe = write_file(
  760. source,
  761. "reference/original/board/unsafe.zip",
  762. zip_bytes({"../outside.txt": b"unsafe\n"}),
  763. )
  764. candidates, _, _ = handoff.scan_tree(source)
  765. candidate = next(item for item in candidates if item.absolute == unsafe)
  766. with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"):
  767. handoff.scan_candidate_archive(candidate)
  768. with tempfile.TemporaryDirectory() as tmp:
  769. source = Path(tmp) / "source"
  770. oversized = write_file(
  771. source,
  772. "reference/original/board/oversized.zip",
  773. zip_bytes({"large.txt": b"A" * 128}),
  774. )
  775. candidates, _, _ = handoff.scan_tree(source)
  776. candidate = next(item for item in candidates if item.absolute == oversized)
  777. with (
  778. mock.patch.object(handoff, "MAX_ARCHIVE_UNCOMPRESSED_BYTES", 64),
  779. self.assertRaisesRegex(handoff.PackagingError, "archive scan resource limit"),
  780. ):
  781. handoff.scan_candidate_archive(candidate)
  782. def test_high_confidence_token_in_source_path_is_rejected_without_echo(self) -> None:
  783. with tempfile.TemporaryDirectory() as tmp:
  784. temp = Path(tmp)
  785. source = temp / "source"
  786. output = temp / "output"
  787. token = "gh" + "p_" + ("A" * 36)
  788. write_file(source, f"docs/{token}.txt", b"safe content\n")
  789. result = run_packager(source, output, "path-token", "-AuditOnly")
  790. self.assertNotEqual(result.returncode, 0)
  791. self.assertIn("secret", (result.stderr + result.stdout).lower())
  792. self.assertNotIn(token, result.stderr + result.stdout)
  793. self.assertFalse(output.exists())
  794. def test_audit_only_creates_no_artifacts(self) -> None:
  795. self.assertTrue(PACKAGER.is_file(), PACKAGER)
  796. with tempfile.TemporaryDirectory() as tmp:
  797. temp = Path(tmp)
  798. source = temp / "source"
  799. output = temp / "not-created"
  800. write_file(source, "src/rtl/core.v")
  801. write_file(source, "tmp/runtime.bin")
  802. result = run_packager(source, output, "audit-fixture", "-AuditOnly")
  803. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  804. payload = json.loads(result.stdout)
  805. self.assertEqual(payload["status"], "pass")
  806. self.assertEqual(payload["mode"], "audit_only")
  807. self.assertEqual(payload["included_file_count"], 2)
  808. self.assertFalse(output.exists())
  809. def test_audit_uses_delete_on_close_snapshot_instead_of_unbounded_memory(self) -> None:
  810. with tempfile.TemporaryDirectory() as tmp:
  811. source = Path(tmp) / "source"
  812. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  813. candidates, _, _ = handoff.scan_tree(source)
  814. with mock.patch.object(
  815. handoff.io,
  816. "BytesIO",
  817. side_effect=AssertionError("audit used an in-memory whole-file snapshot"),
  818. ):
  819. inventory = handoff.audit_candidates(candidates)
  820. self.assertEqual(len(inventory), 1)
  821. def test_existing_archive_requires_force_and_force_replaces_it(self) -> None:
  822. self.assertTrue(PACKAGER.is_file(), PACKAGER)
  823. with tempfile.TemporaryDirectory() as tmp:
  824. temp = Path(tmp)
  825. source = temp / "source"
  826. output = temp / "output"
  827. write_file(source, "src/rtl/first.v", b"first\n")
  828. first = run_packager(source, output, "replace-fixture")
  829. self.assertEqual(first.returncode, 0, first.stderr + first.stdout)
  830. archive = output / "replace-fixture.zip"
  831. original_hash = hashlib.sha256(archive.read_bytes()).hexdigest()
  832. write_file(source, "src/rtl/second.v", b"second\n")
  833. refused = run_packager(source, output, "replace-fixture")
  834. self.assertNotEqual(refused.returncode, 0)
  835. self.assertIn("already exists", refused.stderr + refused.stdout)
  836. self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), original_hash)
  837. replaced = run_packager(source, output, "replace-fixture", "-ForceOverwrite")
  838. self.assertEqual(replaced.returncode, 0, replaced.stderr + replaced.stdout)
  839. self.assertNotEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), original_hash)
  840. with zipfile.ZipFile(archive) as packaged:
  841. self.assertIn("CPLD/src/rtl/second.v", packaged.namelist())
  842. def test_publish_refuses_target_that_appears_after_validation(self) -> None:
  843. with tempfile.TemporaryDirectory() as tmp:
  844. temp = Path(tmp)
  845. final_zip = temp / "handoff.zip"
  846. final_sidecar = temp / "handoff.zip.sha256.txt"
  847. temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
  848. temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
  849. real_link = os.link
  850. def create_racing_target(source: str | Path, target: str | Path) -> None:
  851. if Path(target) == final_sidecar:
  852. final_sidecar.write_bytes(b"sentinel\n")
  853. real_link(source, target)
  854. with mock.patch.object(handoff.os, "link", side_effect=create_racing_target):
  855. with self.assertRaisesRegex(handoff.PackagingError, "atomically"):
  856. handoff.publish_artifacts_atomically(
  857. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  858. force=False,
  859. )
  860. self.assertFalse(final_zip.exists())
  861. self.assertEqual(final_sidecar.read_bytes(), b"sentinel\n")
  862. def test_force_overwrite_rejects_posix_mode_without_write_bits(self) -> None:
  863. with tempfile.TemporaryDirectory() as tmp:
  864. target = write_file(Path(tmp), "handoff.zip", b"old\n")
  865. current = os.lstat(target)
  866. read_only = SimpleNamespace(
  867. st_mode=stat.S_IFREG | 0o444,
  868. st_ino=current.st_ino,
  869. st_dev=current.st_dev,
  870. st_nlink=current.st_nlink,
  871. st_uid=current.st_uid,
  872. st_gid=current.st_gid,
  873. st_size=current.st_size,
  874. st_atime=current.st_atime,
  875. st_mtime=current.st_mtime,
  876. st_mtime_ns=current.st_mtime_ns,
  877. st_ctime=current.st_ctime,
  878. st_file_attributes=0,
  879. )
  880. with mock.patch.object(handoff.os, "lstat", return_value=read_only):
  881. with self.assertRaisesRegex(handoff.PackagingError, "read-only"):
  882. handoff.validate_publish_targets((target,), force=True)
  883. def test_post_publish_zip_and_sidecar_tampering_rolls_back(self) -> None:
  884. for target_kind in ("zip", "sidecar"):
  885. for force in (False, True):
  886. with (
  887. self.subTest(target_kind=target_kind, force=force),
  888. tempfile.TemporaryDirectory() as tmp,
  889. ):
  890. self._assert_post_publish_tampering_rolls_back(tmp, target_kind, force)
  891. def test_source_content_change_during_publication_rolls_back(self) -> None:
  892. with tempfile.TemporaryDirectory() as tmp:
  893. temp = Path(tmp)
  894. source = temp / "source"
  895. output = temp / "output"
  896. source_file = write_file(source, "src/rtl/core.v", b"first!\n")
  897. candidates, excluded, context = handoff.scan_tree(source)
  898. candidate = candidates[0]
  899. final_zip = output / "source-race-fixture.zip"
  900. final_sidecar = output / "source-race-fixture.zip.sha256.txt"
  901. real_link = os.link
  902. def link_then_mutate(source_path: str | Path, target_path: str | Path) -> None:
  903. real_link(source_path, target_path)
  904. if Path(target_path) == final_sidecar:
  905. source_file.write_bytes(b"second\n")
  906. os.utime(source_file, ns=(candidate.mtime_ns, candidate.mtime_ns))
  907. with mock.patch.object(handoff.os, "link", side_effect=link_then_mutate):
  908. with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
  909. handoff.create_package(
  910. root=source,
  911. output_dir=output,
  912. package_name="source-race-fixture",
  913. force=False,
  914. candidates=candidates,
  915. excluded=excluded,
  916. context=context,
  917. )
  918. self.assertFalse(final_zip.exists())
  919. self.assertFalse(final_sidecar.exists())
  920. def _assert_post_publish_tampering_rolls_back(
  921. self,
  922. tmp: str,
  923. target_kind: str,
  924. force: bool,
  925. ) -> None:
  926. temp = Path(tmp)
  927. source = temp / "source"
  928. output = temp / "output"
  929. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  930. candidates, excluded, context = handoff.scan_tree(source)
  931. final_zip = output / "tamper-fixture.zip"
  932. final_sidecar = output / "tamper-fixture.zip.sha256.txt"
  933. old_zip = b"old zip\n"
  934. old_sidecar = b"old sidecar\n"
  935. if force:
  936. write_file(output, final_zip.name, old_zip)
  937. write_file(output, final_sidecar.name, old_sidecar)
  938. real_link = os.link
  939. def link_then_tamper(source_path: str | Path, target_path: str | Path) -> None:
  940. real_link(source_path, target_path)
  941. if Path(target_path) == final_sidecar:
  942. victim = final_zip if target_kind == "zip" else final_sidecar
  943. victim.write_bytes(b"tampered after publication\n")
  944. with mock.patch.object(handoff.os, "link", side_effect=link_then_tamper):
  945. with self.assertRaises(handoff.PackagingError):
  946. handoff.create_package(
  947. root=source,
  948. output_dir=output,
  949. package_name="tamper-fixture",
  950. force=force,
  951. candidates=candidates,
  952. excluded=excluded,
  953. context=context,
  954. )
  955. if force:
  956. self.assertEqual(final_zip.read_bytes(), old_zip)
  957. self.assertEqual(final_sidecar.read_bytes(), old_sidecar)
  958. else:
  959. self.assertFalse(final_zip.exists())
  960. self.assertFalse(final_sidecar.exists())
  961. def test_atomic_publish_restores_existing_artifacts_when_second_publish_fails(self) -> None:
  962. with tempfile.TemporaryDirectory() as tmp:
  963. temp = Path(tmp)
  964. final_zip = write_file(temp, "handoff.zip", b"old zip\n")
  965. final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
  966. temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
  967. temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
  968. real_link = os.link
  969. def fail_second_publish(source: str | Path, target: str | Path) -> None:
  970. if Path(source) == temp_sidecar and Path(target) == final_sidecar:
  971. raise OSError("simulated publish failure")
  972. real_link(source, target)
  973. with mock.patch.object(handoff.os, "link", side_effect=fail_second_publish):
  974. with self.assertRaisesRegex(handoff.PackagingError, "publish"):
  975. handoff.publish_artifacts_atomically(
  976. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  977. force=True,
  978. )
  979. self.assertEqual(final_zip.read_bytes(), b"old zip\n")
  980. self.assertEqual(final_sidecar.read_bytes(), b"old sidecar\n")
  981. self.assertFalse(any("backup" in path.name for path in temp.iterdir()))
  982. def test_force_overwrite_refuses_existing_directory(self) -> None:
  983. with tempfile.TemporaryDirectory() as tmp:
  984. temp = Path(tmp)
  985. source = temp / "source"
  986. output = temp / "output"
  987. write_file(source, "src/rtl/core.v")
  988. target = output / "directory-fixture.zip"
  989. sentinel = write_file(target, "sentinel.txt", b"keep\n")
  990. result = run_packager(source, output, "directory-fixture", "-ForceOverwrite")
  991. self.assertNotEqual(result.returncode, 0)
  992. self.assertIn("regular file", (result.stderr + result.stdout).lower())
  993. self.assertTrue(target.is_dir())
  994. self.assertEqual(sentinel.read_bytes(), b"keep\n")
  995. self.assertFalse(any("backup" in path.name for path in output.iterdir()))
  996. def test_backup_cleanup_failure_keeps_published_artifacts_and_returns_warnings(self) -> None:
  997. with tempfile.TemporaryDirectory() as tmp:
  998. temp = Path(tmp)
  999. final_zip = write_file(temp, "handoff.zip", b"old zip\n")
  1000. final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
  1001. temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
  1002. temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
  1003. real_unlink = Path.unlink
  1004. def fail_backup_cleanup(path: Path, *args: object, **kwargs: object) -> None:
  1005. if path.name.endswith(".backup"):
  1006. raise PermissionError("simulated backup cleanup failure")
  1007. real_unlink(path, *args, **kwargs)
  1008. with mock.patch.object(Path, "unlink", autospec=True, side_effect=fail_backup_cleanup):
  1009. warnings = handoff.publish_artifacts_atomically(
  1010. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  1011. force=True,
  1012. )
  1013. self.assertEqual(final_zip.read_bytes(), b"new zip\n")
  1014. self.assertEqual(final_sidecar.read_bytes(), b"new sidecar\n")
  1015. self.assertEqual(len(warnings), 2)
  1016. self.assertTrue(all("backup" in warning for warning in warnings))
  1017. for backup in temp.glob("*.backup"):
  1018. real_unlink(backup)
  1019. def test_force_overwrite_refuses_read_only_artifacts_before_mutation(self) -> None:
  1020. attrib = shutil.which("attrib.exe")
  1021. if not attrib:
  1022. self.skipTest("Windows read-only attribute is unavailable")
  1023. with tempfile.TemporaryDirectory() as tmp:
  1024. temp = Path(tmp)
  1025. source = temp / "source"
  1026. output = temp / "output"
  1027. write_file(source, "src/rtl/core.v", b"first\n")
  1028. first = run_packager(source, output, "readonly-fixture")
  1029. self.assertEqual(first.returncode, 0, first.stderr + first.stdout)
  1030. archive = output / "readonly-fixture.zip"
  1031. sidecar = output / "readonly-fixture.zip.sha256.txt"
  1032. original = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in (archive, sidecar)}
  1033. for path in (archive, sidecar):
  1034. subprocess.run([attrib, "+R", str(path)], capture_output=True, check=True)
  1035. try:
  1036. write_file(source, "src/rtl/second.v", b"second\n")
  1037. result = run_packager(source, output, "readonly-fixture", "-ForceOverwrite")
  1038. self.assertNotEqual(result.returncode, 0)
  1039. self.assertIn("read-only", (result.stderr + result.stdout).lower())
  1040. self.assertEqual(
  1041. {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in (archive, sidecar)},
  1042. original,
  1043. )
  1044. self.assertFalse(any("backup" in path.name for path in output.iterdir()))
  1045. finally:
  1046. for path in output.iterdir():
  1047. subprocess.run([attrib, "-R", str(path)], capture_output=True, check=False)
  1048. def test_output_directory_inside_source_is_rejected(self) -> None:
  1049. self.assertTrue(PACKAGER.is_file(), PACKAGER)
  1050. with tempfile.TemporaryDirectory() as tmp:
  1051. source = Path(tmp) / "source"
  1052. write_file(source, "src/rtl/core.v")
  1053. result = run_packager(source, source / "dist", "recursive-fixture")
  1054. self.assertNotEqual(result.returncode, 0)
  1055. self.assertIn("outside SourceRoot", result.stderr + result.stdout)
  1056. self.assertFalse((source / "dist" / "recursive-fixture.zip").exists())
  1057. def test_unknown_junction_fails_closed_without_following_it(self) -> None:
  1058. self.assertTrue(PACKAGER.is_file(), PACKAGER)
  1059. with tempfile.TemporaryDirectory() as tmp:
  1060. temp = Path(tmp)
  1061. source = temp / "source"
  1062. outside = temp / "outside"
  1063. output = temp / "output"
  1064. write_file(source, "src/rtl/core.v")
  1065. write_file(outside, "outside-secret.txt", b"must never be followed\n")
  1066. link = source / "docs" / "external-link"
  1067. link.parent.mkdir(parents=True, exist_ok=True)
  1068. cmd = shutil.which("cmd.exe")
  1069. if not cmd:
  1070. self.skipTest("Windows junction creation is unavailable")
  1071. created = subprocess.run(
  1072. [cmd, "/c", "mklink", "/J", str(link), str(outside)],
  1073. capture_output=True,
  1074. text=True,
  1075. check=False,
  1076. )
  1077. if created.returncode != 0:
  1078. self.skipTest("junction creation is unavailable in this environment")
  1079. try:
  1080. result = run_packager(source, output, "junction-fixture")
  1081. self.assertNotEqual(result.returncode, 0)
  1082. self.assertIn("undeclared reparse point", result.stderr + result.stdout)
  1083. self.assertFalse((output / "junction-fixture.zip").exists())
  1084. finally:
  1085. os.rmdir(link)
  1086. def test_git_junction_is_not_used_for_provenance(self) -> None:
  1087. cmd = shutil.which("cmd.exe")
  1088. if not cmd:
  1089. self.skipTest("Windows junction creation is unavailable")
  1090. with tempfile.TemporaryDirectory() as tmp:
  1091. temp = Path(tmp)
  1092. source = temp / "source"
  1093. outside_git = temp / "outside-git"
  1094. source.mkdir()
  1095. write_file(outside_git, "HEAD", b"ref: refs/heads/main\n")
  1096. link = source / ".git"
  1097. created = subprocess.run(
  1098. [cmd, "/c", "mklink", "/J", str(link), str(outside_git)],
  1099. capture_output=True,
  1100. text=True,
  1101. check=False,
  1102. )
  1103. if created.returncode != 0:
  1104. self.skipTest("junction creation is unavailable in this environment")
  1105. try:
  1106. self.assertIsNone(handoff.resolve_git_dir(source))
  1107. finally:
  1108. os.rmdir(link)
  1109. def test_git_provenance_uses_current_python_and_omits_working_tree_patch(self) -> None:
  1110. with tempfile.TemporaryDirectory() as tmp:
  1111. source = Path(tmp) / "source"
  1112. write_file(source, ".git/HEAD", b"ref: refs/heads/main\n")
  1113. untrusted_python = write_file(
  1114. source,
  1115. ".codex/venv/Scripts/python.exe",
  1116. b"must never be executed\n",
  1117. )
  1118. commands: list[list[str]] = []
  1119. def capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
  1120. del cwd, timeout
  1121. commands.append(command)
  1122. return 0, b"clean\n"
  1123. with (
  1124. mock.patch.object(handoff.shutil, "which", return_value=None),
  1125. mock.patch("importlib.util.find_spec", return_value=object()),
  1126. mock.patch.object(handoff, "run_capture", side_effect=capture),
  1127. ):
  1128. provenance, artifacts = handoff.collect_git_provenance(source)
  1129. self.assertEqual(len(commands), 1)
  1130. self.assertEqual(commands[0][0], sys.executable)
  1131. self.assertIn("-I", commands[0])
  1132. self.assertNotEqual(Path(commands[0][0]), untrusted_python)
  1133. self.assertEqual(provenance["tool"], "dulwich")
  1134. self.assertTrue(provenance["status_captured"])
  1135. self.assertNotIn("diff_captured", provenance)
  1136. self.assertEqual(
  1137. set(artifacts),
  1138. {"CPLD/HANDOFF-METADATA/git-status.txt"},
  1139. )
  1140. def test_git_ref_path_traversal_is_not_followed(self) -> None:
  1141. with tempfile.TemporaryDirectory() as tmp:
  1142. temp = Path(tmp)
  1143. git_dir = temp / "source" / ".git"
  1144. write_file(git_dir, "HEAD", b"ref: ../../outside-ref\n")
  1145. write_file(temp, "outside-ref", b"0123456789abcdef0123456789abcdef01234567\n")
  1146. self.assertEqual(handoff.read_head_metadata(git_dir), (None, None))
  1147. def test_git_status_disables_external_fsmonitor_configuration(self) -> None:
  1148. with tempfile.TemporaryDirectory() as tmp:
  1149. source = Path(tmp) / "source"
  1150. write_file(source, ".git/HEAD", b"0123456789abcdef0123456789abcdef01234567\n")
  1151. commands: list[list[str]] = []
  1152. def capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
  1153. del cwd, timeout
  1154. commands.append(command)
  1155. return 0, b"clean\n"
  1156. with (
  1157. mock.patch.object(handoff.shutil, "which", return_value="git"),
  1158. mock.patch.object(handoff, "run_capture", side_effect=capture),
  1159. ):
  1160. handoff.collect_git_provenance(source)
  1161. self.assertEqual(len(commands), 1)
  1162. self.assertIn("core.fsmonitor=false", commands[0])
  1163. self.assertIn("core.untrackedCache=false", commands[0])
  1164. def test_changxin_version_reader_refuses_reparse_point_before_reading(self) -> None:
  1165. fake_link = SimpleNamespace(
  1166. st_mode=stat.S_IFLNK | 0o777,
  1167. st_file_attributes=int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)),
  1168. )
  1169. with (
  1170. mock.patch.object(Path, "is_file", return_value=True),
  1171. mock.patch.object(handoff.os, "lstat", return_value=fake_link),
  1172. mock.patch.object(Path, "read_text", side_effect=AssertionError("followed link")),
  1173. ):
  1174. context = handoff.load_scan_context(Path("C:/untrusted-source"))
  1175. self.assertIsNone(context.changxin_version)
  1176. def test_candidate_identity_change_is_rejected(self) -> None:
  1177. with tempfile.TemporaryDirectory() as tmp:
  1178. source = Path(tmp) / "source"
  1179. original = write_file(source, "src/rtl/core.v", b"first!\n")
  1180. candidates, _, _ = handoff.scan_tree(source)
  1181. candidate = next(item for item in candidates if item.relative == "src/rtl/core.v")
  1182. replacement = source / "replacement.tmp-source"
  1183. replacement.write_bytes(b"second\n")
  1184. os.utime(replacement, ns=(candidate.mtime_ns, candidate.mtime_ns))
  1185. os.replace(replacement, original)
  1186. self.assertEqual(original.stat().st_size, candidate.size)
  1187. self.assertEqual(original.stat().st_mtime_ns, candidate.mtime_ns)
  1188. archive_path = Path(tmp) / "identity.zip"
  1189. with zipfile.ZipFile(archive_path, "w") as archive:
  1190. with self.assertRaises(handoff.PackagingError):
  1191. handoff.write_candidate(archive, candidate)
  1192. def test_source_tree_changes_before_publication_are_rejected(self) -> None:
  1193. for late_path in ("src/rtl/late.v", "download.part"):
  1194. with self.subTest(late_path=late_path), tempfile.TemporaryDirectory() as tmp:
  1195. temp = Path(tmp)
  1196. source = temp / "source"
  1197. output = temp / "output"
  1198. write_file(source, "src/rtl/core.v")
  1199. candidates, excluded, context = handoff.scan_tree(source)
  1200. verify_archive = handoff.verify_archive
  1201. def verify_and_mutate(*args: object, **kwargs: object) -> None:
  1202. verify_archive(*args, **kwargs)
  1203. write_file(source, late_path)
  1204. caught: handoff.PackagingError | None = None
  1205. with mock.patch.object(handoff, "verify_archive", side_effect=verify_and_mutate):
  1206. try:
  1207. handoff.create_package(
  1208. root=source,
  1209. output_dir=output,
  1210. package_name="race-fixture",
  1211. force=False,
  1212. candidates=candidates,
  1213. excluded=excluded,
  1214. context=context,
  1215. )
  1216. except handoff.PackagingError as exc:
  1217. caught = exc
  1218. self.assertIsNotNone(caught)
  1219. self.assertIn("source tree changed", str(caught).lower())
  1220. self.assertFalse((output / "race-fixture.zip").exists())
  1221. self.assertFalse((output / "race-fixture.zip.sha256.txt").exists())
  1222. self.assertFalse(any(path.suffix == ".partial" for path in output.iterdir()))
  1223. def test_source_content_change_with_restored_metadata_is_rejected(self) -> None:
  1224. with tempfile.TemporaryDirectory() as tmp:
  1225. temp = Path(tmp)
  1226. source = temp / "source"
  1227. output = temp / "output"
  1228. original = write_file(source, "src/rtl/core.v", b"first!\n")
  1229. candidates, excluded, context = handoff.scan_tree(source)
  1230. candidate = candidates[0]
  1231. verify_archive = handoff.verify_archive
  1232. def verify_and_mutate(*args: object, **kwargs: object) -> None:
  1233. verify_archive(*args, **kwargs)
  1234. original.write_bytes(b"second\n")
  1235. os.utime(original, ns=(candidate.mtime_ns, candidate.mtime_ns))
  1236. with mock.patch.object(handoff, "verify_archive", side_effect=verify_and_mutate):
  1237. with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
  1238. handoff.create_package(
  1239. root=source,
  1240. output_dir=output,
  1241. package_name="content-race-fixture",
  1242. force=False,
  1243. candidates=candidates,
  1244. excluded=excluded,
  1245. context=context,
  1246. )
  1247. self.assertFalse((output / "content-race-fixture.zip").exists())
  1248. self.assertFalse((output / "content-race-fixture.zip.sha256.txt").exists())
  1249. def test_source_content_change_during_publication_is_rejected_and_rolled_back(self) -> None:
  1250. with tempfile.TemporaryDirectory() as tmp:
  1251. temp = Path(tmp)
  1252. source = temp / "source"
  1253. output = temp / "output"
  1254. original = write_file(source, "src/rtl/core.v", b"first!\n")
  1255. candidates, excluded, context = handoff.scan_tree(source)
  1256. candidate = candidates[0]
  1257. real_publish = handoff.publish_artifacts_atomically
  1258. def mutate_then_publish(*args: object, **kwargs: object) -> list[str]:
  1259. original.write_bytes(b"second\n")
  1260. os.utime(original, ns=(candidate.mtime_ns, candidate.mtime_ns))
  1261. return real_publish(*args, **kwargs)
  1262. with mock.patch.object(
  1263. handoff,
  1264. "publish_artifacts_atomically",
  1265. side_effect=mutate_then_publish,
  1266. ):
  1267. with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
  1268. handoff.create_package(
  1269. root=source,
  1270. output_dir=output,
  1271. package_name="publish-source-race-fixture",
  1272. force=False,
  1273. candidates=candidates,
  1274. excluded=excluded,
  1275. context=context,
  1276. )
  1277. self.assertFalse((output / "publish-source-race-fixture.zip").exists())
  1278. self.assertFalse(
  1279. (output / "publish-source-race-fixture.zip.sha256.txt").exists()
  1280. )
  1281. def test_temp_archive_metadata_replacement_after_verification_is_rejected(self) -> None:
  1282. with tempfile.TemporaryDirectory() as tmp:
  1283. temp = Path(tmp)
  1284. source = temp / "source"
  1285. output = temp / "output"
  1286. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  1287. candidates, excluded, context = handoff.scan_tree(source)
  1288. real_verify = handoff.verify_archive
  1289. def verify_then_replace(path: object, *args: object, **kwargs: object) -> None:
  1290. real_verify(path, *args, **kwargs)
  1291. temp_zip = next(
  1292. item
  1293. for item in output.glob("*.partial")
  1294. if "sha256" not in item.name
  1295. )
  1296. with zipfile.ZipFile(temp_zip, "r") as archive:
  1297. entries = {name: archive.read(name) for name in archive.namelist()}
  1298. entries["CPLD/HANDOFF-METADATA/manifest.json"] = b'{"status":"tampered"}\n'
  1299. replacement = output / "attacker-replacement.zip"
  1300. with zipfile.ZipFile(replacement, "w", compression=zipfile.ZIP_DEFLATED) as archive:
  1301. for name, payload in entries.items():
  1302. archive.writestr(name, payload)
  1303. os.replace(replacement, temp_zip)
  1304. with mock.patch.object(handoff, "verify_archive", side_effect=verify_then_replace):
  1305. with self.assertRaises(handoff.PackagingError):
  1306. handoff.create_package(
  1307. root=source,
  1308. output_dir=output,
  1309. package_name="temp-race-fixture",
  1310. force=False,
  1311. candidates=candidates,
  1312. excluded=excluded,
  1313. context=context,
  1314. )
  1315. self.assertFalse((output / "temp-race-fixture.zip").exists())
  1316. self.assertFalse((output / "temp-race-fixture.zip.sha256.txt").exists())
  1317. def test_partial_cleanup_errors_are_reported(self) -> None:
  1318. attrib = shutil.which("attrib.exe")
  1319. if not attrib:
  1320. self.skipTest("Windows read-only attribute is unavailable")
  1321. with tempfile.TemporaryDirectory() as tmp:
  1322. partial = write_file(Path(tmp), "archive.partial")
  1323. subprocess.run([attrib, "+R", str(partial)], capture_output=True, check=True)
  1324. try:
  1325. with self.assertRaisesRegex(handoff.PackagingError, "partial"):
  1326. handoff.remove_partial_artifacts((partial,))
  1327. finally:
  1328. subprocess.run([attrib, "-R", str(partial)], capture_output=True, check=False)
  1329. partial.unlink(missing_ok=True)
  1330. def test_publish_rollback_attempts_all_restores_and_reports_recovery_paths(self) -> None:
  1331. with tempfile.TemporaryDirectory() as tmp:
  1332. temp = Path(tmp)
  1333. final_zip = write_file(temp, "handoff.zip", b"old zip\n")
  1334. final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
  1335. temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
  1336. temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
  1337. real_link = os.link
  1338. real_replace = os.replace
  1339. restored: list[Path] = []
  1340. def fail_second_publish(source_path: str | Path, target_path: str | Path) -> None:
  1341. if Path(source_path) == temp_sidecar:
  1342. raise OSError("simulated publish failure")
  1343. real_link(source_path, target_path)
  1344. def fail_one_restore(source_path: str | Path, target_path: str | Path) -> None:
  1345. source = Path(source_path)
  1346. target = Path(target_path)
  1347. if source.name.endswith(".backup"):
  1348. restored.append(target)
  1349. if target == final_zip:
  1350. raise OSError("simulated restore failure")
  1351. real_replace(source_path, target_path)
  1352. with (
  1353. mock.patch.object(handoff.os, "link", side_effect=fail_second_publish),
  1354. mock.patch.object(handoff.os, "replace", side_effect=fail_one_restore),
  1355. self.assertRaisesRegex(handoff.PackagingError, "rollback was incomplete") as caught,
  1356. ):
  1357. handoff.publish_artifacts_atomically(
  1358. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  1359. force=True,
  1360. )
  1361. self.assertEqual(set(restored), {final_zip, final_sidecar})
  1362. self.assertEqual(final_sidecar.read_bytes(), b"old sidecar\n")
  1363. self.assertIn("manual recovery paths", str(caught.exception))
  1364. self.assertTrue(any(path.name.endswith(".backup") for path in temp.iterdir()))
  1365. def test_create_package_returns_warning_when_published_temp_cleanup_fails(self) -> None:
  1366. with tempfile.TemporaryDirectory() as tmp:
  1367. temp = Path(tmp)
  1368. source = temp / "source"
  1369. output = temp / "output"
  1370. write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
  1371. candidates, excluded, context = handoff.scan_tree(source)
  1372. real_unlink = Path.unlink
  1373. def fail_partial_cleanup(path: Path, *args: object, **kwargs: object) -> None:
  1374. if path.name.endswith(".partial"):
  1375. raise PermissionError("simulated temporary cleanup failure")
  1376. real_unlink(path, *args, **kwargs)
  1377. with mock.patch.object(
  1378. Path,
  1379. "unlink",
  1380. autospec=True,
  1381. side_effect=fail_partial_cleanup,
  1382. ):
  1383. result = handoff.create_package(
  1384. root=source,
  1385. output_dir=output,
  1386. package_name="cleanup-warning",
  1387. force=False,
  1388. candidates=candidates,
  1389. excluded=excluded,
  1390. context=context,
  1391. )
  1392. self.assertEqual(result["status"], "pass")
  1393. self.assertEqual(len(result["warnings"]), 2)
  1394. self.assertTrue((output / "cleanup-warning.zip").is_file())
  1395. self.assertTrue((output / "cleanup-warning.zip.sha256.txt").is_file())
  1396. for partial in output.glob("*.partial"):
  1397. real_unlink(partial)
  1398. def test_windows_reserved_device_names_are_rejected(self) -> None:
  1399. for relative in ("CON", "docs/aux.txt", "reports/COM1.log", "LPT9"):
  1400. with self.subTest(relative=relative):
  1401. with self.assertRaises(handoff.PackagingError):
  1402. handoff.windows_collision_key(relative)
  1403. def test_windows_unsafe_path_components_are_rejected(self) -> None:
  1404. unsafe = (
  1405. "docs/trailing.",
  1406. "docs/trailing ",
  1407. "docs/question?.txt",
  1408. "docs/star*.txt",
  1409. "docs/less<.txt",
  1410. "docs/greater>.txt",
  1411. "docs/pipe|.txt",
  1412. 'docs/quote".txt',
  1413. "docs/control\x1f.txt",
  1414. )
  1415. for relative in unsafe:
  1416. with self.subTest(relative=relative):
  1417. with self.assertRaises(handoff.PackagingError):
  1418. handoff.normalize_relative(relative.split("/"))
  1419. with self.assertRaisesRegex(handoff.PackagingError, "UTF-8"):
  1420. handoff.normalize_relative(["docs", "bad\udcff.txt"])
  1421. def test_windows_reserved_or_trailing_package_names_are_rejected(self) -> None:
  1422. with tempfile.TemporaryDirectory() as tmp:
  1423. temp = Path(tmp)
  1424. source = temp / "source"
  1425. output = temp / "output"
  1426. write_file(source, "src/rtl/core.v")
  1427. for package_name in ("CON", "COM1", "trailing."):
  1428. with self.subTest(package_name=package_name):
  1429. result = run_packager(source, output, package_name, "-AuditOnly")
  1430. self.assertNotEqual(result.returncode, 0)
  1431. self.assertIn("PackageName", result.stderr + result.stdout)
  1432. def test_wrapper_and_readme_require_python_311_or_newer(self) -> None:
  1433. wrapper = PACKAGER.read_text(encoding="utf-8-sig")
  1434. readme = (ROOT / "docs/agent-handoff-packaging.zh-CN.md").read_text(encoding="utf-8-sig")
  1435. self.assertIn("3.11", wrapper)
  1436. self.assertIn("3.11", readme)
  1437. # Linux authority entry is python -B; isolation flags remain on the PS1 wrapper.
  1438. self.assertIn("python -B package_for_agent_analysis.py", readme)
  1439. self.assertIn("GetFinalPathNameByHandle", wrapper)
  1440. self.assertNotIn(".codex\\venv\\Scripts\\python.exe", wrapper)
  1441. for flag in ("-I", "-S", "-B"):
  1442. with self.subTest(flag=flag):
  1443. self.assertIn(flag, wrapper)
  1444. self.assertIn("SourceRoot", wrapper)
  1445. self.assertIn("source-root", readme.casefold())
  1446. for marker in (
  1447. "-AuditOnly",
  1448. "-OutputDir",
  1449. "-ForceOverwrite",
  1450. "Get-FileHash",
  1451. "tmp/photos",
  1452. "tmp/pdfs",
  1453. "clean-runtime",
  1454. "编译产物",
  1455. "Deflate",
  1456. ):
  1457. with self.subTest(marker=marker):
  1458. self.assertIn(marker, readme)
  1459. self.assertIn("100,000", readme)
  1460. self.assertIn("8 GiB", readme)
  1461. self.assertIn("外", readme)
  1462. if __name__ == "__main__":
  1463. unittest.main()