| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601 |
- #!/usr/bin/env python3
- """Integration tests for the agent analysis handoff packager."""
- from __future__ import annotations
- import hashlib
- import io
- import json
- import os
- import shutil
- import stat
- import subprocess
- import sys
- import tarfile
- import tempfile
- import unittest
- import zipfile
- from contextlib import contextmanager
- from pathlib import Path
- from types import SimpleNamespace
- from unittest import mock
- ROOT = Path(__file__).resolve().parents[2]
- PACKAGER = ROOT / "tools" / "package_agent_handoff.ps1"
- PACKAGER_CORE = ROOT / "tools" / "package_agent_handoff.py"
- sys.path.insert(0, str(ROOT / "tools"))
- import package_agent_handoff as handoff # noqa: E402
- def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
- path = root / Path(relative)
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(data)
- return path
- def zip_bytes(entries: dict[str, bytes]) -> bytes:
- payload = io.BytesIO()
- with zipfile.ZipFile(payload, "w", compression=zipfile.ZIP_DEFLATED) as archive:
- for name, data in entries.items():
- archive.writestr(name, data)
- return payload.getvalue()
- def stored_zip_bytes(entries: dict[str, bytes]) -> bytes:
- payload = io.BytesIO()
- with zipfile.ZipFile(payload, "w", compression=zipfile.ZIP_STORED) as archive:
- for name, data in entries.items():
- archive.writestr(name, data)
- return payload.getvalue()
- def tar_gz_bytes(entries: dict[str, bytes]) -> bytes:
- payload = io.BytesIO()
- with tarfile.open(fileobj=payload, mode="w:gz") as archive:
- for name, data in entries.items():
- info = tarfile.TarInfo(name)
- info.size = len(data)
- info.mtime = 0
- archive.addfile(info, io.BytesIO(data))
- return payload.getvalue()
- def run_packager(
- source_root: Path,
- output_dir: Path,
- package_name: str,
- *extra: str,
- env: dict[str, str] | None = None,
- ) -> subprocess.CompletedProcess[str]:
- powershell = shutil.which("powershell.exe")
- if powershell:
- command = [
- powershell,
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(PACKAGER),
- "-SourceRoot",
- str(source_root),
- "-OutputDir",
- str(output_dir),
- "-PackageName",
- package_name,
- *extra,
- ]
- else:
- option_map = {
- "-AuditOnly": "--audit-only",
- "-ForceOverwrite": "--force-overwrite",
- }
- command = [
- sys.executable,
- str(PACKAGER_CORE),
- "--source-root",
- str(source_root),
- "--output-dir",
- str(output_dir),
- "--package-name",
- package_name,
- *(option_map[item] for item in extra),
- ]
- return subprocess.run(
- command,
- cwd=ROOT,
- capture_output=True,
- text=True,
- check=False,
- env=env,
- )
- class AgentHandoffPackageTests(unittest.TestCase):
- maxDiff = None
- def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
- command = handoff.build_7zip_create_command(
- Path("package.zip"),
- Path("staging"),
- )
- self.assertEqual(command[:4], ["a", "-tzip", "-mm=Deflate", "-mx=9"])
- self.assertNotIn("LZMA", " ".join(command).upper())
- def test_create_package_falls_back_to_zipfile_without_7zip(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
- file_stat = os.lstat(source)
- candidate = handoff.Candidate(
- absolute=source,
- relative="src/core.v",
- size=file_stat.st_size,
- mtime_ns=file_stat.st_mtime_ns,
- device=int(file_stat.st_dev),
- inode=int(file_stat.st_ino),
- mode=int(file_stat.st_mode),
- )
- with mock.patch.object(handoff, "find_7z", return_value=None):
- result = handoff.create_package(
- root=temp / "source",
- output_dir=temp / "output",
- package_name="no-7z",
- force=False,
- candidates=[candidate],
- excluded=[],
- context=handoff.ScanContext(None),
- )
- self.assertEqual(result["status"], "pass")
- zip_path = Path(result["package_zip"])
- self.assertTrue(zip_path.is_file())
- with zipfile.ZipFile(zip_path, "r") as archive:
- names = set(archive.namelist())
- self.assertIn(f"{handoff.ARCHIVE_ROOT}/src/core.v", names)
- self.assertIn(f"{handoff.METADATA_ROOT}/manifest.json", names)
- @unittest.skipUnless(os.name == "nt", "Windows executable mode semantics are required")
- def test_open_candidate_accepts_windows_executable_mode_disagreement(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp)
- path = write_file(source, "run.bat", b"@echo off\r\n")
- file_stat = os.lstat(path)
- candidate = handoff.Candidate(
- absolute=path,
- relative="run.bat",
- size=file_stat.st_size,
- mtime_ns=file_stat.st_mtime_ns,
- device=int(file_stat.st_dev),
- inode=int(file_stat.st_ino),
- mode=int(file_stat.st_mode),
- )
- with handoff.open_candidate(candidate) as source_stream:
- self.assertEqual(source_stream.read(), b"@echo off\r\n")
- def test_wrapper_ignores_python_startup_hooks(self) -> None:
- powershell = shutil.which("powershell.exe")
- if not powershell:
- self.skipTest("Windows PowerShell is unavailable")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- hooks = temp / "python-hooks"
- marker = temp / "sitecustomize-executed.txt"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- write_file(
- hooks,
- "sitecustomize.py",
- (
- "from pathlib import Path\n"
- f"Path({str(marker)!r}).write_text('executed', encoding='utf-8')\n"
- ).encode("utf-8"),
- )
- env = os.environ.copy()
- env["PYTHONPATH"] = str(hooks)
- env["PYTHONSTARTUP"] = str(hooks / "sitecustomize.py")
- result = run_packager(
- source,
- output,
- "startup-isolation-fixture",
- "-AuditOnly",
- env=env,
- )
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- self.assertFalse(marker.exists(), "wrapper executed source-controlled startup code")
- payload = json.loads(result.stdout)
- self.assertEqual(payload["status"], "pass")
- self.assertEqual(payload["mode"], "audit_only")
- def test_wrapper_skips_python_candidates_inside_repo_or_source_root(self) -> None:
- powershell = shutil.which("powershell.exe")
- py_launcher = shutil.which("py.exe") or shutil.which("py")
- if not powershell or not py_launcher:
- self.skipTest("Windows PowerShell and the external Python launcher are required")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- wrapper_repo = temp / "wrapper-repo"
- tools = wrapper_repo / "tools"
- tools.mkdir(parents=True)
- shutil.copy2(PACKAGER, tools / PACKAGER.name)
- shutil.copy2(PACKAGER_CORE, tools / PACKAGER_CORE.name)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- for candidate_scope in ("repo", "source"):
- with self.subTest(candidate_scope=candidate_scope):
- candidate_root = wrapper_repo if candidate_scope == "repo" else source
- candidate_dir = (
- candidate_root / "candidate-bin"
- if candidate_scope == "repo"
- else candidate_root / ".venv" / "Scripts"
- )
- candidate_dir.mkdir(parents=True, exist_ok=True)
- marker = temp / f"{candidate_scope}-python-executed.txt"
- fake_python = candidate_dir / "python.cmd"
- fake_python.write_text(
- f'@echo invoked>>"{marker}"\n@exit /b 0\n',
- encoding="ascii",
- )
- env = os.environ.copy()
- env["PATH"] = os.pathsep.join(
- (
- str(candidate_dir),
- str(Path(py_launcher).parent),
- str(Path(powershell).parent),
- )
- )
- result = subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(tools / PACKAGER.name),
- "-SourceRoot",
- str(source),
- "-OutputDir",
- str(output),
- "-PackageName",
- f"{candidate_scope}-candidate-fixture",
- "-AuditOnly",
- ],
- cwd=wrapper_repo,
- capture_output=True,
- text=True,
- check=False,
- env=env,
- )
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- self.assertFalse(
- marker.exists(),
- f"wrapper executed Python candidate inside {candidate_scope}",
- )
- payload = json.loads(result.stdout)
- self.assertEqual(payload["status"], "pass")
- self.assertEqual(payload["mode"], "audit_only")
- def test_wrapper_resolves_junction_source_root_before_python_selection(self) -> None:
- powershell = shutil.which("powershell.exe")
- py_launcher = shutil.which("py.exe") or shutil.which("py")
- command_prompt = shutil.which("cmd.exe")
- if not powershell or not py_launcher or not command_prompt:
- self.skipTest("Windows PowerShell, cmd, and the external Python launcher are required")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- wrapper_repo = temp / "wrapper-repo"
- tools = wrapper_repo / "tools"
- tools.mkdir(parents=True)
- shutil.copy2(PACKAGER, tools / PACKAGER.name)
- shutil.copy2(PACKAGER_CORE, tools / PACKAGER_CORE.name)
- source = temp / "actual-source"
- source_alias = temp / "source-alias"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- candidate_dir = source / ".venv" / "Scripts"
- candidate_dir.mkdir(parents=True)
- marker = temp / "junction-python-executed.txt"
- (candidate_dir / "python.cmd").write_text(
- f'@echo invoked>>"{marker}"\n@exit /b 0\n',
- encoding="ascii",
- )
- junction = subprocess.run(
- [command_prompt, "/d", "/c", "mklink", "/J", str(source_alias), str(source)],
- capture_output=True,
- text=True,
- check=False,
- )
- if junction.returncode != 0:
- self.skipTest(f"unable to create a directory junction: {junction.stderr}")
- try:
- env = os.environ.copy()
- env["PATH"] = os.pathsep.join(
- (
- str(candidate_dir),
- str(Path(py_launcher).parent),
- str(Path(powershell).parent),
- )
- )
- result = subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(tools / PACKAGER.name),
- "-SourceRoot",
- str(source_alias),
- "-OutputDir",
- str(output),
- "-PackageName",
- "junction-source-fixture",
- "-AuditOnly",
- ],
- cwd=wrapper_repo,
- capture_output=True,
- text=True,
- check=False,
- env=env,
- )
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- self.assertFalse(marker.exists(), "wrapper executed Python inside junction target")
- payload = json.loads(result.stdout)
- self.assertEqual(payload["status"], "pass")
- self.assertEqual(payload["mode"], "audit_only")
- finally:
- if os.path.lexists(source_alias):
- os.rmdir(source_alias)
- def test_packager_keeps_analysis_inputs_and_removes_only_declared_runtime_content(self) -> None:
- self.assertTrue(PACKAGER.is_file(), PACKAGER)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- included = {
- "AGENTS.md": b"project contract\n",
- ".gitignore": b"tmp/\n",
- "config/.env.template": b"DEVICE_PORT=COM3\n",
- "src/rtl/core.v": b"module core; endmodule\n",
- "docs/需求说明.md": "完整需求\n".encode("utf-8"),
- "tests/fixtures/failure.log": b"expected failure fixture\n",
- "receipts/programmer/bitwriter-stdout.log": b"evidence\n",
- "receipts/fail.json": b'{"status":"fail"}\n',
- "reference/original/board/vendor-original.zip": zip_bytes(
- {"vendor/readme.txt": b"raw original archive\n"}
- ),
- "reference/original/board/public-ca.pem": b"-----BEGIN CERTIFICATE-----\npublic\n-----END CERTIFICATE-----\n",
- "reference/original/local_archives/private.zip": zip_bytes(
- {"private/readme.txt": b"original archive\n"}
- ),
- "td/project/active_project.al": b"active TD project input\n",
- "td/project/active_project.cwc": b"active ChipWatcher project input\n",
- "td/project/assets/test_runs/keep.al": b"nested active project input\n",
- "tools/computer_use/README.md": b"future active verification tool\n",
- "tmp/mutation/remove_force_off.json": b'{"mutation":"remove_force_off"}\n',
- "tmp/mutation/remove_force_off.patch": b"mutation patch evidence\n",
- "tmp/resource_audit/profile/probe.v": b"module probe; endmodule\n",
- "tmp/resource_audit/profile/generated.f": b"rtl/core.v\n",
- "tmp/resource_audit/profile/generated.tsm": b"generated timing model\n",
- "tmp/pwm_executor_probe/profile/run.tcl": b"# probe definition\n",
- "tmp/pwm_executor_probe/profile/generated.f": b"rtl/pwm.v\n",
- "tmp/pwm_executor_probe/profile/generated.tsm": b"generated timing model\n",
- "tmp/debug_bundle/offline/agent_context.md": b"debug context\n",
- "tmp/formal_runs/fault/trace.vcd": b"$date\n",
- "tmp/formal_runs/fault/config.sby": b"[options]\nmode prove\n",
- "tmp/formal_runs/fault/model/design.json": b'{"formal":"model"}\n',
- "tmp/formal_runs/fault/logfile.txt": b"formal proof log\n",
- "tmp/formal_runs/fault/PASS": b"pass\n",
- "tmp/photos/board-connectors.jpg": b"real board photo\n",
- "tmp/pdfs/schematic-page.png": b"schematic crop\n",
- "tmp/new-analysis/evidence.json": b'{"status":"observed"}\n',
- "tools/changxin-temp-uart/pyproject.toml": b'[project]\nname="changxin-temp-uart"\nversion="0.1.9"\n',
- "notes/build-notes.txt": b"not a build directory\n",
- "mytmp/keep.txt": b"not the top-level tmp directory\n",
- }
- for relative, data in included.items():
- write_file(source, relative, data)
- hidden = write_file(source, "docs/hidden-contract.txt", b"hidden but required\n")
- attrib = shutil.which("attrib.exe")
- if attrib:
- subprocess.run([attrib, "+H", str(hidden)], capture_output=True, check=True)
- included["docs/hidden-contract.txt"] = b"hidden but required\n"
- deprecated_workspace_path = "/".join(("workspace", "old-study.v"))
- excluded = [
- ".git/objects/dead-secret",
- ".codegraph/codegraph.db",
- ".codex/venv/Lib/site-packages/cache.py",
- ".codex/session-state.json",
- ".codex/cleanup_manifests/cleanup.json",
- ".codex/reports/report.tmp",
- ".omo/run-continuation/session.json",
- ".hypothesis/constants/cache",
- ".pytest_cache/v/cache/nodeids",
- "src/rtl/__pycache__/core.cpython-312.pyc",
- "tmp/rtl_sim/core.vvp",
- "tmp/cocotb/pid_core_smoke/sim.vvp",
- "tmp/detector_selftest/bad_icarus.vvp",
- "tmp/toolchain_probe/td_probe.log",
- "tmp/resource_audit/profile/stale.db",
- "tmp/resource_audit/profile/postgate.area",
- "tmp/pwm_executor_probe/profile/gate.qor",
- "tmp/resource_audit/profile/td_user_env/temp/state.bin",
- "tmp/pwm_executor_probe/profile/td_user_env/temp/state.bin",
- "tmp/debug_bundle/offline/fw.bit",
- "td/build/profile/syn/profile_gate.db",
- "td/build/profile/syn/gate.qor",
- "td/build/profile/phy/final_timing.rpt",
- "td/build/profile/syn/td_20260711_120000.log",
- "td/build/profile/syn/source-manifest.json",
- "td/build/profile/syn/profile_elaboration_plan.json",
- "td/build/profile/phy/profile.bit",
- "td/build/profile/syn/src/rtl/core.v",
- "td/build/profile/syn/constraints/pins.adc",
- "td/build/profile/syn/profile.prj",
- "td/build/profile/syn/profile.tcl",
- "td/build/profile/syn/td_user_env/temp/state.bin",
- "td/project/profile_Runs/run.log",
- "td/project/log/runtime.log",
- "td/project/.lock.f",
- "td/project/.recent_user_depot.ini",
- "td/td_20260711_120000.log",
- "td/td_20260711_120000.logw",
- "receipts/local/live.json",
- "reference/original/local_archives/Anlogic.lic",
- "reference/original/vendor/installer.exe",
- deprecated_workspace_path,
- "dist/old-package.zip",
- "_archive/old-source.v",
- "ANLOGIC_CD/setup.exe",
- "log/bw_runtime.log",
- "unused/note.txt",
- "tools/changxin-temp-uart/build/lib/copy.py",
- "tools/changxin-temp-uart/changxin_temp_uart.egg-info/PKG-INFO",
- "tools/changxin-temp-uart/pyinstaller-build/cache.bin",
- "tools/changxin-temp-uart/pyinstaller-spec/app.spec",
- "tools/changxin-temp-uart/pyinstaller-entry.py",
- "tools/changxin-temp-uart/linux-onefile-build.json",
- "tools/changxin-temp-uart/changxin-temp-uart-static",
- "atomic-receipt.json.tmp",
- "download.part",
- "minidump-123.dmp",
- "tmp_last_pkg1.txt",
- "a.out",
- ".env",
- "id_rsa",
- "signing.key",
- "certificate.pfx",
- ".netrc",
- ".pypirc",
- ".npmrc",
- ".git-credentials",
- ".aws/credentials",
- ".docker/config.json",
- "receipts/incomplete.json",
- "tests/cocotb/results.xml",
- ".codex/reports/chipwatcher.json",
- "tmp/new-analysis/host-crash.dmp",
- "tmp/new-analysis/interrupted.partial",
- "tools/changxin-temp-uart/dist/changxin-temp-uart-0.1.2-release.zip",
- "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.8-py3-none-any.whl",
- "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.9-py3-none-any.whl",
- "tools/changxin-temp-uart/dist/changxin_temp_uart-0.1.9.tar.gz",
- "tools/changxin-temp-uart/dist/changxin-temp-uart-0.1.9-deploy.zip",
- "tools/changxin-temp-uart/dist/pyserial-3.5-py2.py3-none-any.whl",
- ]
- for relative in excluded:
- data = b"null\r\n" if relative == "receipts/incomplete.json" else b"fixture\n"
- write_file(source, relative, data)
- result = run_packager(source, output, "fixture-handoff")
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- zip_path = output / "fixture-handoff.zip"
- sidecar = output / "fixture-handoff.zip.sha256.txt"
- self.assertTrue(zip_path.is_file())
- self.assertTrue(sidecar.is_file())
- self.assertEqual(
- sidecar.read_text(encoding="ascii").split()[0],
- hashlib.sha256(zip_path.read_bytes()).hexdigest(),
- )
- with zipfile.ZipFile(zip_path) as archive:
- names = archive.namelist()
- name_set = set(names)
- self.assertEqual(len(names), len(name_set))
- self.assertTrue(all("\\" not in name for name in names))
- for relative, data in included.items():
- entry = f"CPLD/{relative}"
- self.assertIn(entry, name_set)
- self.assertEqual(archive.read(entry), data)
- for relative in excluded:
- self.assertNotIn(f"CPLD/{relative}", name_set)
- metadata_root = "CPLD/HANDOFF-METADATA"
- manifest = json.loads(archive.read(f"{metadata_root}/manifest.json").decode("utf-8"))
- exclusions = json.loads(archive.read(f"{metadata_root}/exclusions.json").decode("utf-8"))
- inventory = json.loads(archive.read(f"{metadata_root}/sha256-inventory.json").decode("utf-8"))
- self.assertEqual(manifest["schema"], "cpld-agent-handoff-v1")
- self.assertEqual(manifest["status"], "pass")
- self.assertEqual(manifest["package_name"], "fixture-handoff")
- self.assertEqual(
- manifest["archive_scan_limits"],
- {
- "max_depth": 3,
- "max_members": 100_000,
- "max_uncompressed_bytes": 8 * 1024 * 1024 * 1024,
- "source_file_size_limit": None,
- },
- )
- self.assertNotIn(str(source), json.dumps(manifest, ensure_ascii=False))
- self.assertEqual(
- [item["path"] for item in inventory["inventory"]],
- sorted(included, key=handoff.windows_collision_key),
- )
- for item in inventory["inventory"]:
- self.assertEqual(item["sha256"], hashlib.sha256(included[item["path"]]).hexdigest())
- self.assertEqual(item["size"], len(included[item["path"]]))
- excluded_paths = {item["path"] for item in exclusions["excluded"]}
- excluded_rules = {item["rule"] for item in exclusions["excluded"]}
- self.assertIn("tmp/rtl_sim", excluded_paths)
- self.assertIn("td/build", excluded_paths)
- self.assertNotIn("reference/original/local_archives", excluded_paths)
- self.assertIn(".codex", excluded_paths)
- self.assertNotIn("tmp_runtime_non_evidence", excluded_rules)
- self.assertNotIn("obsolete_or_third_party_changxin_release", excluded_rules)
- def test_generated_metadata_rejects_private_key_content(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- archive_path = Path(tmp) / "metadata.zip"
- marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
- with zipfile.ZipFile(archive_path, "w") as archive:
- with self.assertRaises(handoff.PackagingError):
- handoff.write_bytes_entry(
- archive,
- "CPLD/HANDOFF-METADATA/working-tree.patch",
- marker,
- )
- def test_generated_metadata_rejects_high_confidence_token(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- archive_path = Path(tmp) / "metadata.zip"
- token = b"aws_" + b"secret_access_key=" + (b"A" * 40)
- with zipfile.ZipFile(archive_path, "w") as archive:
- with self.assertRaises(handoff.PackagingError):
- handoff.write_bytes_entry(
- archive,
- "CPLD/HANDOFF-METADATA/git-status.txt",
- b"M docs/" + token + b".txt\n",
- )
- def test_secret_scanner_covers_supported_tokens_and_chunk_boundaries(self) -> None:
- tokens = {
- "github_classic": b"gh" + b"p_" + (b"A" * 36),
- "github_fine_grained": b"github_" + b"pat_" + (b"A" * 22) + b"_" + (b"B" * 59),
- "aws_secret_access_key": b"aws_" + b"secret_access_key = " + (b"A" * 40),
- "aws_session_token": b"aws_" + b"session_token: " + (b"A" * 80),
- "openai_project": b"sk-" + b"proj-" + (b"A" * 48),
- "slack_bot": b"xox" + b"b-" + b"123456789012-" + (b"A" * 32),
- }
- for name, token in tokens.items():
- with self.subTest(name=name):
- with self.assertRaises(handoff.PackagingError):
- handoff.scan_secret_markers(token, b"", f"docs/{name}.txt")
- token = b"gh" + b"o_" + (b"C" * 36)
- first = b"prefix:" + token[:9]
- tail = handoff.scan_secret_markers(first, b"", "docs/chunked.txt")
- with self.assertRaises(handoff.PackagingError):
- handoff.scan_secret_markers(token[9:] + b":suffix", tail, "docs/chunked.txt")
- handoff.scan_secret_markers(b"ghp_EXAMPLE", b"", "docs/example.txt")
- handoff.scan_secret_markers(b"AK" + b"IAIOSFODNN7EXAMPLE", b"", "docs/aws-example.txt")
- def test_audit_only_rejects_private_key_content(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
- write_file(source, "docs/leak.txt", marker)
- result = run_packager(source, output, "audit-secret", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("private key", (result.stderr + result.stdout).lower())
- self.assertFalse(output.exists())
- def test_high_confidence_token_is_rejected_without_archive(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- token = b"ghp_" + (b"A" * 36)
- write_file(source, "docs/leak.txt", token + b"\n")
- result = run_packager(source, output, "token-secret")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertFalse((output / "token-secret.zip").exists())
- self.assertNotIn(token.decode("ascii"), result.stderr + result.stdout)
- def test_audit_only_rejects_high_confidence_token(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- token = b"aws_" + b"secret_access_key=" + (b"A" * 40)
- write_file(source, "docs/leak.txt", token + b"\n")
- result = run_packager(source, output, "audit-token", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertFalse(output.exists())
- self.assertNotIn(token.decode("ascii"), result.stderr + result.stdout)
- def test_audit_rejects_secrets_inside_nested_archives(self) -> None:
- marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
- inner_wheel = zip_bytes({"package/secret.pem": marker})
- payloads = {
- "test-archives/secret.whl": inner_wheel,
- "reference/original/board/secret.tar.gz": tar_gz_bytes({"secret.txt": marker}),
- "test-archives/deploy.zip": zip_bytes(
- {"wheels/nested-secret.whl": inner_wheel}
- ),
- }
- for relative, payload in payloads.items():
- with self.subTest(relative=relative), tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- self.assertNotIn(marker, payload)
- write_file(source, relative, payload)
- result = run_packager(source, output, "archive-secret", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertFalse(output.exists())
- def test_audit_rejects_secret_zip_renamed_without_archive_extension(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
- write_file(
- source,
- "test-archives/release.bin",
- zip_bytes({"payload/secret.pem": marker}),
- )
- result = run_packager(source, output, "renamed-secret", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertFalse(output.exists())
- def test_write_candidate_never_packages_bytes_swapped_after_archive_scan(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- marker = b"-----BEGIN " + b"PRIVATE KEY-----\nsecret\n"
- safe = zip_bytes({"payload/data.txt": b"S" * len(marker)})
- secret = zip_bytes({"payload/data.txt": marker})
- target_size = max(len(safe), len(secret))
- def pad_comment(payload: bytes) -> bytes:
- buffer = io.BytesIO(payload)
- with zipfile.ZipFile(buffer, "a") as archive:
- archive.comment = b"P" * (target_size - len(payload))
- return buffer.getvalue()
- safe = pad_comment(safe)
- secret = pad_comment(secret)
- self.assertEqual(len(safe), len(secret))
- self.assertNotIn(marker, secret)
- archive_source = write_file(source, "test-archives/release.zip", safe)
- candidates, _, _ = handoff.scan_tree(source)
- candidate = next(item for item in candidates if item.absolute == archive_source)
- real_snapshot = handoff.snapshot_candidate
- swapped = False
- @contextmanager
- def snapshot_then_swap(
- item: handoff.Candidate,
- *,
- allow_disk: bool,
- ) -> object:
- nonlocal swapped
- with real_snapshot(item, allow_disk=allow_disk) as snapshot:
- item.absolute.write_bytes(secret)
- os.utime(item.absolute, ns=(item.mtime_ns, item.mtime_ns))
- swapped = True
- yield snapshot
- outer_path = temp / "outer.zip"
- caught: handoff.PackagingError | None = None
- with mock.patch.object(handoff, "snapshot_candidate", side_effect=snapshot_then_swap):
- try:
- with zipfile.ZipFile(outer_path, "w") as outer:
- handoff.write_candidate(outer, candidate)
- except handoff.PackagingError as exc:
- caught = exc
- self.assertTrue(swapped)
- if caught is None:
- with zipfile.ZipFile(outer_path) as outer:
- embedded = outer.read("CPLD/test-archives/release.zip")
- with zipfile.ZipFile(io.BytesIO(embedded)) as nested:
- self.assertNotIn(marker, nested.read("payload/data.txt"))
- def test_archive_scan_rejects_data_bearing_directories_and_special_zip_types(self) -> None:
- cases: list[tuple[str, zipfile.ZipInfo, bytes]] = []
- directory = zipfile.ZipInfo("hidden/")
- directory.create_system = 3
- directory.external_attr = (stat.S_IFDIR | 0o755) << 16
- cases.append(("directory", directory, b"hidden data"))
- fifo = zipfile.ZipInfo("hidden-fifo")
- fifo.create_system = 3
- fifo.external_attr = (stat.S_IFIFO | 0o600) << 16
- cases.append(("fifo", fifo, b""))
- absolute_root = zipfile.ZipInfo("/")
- absolute_root.create_system = 3
- absolute_root.external_attr = (stat.S_IFDIR | 0o755) << 16
- cases.append(("absolute-root", absolute_root, b""))
- for label, member, data in cases:
- with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- payload = io.BytesIO()
- with zipfile.ZipFile(payload, "w") as archive:
- archive.writestr(member, data)
- path = write_file(
- source,
- "test-archives/unsafe.zip",
- payload.getvalue(),
- )
- candidates, _, _ = handoff.scan_tree(source)
- candidate = next(item for item in candidates if item.absolute == path)
- with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"):
- handoff.scan_candidate_archive(candidate)
- def test_audit_rejects_secrets_in_tar_metadata(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- marker = "-----BEGIN " + "PRIVATE KEY-----\nsecret\n"
- payload = io.BytesIO()
- with tarfile.open(fileobj=payload, mode="w:gz", format=tarfile.PAX_FORMAT) as archive:
- member = tarfile.TarInfo("safe.txt")
- member.size = 4
- member.pax_headers = {"comment": marker}
- archive.addfile(member, io.BytesIO(b"safe"))
- self.assertNotIn(marker.encode(), payload.getvalue())
- write_file(
- source,
- "test-archives/metadata.tar.gz",
- payload.getvalue(),
- )
- result = run_packager(source, output, "tar-metadata-secret", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertFalse(output.exists())
- def test_archive_scan_rejects_unsafe_members_and_resource_exhaustion(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- unsafe = write_file(
- source,
- "reference/original/board/unsafe.zip",
- zip_bytes({"../outside.txt": b"unsafe\n"}),
- )
- candidates, _, _ = handoff.scan_tree(source)
- candidate = next(item for item in candidates if item.absolute == unsafe)
- with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"):
- handoff.scan_candidate_archive(candidate)
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- oversized = write_file(
- source,
- "reference/original/board/oversized.zip",
- zip_bytes({"large.txt": b"A" * 128}),
- )
- candidates, _, _ = handoff.scan_tree(source)
- candidate = next(item for item in candidates if item.absolute == oversized)
- with (
- mock.patch.object(handoff, "MAX_ARCHIVE_UNCOMPRESSED_BYTES", 64),
- self.assertRaisesRegex(handoff.PackagingError, "archive scan resource limit"),
- ):
- handoff.scan_candidate_archive(candidate)
- def test_high_confidence_token_in_source_path_is_rejected_without_echo(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- token = "gh" + "p_" + ("A" * 36)
- write_file(source, f"docs/{token}.txt", b"safe content\n")
- result = run_packager(source, output, "path-token", "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("secret", (result.stderr + result.stdout).lower())
- self.assertNotIn(token, result.stderr + result.stdout)
- self.assertFalse(output.exists())
- def test_audit_only_creates_no_artifacts(self) -> None:
- self.assertTrue(PACKAGER.is_file(), PACKAGER)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "not-created"
- write_file(source, "src/rtl/core.v")
- write_file(source, "tmp/runtime.bin")
- result = run_packager(source, output, "audit-fixture", "-AuditOnly")
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- payload = json.loads(result.stdout)
- self.assertEqual(payload["status"], "pass")
- self.assertEqual(payload["mode"], "audit_only")
- self.assertEqual(payload["included_file_count"], 2)
- self.assertFalse(output.exists())
- def test_audit_uses_delete_on_close_snapshot_instead_of_unbounded_memory(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- candidates, _, _ = handoff.scan_tree(source)
- with mock.patch.object(
- handoff.io,
- "BytesIO",
- side_effect=AssertionError("audit used an in-memory whole-file snapshot"),
- ):
- inventory = handoff.audit_candidates(candidates)
- self.assertEqual(len(inventory), 1)
- def test_existing_archive_requires_force_and_force_replaces_it(self) -> None:
- self.assertTrue(PACKAGER.is_file(), PACKAGER)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/first.v", b"first\n")
- first = run_packager(source, output, "replace-fixture")
- self.assertEqual(first.returncode, 0, first.stderr + first.stdout)
- archive = output / "replace-fixture.zip"
- original_hash = hashlib.sha256(archive.read_bytes()).hexdigest()
- write_file(source, "src/rtl/second.v", b"second\n")
- refused = run_packager(source, output, "replace-fixture")
- self.assertNotEqual(refused.returncode, 0)
- self.assertIn("already exists", refused.stderr + refused.stdout)
- self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), original_hash)
- replaced = run_packager(source, output, "replace-fixture", "-ForceOverwrite")
- self.assertEqual(replaced.returncode, 0, replaced.stderr + replaced.stdout)
- self.assertNotEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), original_hash)
- with zipfile.ZipFile(archive) as packaged:
- self.assertIn("CPLD/src/rtl/second.v", packaged.namelist())
- def test_publish_refuses_target_that_appears_after_validation(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- final_zip = temp / "handoff.zip"
- final_sidecar = temp / "handoff.zip.sha256.txt"
- temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
- temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
- real_link = os.link
- def create_racing_target(source: str | Path, target: str | Path) -> None:
- if Path(target) == final_sidecar:
- final_sidecar.write_bytes(b"sentinel\n")
- real_link(source, target)
- with mock.patch.object(handoff.os, "link", side_effect=create_racing_target):
- with self.assertRaisesRegex(handoff.PackagingError, "atomically"):
- handoff.publish_artifacts_atomically(
- [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
- force=False,
- )
- self.assertFalse(final_zip.exists())
- self.assertEqual(final_sidecar.read_bytes(), b"sentinel\n")
- def test_force_overwrite_rejects_posix_mode_without_write_bits(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- target = write_file(Path(tmp), "handoff.zip", b"old\n")
- current = os.lstat(target)
- read_only = SimpleNamespace(
- st_mode=stat.S_IFREG | 0o444,
- st_ino=current.st_ino,
- st_dev=current.st_dev,
- st_nlink=current.st_nlink,
- st_uid=current.st_uid,
- st_gid=current.st_gid,
- st_size=current.st_size,
- st_atime=current.st_atime,
- st_mtime=current.st_mtime,
- st_mtime_ns=current.st_mtime_ns,
- st_ctime=current.st_ctime,
- st_file_attributes=0,
- )
- with mock.patch.object(handoff.os, "lstat", return_value=read_only):
- with self.assertRaisesRegex(handoff.PackagingError, "read-only"):
- handoff.validate_publish_targets((target,), force=True)
- def test_post_publish_zip_and_sidecar_tampering_rolls_back(self) -> None:
- for target_kind in ("zip", "sidecar"):
- for force in (False, True):
- with (
- self.subTest(target_kind=target_kind, force=force),
- tempfile.TemporaryDirectory() as tmp,
- ):
- self._assert_post_publish_tampering_rolls_back(tmp, target_kind, force)
- def test_source_content_change_during_publication_rolls_back(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- source_file = write_file(source, "src/rtl/core.v", b"first!\n")
- candidates, excluded, context = handoff.scan_tree(source)
- candidate = candidates[0]
- final_zip = output / "source-race-fixture.zip"
- final_sidecar = output / "source-race-fixture.zip.sha256.txt"
- real_link = os.link
- def link_then_mutate(source_path: str | Path, target_path: str | Path) -> None:
- real_link(source_path, target_path)
- if Path(target_path) == final_sidecar:
- source_file.write_bytes(b"second\n")
- os.utime(source_file, ns=(candidate.mtime_ns, candidate.mtime_ns))
- with mock.patch.object(handoff.os, "link", side_effect=link_then_mutate):
- with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="source-race-fixture",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- self.assertFalse(final_zip.exists())
- self.assertFalse(final_sidecar.exists())
- def _assert_post_publish_tampering_rolls_back(
- self,
- tmp: str,
- target_kind: str,
- force: bool,
- ) -> None:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- candidates, excluded, context = handoff.scan_tree(source)
- final_zip = output / "tamper-fixture.zip"
- final_sidecar = output / "tamper-fixture.zip.sha256.txt"
- old_zip = b"old zip\n"
- old_sidecar = b"old sidecar\n"
- if force:
- write_file(output, final_zip.name, old_zip)
- write_file(output, final_sidecar.name, old_sidecar)
- real_link = os.link
- def link_then_tamper(source_path: str | Path, target_path: str | Path) -> None:
- real_link(source_path, target_path)
- if Path(target_path) == final_sidecar:
- victim = final_zip if target_kind == "zip" else final_sidecar
- victim.write_bytes(b"tampered after publication\n")
- with mock.patch.object(handoff.os, "link", side_effect=link_then_tamper):
- with self.assertRaises(handoff.PackagingError):
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="tamper-fixture",
- force=force,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- if force:
- self.assertEqual(final_zip.read_bytes(), old_zip)
- self.assertEqual(final_sidecar.read_bytes(), old_sidecar)
- else:
- self.assertFalse(final_zip.exists())
- self.assertFalse(final_sidecar.exists())
- def test_atomic_publish_restores_existing_artifacts_when_second_publish_fails(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- final_zip = write_file(temp, "handoff.zip", b"old zip\n")
- final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
- temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
- temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
- real_link = os.link
- def fail_second_publish(source: str | Path, target: str | Path) -> None:
- if Path(source) == temp_sidecar and Path(target) == final_sidecar:
- raise OSError("simulated publish failure")
- real_link(source, target)
- with mock.patch.object(handoff.os, "link", side_effect=fail_second_publish):
- with self.assertRaisesRegex(handoff.PackagingError, "publish"):
- handoff.publish_artifacts_atomically(
- [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
- force=True,
- )
- self.assertEqual(final_zip.read_bytes(), b"old zip\n")
- self.assertEqual(final_sidecar.read_bytes(), b"old sidecar\n")
- self.assertFalse(any("backup" in path.name for path in temp.iterdir()))
- def test_force_overwrite_refuses_existing_directory(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v")
- target = output / "directory-fixture.zip"
- sentinel = write_file(target, "sentinel.txt", b"keep\n")
- result = run_packager(source, output, "directory-fixture", "-ForceOverwrite")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("regular file", (result.stderr + result.stdout).lower())
- self.assertTrue(target.is_dir())
- self.assertEqual(sentinel.read_bytes(), b"keep\n")
- self.assertFalse(any("backup" in path.name for path in output.iterdir()))
- def test_backup_cleanup_failure_keeps_published_artifacts_and_returns_warnings(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- final_zip = write_file(temp, "handoff.zip", b"old zip\n")
- final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
- temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
- temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
- real_unlink = Path.unlink
- def fail_backup_cleanup(path: Path, *args: object, **kwargs: object) -> None:
- if path.name.endswith(".backup"):
- raise PermissionError("simulated backup cleanup failure")
- real_unlink(path, *args, **kwargs)
- with mock.patch.object(Path, "unlink", autospec=True, side_effect=fail_backup_cleanup):
- warnings = handoff.publish_artifacts_atomically(
- [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
- force=True,
- )
- self.assertEqual(final_zip.read_bytes(), b"new zip\n")
- self.assertEqual(final_sidecar.read_bytes(), b"new sidecar\n")
- self.assertEqual(len(warnings), 2)
- self.assertTrue(all("backup" in warning for warning in warnings))
- for backup in temp.glob("*.backup"):
- real_unlink(backup)
- def test_force_overwrite_refuses_read_only_artifacts_before_mutation(self) -> None:
- attrib = shutil.which("attrib.exe")
- if not attrib:
- self.skipTest("Windows read-only attribute is unavailable")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"first\n")
- first = run_packager(source, output, "readonly-fixture")
- self.assertEqual(first.returncode, 0, first.stderr + first.stdout)
- archive = output / "readonly-fixture.zip"
- sidecar = output / "readonly-fixture.zip.sha256.txt"
- original = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in (archive, sidecar)}
- for path in (archive, sidecar):
- subprocess.run([attrib, "+R", str(path)], capture_output=True, check=True)
- try:
- write_file(source, "src/rtl/second.v", b"second\n")
- result = run_packager(source, output, "readonly-fixture", "-ForceOverwrite")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("read-only", (result.stderr + result.stdout).lower())
- self.assertEqual(
- {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in (archive, sidecar)},
- original,
- )
- self.assertFalse(any("backup" in path.name for path in output.iterdir()))
- finally:
- for path in output.iterdir():
- subprocess.run([attrib, "-R", str(path)], capture_output=True, check=False)
- def test_output_directory_inside_source_is_rejected(self) -> None:
- self.assertTrue(PACKAGER.is_file(), PACKAGER)
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- write_file(source, "src/rtl/core.v")
- result = run_packager(source, source / "dist", "recursive-fixture")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("outside SourceRoot", result.stderr + result.stdout)
- self.assertFalse((source / "dist" / "recursive-fixture.zip").exists())
- def test_unknown_junction_fails_closed_without_following_it(self) -> None:
- self.assertTrue(PACKAGER.is_file(), PACKAGER)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- outside = temp / "outside"
- output = temp / "output"
- write_file(source, "src/rtl/core.v")
- write_file(outside, "outside-secret.txt", b"must never be followed\n")
- link = source / "docs" / "external-link"
- link.parent.mkdir(parents=True, exist_ok=True)
- cmd = shutil.which("cmd.exe")
- if not cmd:
- self.skipTest("Windows junction creation is unavailable")
- created = subprocess.run(
- [cmd, "/c", "mklink", "/J", str(link), str(outside)],
- capture_output=True,
- text=True,
- check=False,
- )
- if created.returncode != 0:
- self.skipTest("junction creation is unavailable in this environment")
- try:
- result = run_packager(source, output, "junction-fixture")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("undeclared reparse point", result.stderr + result.stdout)
- self.assertFalse((output / "junction-fixture.zip").exists())
- finally:
- os.rmdir(link)
- def test_git_junction_is_not_used_for_provenance(self) -> None:
- cmd = shutil.which("cmd.exe")
- if not cmd:
- self.skipTest("Windows junction creation is unavailable")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- outside_git = temp / "outside-git"
- source.mkdir()
- write_file(outside_git, "HEAD", b"ref: refs/heads/main\n")
- link = source / ".git"
- created = subprocess.run(
- [cmd, "/c", "mklink", "/J", str(link), str(outside_git)],
- capture_output=True,
- text=True,
- check=False,
- )
- if created.returncode != 0:
- self.skipTest("junction creation is unavailable in this environment")
- try:
- self.assertIsNone(handoff.resolve_git_dir(source))
- finally:
- os.rmdir(link)
- def test_git_provenance_uses_current_python_and_omits_working_tree_patch(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- write_file(source, ".git/HEAD", b"ref: refs/heads/main\n")
- untrusted_python = write_file(
- source,
- ".codex/venv/Scripts/python.exe",
- b"must never be executed\n",
- )
- commands: list[list[str]] = []
- def capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
- del cwd, timeout
- commands.append(command)
- return 0, b"clean\n"
- with (
- mock.patch.object(handoff.shutil, "which", return_value=None),
- mock.patch("importlib.util.find_spec", return_value=object()),
- mock.patch.object(handoff, "run_capture", side_effect=capture),
- ):
- provenance, artifacts = handoff.collect_git_provenance(source)
- self.assertEqual(len(commands), 1)
- self.assertEqual(commands[0][0], sys.executable)
- self.assertIn("-I", commands[0])
- self.assertNotEqual(Path(commands[0][0]), untrusted_python)
- self.assertEqual(provenance["tool"], "dulwich")
- self.assertTrue(provenance["status_captured"])
- self.assertNotIn("diff_captured", provenance)
- self.assertEqual(
- set(artifacts),
- {"CPLD/HANDOFF-METADATA/git-status.txt"},
- )
- def test_git_ref_path_traversal_is_not_followed(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- git_dir = temp / "source" / ".git"
- write_file(git_dir, "HEAD", b"ref: ../../outside-ref\n")
- write_file(temp, "outside-ref", b"0123456789abcdef0123456789abcdef01234567\n")
- self.assertEqual(handoff.read_head_metadata(git_dir), (None, None))
- def test_git_status_disables_external_fsmonitor_configuration(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- write_file(source, ".git/HEAD", b"0123456789abcdef0123456789abcdef01234567\n")
- commands: list[list[str]] = []
- def capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
- del cwd, timeout
- commands.append(command)
- return 0, b"clean\n"
- with (
- mock.patch.object(handoff.shutil, "which", return_value="git"),
- mock.patch.object(handoff, "run_capture", side_effect=capture),
- ):
- handoff.collect_git_provenance(source)
- self.assertEqual(len(commands), 1)
- self.assertIn("core.fsmonitor=false", commands[0])
- self.assertIn("core.untrackedCache=false", commands[0])
- def test_changxin_version_reader_refuses_reparse_point_before_reading(self) -> None:
- fake_link = SimpleNamespace(
- st_mode=stat.S_IFLNK | 0o777,
- st_file_attributes=int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)),
- )
- with (
- mock.patch.object(Path, "is_file", return_value=True),
- mock.patch.object(handoff.os, "lstat", return_value=fake_link),
- mock.patch.object(Path, "read_text", side_effect=AssertionError("followed link")),
- ):
- context = handoff.load_scan_context(Path("C:/untrusted-source"))
- self.assertIsNone(context.changxin_version)
- def test_candidate_identity_change_is_rejected(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- source = Path(tmp) / "source"
- original = write_file(source, "src/rtl/core.v", b"first!\n")
- candidates, _, _ = handoff.scan_tree(source)
- candidate = next(item for item in candidates if item.relative == "src/rtl/core.v")
- replacement = source / "replacement.tmp-source"
- replacement.write_bytes(b"second\n")
- os.utime(replacement, ns=(candidate.mtime_ns, candidate.mtime_ns))
- os.replace(replacement, original)
- self.assertEqual(original.stat().st_size, candidate.size)
- self.assertEqual(original.stat().st_mtime_ns, candidate.mtime_ns)
- archive_path = Path(tmp) / "identity.zip"
- with zipfile.ZipFile(archive_path, "w") as archive:
- with self.assertRaises(handoff.PackagingError):
- handoff.write_candidate(archive, candidate)
- def test_source_tree_changes_before_publication_are_rejected(self) -> None:
- for late_path in ("src/rtl/late.v", "download.part"):
- with self.subTest(late_path=late_path), tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v")
- candidates, excluded, context = handoff.scan_tree(source)
- verify_archive = handoff.verify_archive
- def verify_and_mutate(*args: object, **kwargs: object) -> None:
- verify_archive(*args, **kwargs)
- write_file(source, late_path)
- caught: handoff.PackagingError | None = None
- with mock.patch.object(handoff, "verify_archive", side_effect=verify_and_mutate):
- try:
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="race-fixture",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- except handoff.PackagingError as exc:
- caught = exc
- self.assertIsNotNone(caught)
- self.assertIn("source tree changed", str(caught).lower())
- self.assertFalse((output / "race-fixture.zip").exists())
- self.assertFalse((output / "race-fixture.zip.sha256.txt").exists())
- self.assertFalse(any(path.suffix == ".partial" for path in output.iterdir()))
- def test_source_content_change_with_restored_metadata_is_rejected(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- original = write_file(source, "src/rtl/core.v", b"first!\n")
- candidates, excluded, context = handoff.scan_tree(source)
- candidate = candidates[0]
- verify_archive = handoff.verify_archive
- def verify_and_mutate(*args: object, **kwargs: object) -> None:
- verify_archive(*args, **kwargs)
- original.write_bytes(b"second\n")
- os.utime(original, ns=(candidate.mtime_ns, candidate.mtime_ns))
- with mock.patch.object(handoff, "verify_archive", side_effect=verify_and_mutate):
- with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="content-race-fixture",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- self.assertFalse((output / "content-race-fixture.zip").exists())
- self.assertFalse((output / "content-race-fixture.zip.sha256.txt").exists())
- def test_source_content_change_during_publication_is_rejected_and_rolled_back(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- original = write_file(source, "src/rtl/core.v", b"first!\n")
- candidates, excluded, context = handoff.scan_tree(source)
- candidate = candidates[0]
- real_publish = handoff.publish_artifacts_atomically
- def mutate_then_publish(*args: object, **kwargs: object) -> list[str]:
- original.write_bytes(b"second\n")
- os.utime(original, ns=(candidate.mtime_ns, candidate.mtime_ns))
- return real_publish(*args, **kwargs)
- with mock.patch.object(
- handoff,
- "publish_artifacts_atomically",
- side_effect=mutate_then_publish,
- ):
- with self.assertRaisesRegex(handoff.PackagingError, "source tree changed"):
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="publish-source-race-fixture",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- self.assertFalse((output / "publish-source-race-fixture.zip").exists())
- self.assertFalse(
- (output / "publish-source-race-fixture.zip.sha256.txt").exists()
- )
- def test_temp_archive_metadata_replacement_after_verification_is_rejected(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- candidates, excluded, context = handoff.scan_tree(source)
- real_verify = handoff.verify_archive
- def verify_then_replace(path: object, *args: object, **kwargs: object) -> None:
- real_verify(path, *args, **kwargs)
- temp_zip = next(
- item
- for item in output.glob("*.partial")
- if "sha256" not in item.name
- )
- with zipfile.ZipFile(temp_zip, "r") as archive:
- entries = {name: archive.read(name) for name in archive.namelist()}
- entries["CPLD/HANDOFF-METADATA/manifest.json"] = b'{"status":"tampered"}\n'
- replacement = output / "attacker-replacement.zip"
- with zipfile.ZipFile(replacement, "w", compression=zipfile.ZIP_DEFLATED) as archive:
- for name, payload in entries.items():
- archive.writestr(name, payload)
- os.replace(replacement, temp_zip)
- with mock.patch.object(handoff, "verify_archive", side_effect=verify_then_replace):
- with self.assertRaises(handoff.PackagingError):
- handoff.create_package(
- root=source,
- output_dir=output,
- package_name="temp-race-fixture",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- self.assertFalse((output / "temp-race-fixture.zip").exists())
- self.assertFalse((output / "temp-race-fixture.zip.sha256.txt").exists())
- def test_partial_cleanup_errors_are_reported(self) -> None:
- attrib = shutil.which("attrib.exe")
- if not attrib:
- self.skipTest("Windows read-only attribute is unavailable")
- with tempfile.TemporaryDirectory() as tmp:
- partial = write_file(Path(tmp), "archive.partial")
- subprocess.run([attrib, "+R", str(partial)], capture_output=True, check=True)
- try:
- with self.assertRaisesRegex(handoff.PackagingError, "partial"):
- handoff.remove_partial_artifacts((partial,))
- finally:
- subprocess.run([attrib, "-R", str(partial)], capture_output=True, check=False)
- partial.unlink(missing_ok=True)
- def test_publish_rollback_attempts_all_restores_and_reports_recovery_paths(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- final_zip = write_file(temp, "handoff.zip", b"old zip\n")
- final_sidecar = write_file(temp, "handoff.zip.sha256.txt", b"old sidecar\n")
- temp_zip = write_file(temp, ".handoff.partial", b"new zip\n")
- temp_sidecar = write_file(temp, ".handoff.sha256.partial", b"new sidecar\n")
- real_link = os.link
- real_replace = os.replace
- restored: list[Path] = []
- def fail_second_publish(source_path: str | Path, target_path: str | Path) -> None:
- if Path(source_path) == temp_sidecar:
- raise OSError("simulated publish failure")
- real_link(source_path, target_path)
- def fail_one_restore(source_path: str | Path, target_path: str | Path) -> None:
- source = Path(source_path)
- target = Path(target_path)
- if source.name.endswith(".backup"):
- restored.append(target)
- if target == final_zip:
- raise OSError("simulated restore failure")
- real_replace(source_path, target_path)
- with (
- mock.patch.object(handoff.os, "link", side_effect=fail_second_publish),
- mock.patch.object(handoff.os, "replace", side_effect=fail_one_restore),
- self.assertRaisesRegex(handoff.PackagingError, "rollback was incomplete") as caught,
- ):
- handoff.publish_artifacts_atomically(
- [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
- force=True,
- )
- self.assertEqual(set(restored), {final_zip, final_sidecar})
- self.assertEqual(final_sidecar.read_bytes(), b"old sidecar\n")
- self.assertIn("manual recovery paths", str(caught.exception))
- self.assertTrue(any(path.name.endswith(".backup") for path in temp.iterdir()))
- def test_create_package_returns_warning_when_published_temp_cleanup_fails(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v", b"module core; endmodule\n")
- candidates, excluded, context = handoff.scan_tree(source)
- real_unlink = Path.unlink
- def fail_partial_cleanup(path: Path, *args: object, **kwargs: object) -> None:
- if path.name.endswith(".partial"):
- raise PermissionError("simulated temporary cleanup failure")
- real_unlink(path, *args, **kwargs)
- with mock.patch.object(
- Path,
- "unlink",
- autospec=True,
- side_effect=fail_partial_cleanup,
- ):
- result = handoff.create_package(
- root=source,
- output_dir=output,
- package_name="cleanup-warning",
- force=False,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- self.assertEqual(result["status"], "pass")
- self.assertEqual(len(result["warnings"]), 2)
- self.assertTrue((output / "cleanup-warning.zip").is_file())
- self.assertTrue((output / "cleanup-warning.zip.sha256.txt").is_file())
- for partial in output.glob("*.partial"):
- real_unlink(partial)
- def test_windows_reserved_device_names_are_rejected(self) -> None:
- for relative in ("CON", "docs/aux.txt", "reports/COM1.log", "LPT9"):
- with self.subTest(relative=relative):
- with self.assertRaises(handoff.PackagingError):
- handoff.windows_collision_key(relative)
- def test_windows_unsafe_path_components_are_rejected(self) -> None:
- unsafe = (
- "docs/trailing.",
- "docs/trailing ",
- "docs/question?.txt",
- "docs/star*.txt",
- "docs/less<.txt",
- "docs/greater>.txt",
- "docs/pipe|.txt",
- 'docs/quote".txt',
- "docs/control\x1f.txt",
- )
- for relative in unsafe:
- with self.subTest(relative=relative):
- with self.assertRaises(handoff.PackagingError):
- handoff.normalize_relative(relative.split("/"))
- with self.assertRaisesRegex(handoff.PackagingError, "UTF-8"):
- handoff.normalize_relative(["docs", "bad\udcff.txt"])
- def test_windows_reserved_or_trailing_package_names_are_rejected(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- output = temp / "output"
- write_file(source, "src/rtl/core.v")
- for package_name in ("CON", "COM1", "trailing."):
- with self.subTest(package_name=package_name):
- result = run_packager(source, output, package_name, "-AuditOnly")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("PackageName", result.stderr + result.stdout)
- def test_wrapper_and_readme_require_python_311_or_newer(self) -> None:
- wrapper = PACKAGER.read_text(encoding="utf-8-sig")
- readme = (ROOT / "docs/agent-handoff-packaging.zh-CN.md").read_text(encoding="utf-8-sig")
- self.assertIn("3.11", wrapper)
- self.assertIn("3.11", readme)
- self.assertIn("-I -S -B", readme)
- self.assertIn("GetFinalPathNameByHandle", wrapper)
- self.assertNotIn(".codex\\venv\\Scripts\\python.exe", wrapper)
- for flag in ("-I", "-S", "-B"):
- with self.subTest(flag=flag):
- self.assertIn(flag, wrapper)
- for marker in (
- "-AuditOnly",
- "-SourceRoot",
- "-OutputDir",
- "-ForceOverwrite",
- "Get-FileHash",
- "tmp/photos",
- "tmp/pdfs",
- "clean-runtime",
- "编译产物",
- "Deflate",
- ):
- with self.subTest(marker=marker):
- self.assertIn(marker, readme)
- self.assertIn("100,000", readme)
- self.assertIn("8 GiB", readme)
- self.assertIn("SourceRoot", readme)
- self.assertIn("外", readme)
- if __name__ == "__main__":
- unittest.main()
|