返回 CodeWhale
test_ci_migration_wiring.py
根目录 / scripts / test_ci_migration_wiring.py
1 #!/usr/bin/env python3
2 """Hermetic tests for migration gates and manual workspace qualification.
3
4 Verifies `.github/workflows/ci.yml` keeps both migration checker commands
5 (self-tests then live scan) beside the command-contract boundary step, and that
6 the boundary step itself remains intact. Exercise the GH6698 workflow shell with a fake Cargo and the real
7 HOME-isolation wrapper so these wiring tests never compile or run Rust.
8 """
9
10 from __future__ import annotations
11
12 import json
13 import os
14 import re
15 import shutil
16 import subprocess
17 import sys
18 import tempfile
19 import textwrap
20 import unittest
21 from pathlib import Path
22
23 ROOT = Path(__file__).resolve().parents[1]
24 CI_PATH = ROOT / ".github" / "workflows" / "ci.yml"
25 SHARED_PROCESS_MODE = "inputs.workspace_test_mode == 'shared-process-twice'"
26 ISSUE_6698_TESTS = (
27 "remote_control::tests::classic_recovery_uses_persisted_seq_floor_and_ignores_older_terminal",
28 "remote_control::tests::actual_start_reclaims_runtime_chat_writer_before_worker_spawn",
29 "remote_control::tests::separate_predispatch_crashes_on_one_run_get_distinct_recovery_turn_ids",
30 "runtime_api::tests::events_endpoint_respects_since_seq_cursor",
31 "runtime_threads::tests::approval_required_awaits_external_decision_allow",
32 "runtime_threads::tests::approval_remember_grants_tool_class_without_changing_posture",
33 "tools::subagent::budget_handback_tests::budget_handback_inflight_wall_timeout_persists_unreported_usage",
34 "tools::subagent::tests::child_permission_gate::wall_deadline_ends_pending_wait_with_receipt",
35 "tools::subagent::tests::resume_keeps_recorded_reasoning_in_manifest_and_request_after_parent_changes",
36 )
37
38
39 def load_ci() -> str:
40 return CI_PATH.read_text(encoding="utf-8")
41
42
43 def boundary_step_block(ci: str) -> str:
44 """Extract the 'Check command-contract prototype boundary' step block."""
45 marker = "Check command-contract prototype boundary"
46 start = ci.index(marker)
47 step_start = ci.rindex("- name:", 0, start)
48 # The step ends at the next "- name:" after the marker.
49 next_step = ci.index("- name:", start + len(marker))
50 return ci[step_start:next_step]
51
52
53 def migration_step_block(ci: str) -> str:
54 marker = "Check command migration manifest"
55 start = ci.index(marker)
56 step_start = ci.rindex("- name:", 0, start)
57 next_step = ci.index("- name:", start + len(marker))
58 return ci[step_start:next_step]
59
60
61 def named_step(ci: str, name: str) -> str:
62 start = ci.index(f" - name: {name}\n")
63 return ci[start:ci.index(" - name:", start + 1)]
64
65
66 def run_shared_process_fixture(mode: str = "pass", expected_sha: str | None = None) -> dict:
67 """Execute the actual workflow shell and HOME wrapper, never real Cargo."""
68 block = named_step(load_ci(), "Shared-process workspace qualification")
69 script = textwrap.dedent(block.split(" run: |\n", 1)[1])
70 with tempfile.TemporaryDirectory(prefix="shared-process-wiring-") as temp:
71 fixture = Path(temp)
72 repo = fixture / "repo"
73 binary = fixture / "bin"
74 (repo / "scripts").mkdir(parents=True)
75 binary.mkdir()
76 shutil.copyfile(
77 ROOT / "scripts/with-hermetic-test-home.sh",
78 repo / "scripts/with-hermetic-test-home.sh",
79 )
80 trace = fixture / "cargo-calls.jsonl"
81 outside = fixture / "outside"
82 outside.mkdir()
83 outside_payload = outside / "payload.txt"
84 outside_payload.write_text("outside fixture must remain unchanged", encoding="utf-8")
85 outside_payload.chmod(0o400)
86 outside.chmod(0o500)
87 fake_cargo = f"""#!{sys.executable}
88 import json, os, sys
89 from pathlib import Path
90 if sys.argv[1:] == ['-V']:
91 print('cargo fixture (no compiler invoked)')
92 raise SystemExit(0)
93 trace = Path(os.environ['FIXTURE_TRACE'])
94 calls = trace.read_text().splitlines() if trace.exists() else []
95 call = {{'args': sys.argv[1:], 'home': os.environ['HOME'],
96 'tmpdir': os.environ['TMPDIR'], 'threads': os.environ.get('RUST_TEST_THREADS'),
97 'stack': os.environ['RUST_MIN_STACK'],
98 'credential_present': bool(os.environ.get('OPENAI_API_KEY'))}}
99 with trace.open('a') as out:
100 out.write(json.dumps(call) + '\\n')
101 identities = {ISSUE_6698_TESTS!r}
102 if os.environ['FIXTURE_MODE'] == 'missing_identity':
103 identities = identities[:-1]
104 for identity in identities:
105 print('test ' + identity + ' ... ok')
106 print('fixture complete: integration targets and doctests reached')
107 if os.environ['FIXTURE_MODE'] == 'source_changed':
108 Path('scripts/with-hermetic-test-home.sh').write_text('# changed fixture source\\n')
109 if os.environ['FIXTURE_MODE'] in ('readonly_cleanup', 'cleanup_failure'):
110 root = Path(os.environ['TMPDIR']) / 'readonly-runtime'
111 nested = root / 'nested'
112 nested.mkdir(parents=True)
113 (nested / 'payload.txt').write_text('read-only plugin fixture')
114 (nested / 'payload.txt').chmod(0o400)
115 outside = Path(os.environ['FIXTURE_OUTSIDE'])
116 (root / 'external-directory').symlink_to(outside, target_is_directory=True)
117 (root / 'external-file').symlink_to(outside / 'payload.txt')
118 os.link(outside / 'payload.txt', root / 'external-hardlink')
119 nested.chmod(0o500)
120 root.chmod(0o500)
121 raise SystemExit(101 if os.environ['FIXTURE_MODE'] in ('first_failure', 'cleanup_failure') and not calls else 0)
122 """
123 fake_rm = f"""#!{sys.executable}
124 import os, sys
125 from pathlib import Path
126 target = Path(sys.argv[-1])
127 trace = Path(os.environ['FIXTURE_TRACE'])
128 if (os.environ['FIXTURE_MODE'] == 'cleanup_failure'
129 and target.parent == Path('/tmp') and target.name.startswith('cw69.')
130 and len(trace.read_text().splitlines()) == 1):
131 print('fixture: qualification cleanup refused', file=sys.stderr)
132 raise SystemExit(73)
133 os.execv({shutil.which('rm')!r}, ['rm', *sys.argv[1:]])
134 """
135 for name, content in {
136 "cargo": fake_cargo,
137 "rm": fake_rm,
138 "rustc": "#!/bin/sh\nprintf '%s\\n' 'rustc fixture (no compiler invoked)'\n",
139 "rustup": '#!/bin/sh\nprintf "%s\\n" "$FIXTURE_BIN/rustc"\n',
140 }.items():
141 path = binary / name
142 path.write_text(content, encoding="utf-8")
143 path.chmod(0o700)
144 env = {
145 "PATH": f"{binary}{os.pathsep}{os.environ['PATH']}",
146 "HOME": str(fixture / "outer-home"),
147 "CARGO_HOME": str(fixture / "cargo-home"),
148 "RUSTUP_HOME": str(fixture / "rustup-home"),
149 "GIT_CONFIG_NOSYSTEM": "1",
150 "RUNNER_TEMP": str(fixture / "evidence"),
151 "RUNNER_OS": "Linux", "RUNNER_ARCH": "X64",
152 "RUST_MIN_STACK": "16777216", "RUST_TEST_THREADS": "1",
153 "OPENAI_API_KEY": "synthetic-untrusted-fixture-key",
154 "FIXTURE_BIN": str(binary), "FIXTURE_TRACE": str(trace),
155 "FIXTURE_MODE": mode, "FIXTURE_OUTSIDE": str(outside),
156 }
157 for args in (
158 ["init", "-q"], ["add", "scripts/with-hermetic-test-home.sh"],
159 ["-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid",
160 "commit", "-qm", "fixture", "--no-gpg-sign"],
161 ):
162 subprocess.run(["git", *args], cwd=repo, env=env, check=True, capture_output=True)
163 sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, env=env, text=True).strip()
164 env.update(EXPECTED_SHA=expected_sha or sha, GITHUB_SHA=sha)
165 result = subprocess.run(
166 ["bash", "-c", script], cwd=repo, env=env, text=True, capture_output=True, timeout=30,
167 )
168 evidence = fixture / "evidence/shared-process-workspace"
169 calls = [json.loads(line) for line in trace.read_text().splitlines()] if trace.exists() else []
170 proof = {
171 "result": result,
172 "calls": calls,
173 "evidence": {path.name: path.read_text() for path in evidence.iterdir()},
174 "qualification_removed": [not Path(call["tmpdir"]).exists() for call in calls],
175 "outside": {
176 "directory_mode": outside.stat().st_mode & 0o777,
177 "file_mode": outside_payload.stat().st_mode & 0o777,
178 "contents": outside_payload.read_text(encoding="utf-8"),
179 },
180 }
181 # Only the injected rm failure leaves a root; the workflow has already
182 # made its directories writable. Do not leave the deliberate fixture.
183 for call in calls:
184 if Path(call["tmpdir"]).exists():
185 shutil.rmtree(call["tmpdir"])
186 outside.chmod(0o700)
187 return proof
188
189
190 class CiWiringTests(unittest.TestCase):
191 def test_boundary_step_still_present(self) -> None:
192 ci = load_ci()
193 self.assertIn("Check command-contract prototype boundary", ci)
194 block = boundary_step_block(ci)
195 self.assertIn("test_check_command_crate_boundaries.py", block)
196 self.assertIn("check-command-crate-boundaries.py", block)
197
198 def test_migration_self_test_present(self) -> None:
199 ci = load_ci()
200 block = migration_step_block(ci)
201 self.assertIn("test_check_command_migration_manifest.py", block)
202
203 def test_migration_live_scan_present(self) -> None:
204 ci = load_ci()
205 block = migration_step_block(ci)
206 self.assertIn("check-command-migration-manifest.py", block)
207
208 def test_baseline_checks_derive_their_baseline_locally(self) -> None:
209 ci = load_ci()
210 for block in (boundary_step_block(ci), migration_step_block(ci)):
211 self.assertNotIn("--baseline-ref", block)
212 self.assertNotIn("github.event", block)
213
214 def test_migration_commands_are_ordered_self_test_first(self) -> None:
215 ci = load_ci()
216 block = migration_step_block(ci)
217 self.assertLess(
218 block.index("test_check_command_migration_manifest.py"),
219 block.index("check-command-migration-manifest.py"),
220 "checker self-tests must run before the live migration scan",
221 )
222
223 def test_boundary_and_migration_steps_are_unconditional(self) -> None:
224 ci = load_ci()
225 for block in (boundary_step_block(ci), migration_step_block(ci)):
226 self.assertNotIn("if:", block)
227
228 def test_migration_step_does_not_remove_boundary_step(self) -> None:
229 ci = load_ci()
230 # Both steps must coexist (the migration step is added beside, never
231 # replacing, the boundary step).
232 self.assertLess(
233 ci.index("Check command-contract prototype boundary"),
234 ci.index("Check command migration manifest"),
235 )
236
237 def test_main_ci_concurrency_is_keyed_by_sha(self) -> None:
238 ci = load_ci()
239 self.assertIn("github.workflow, github.sha", ci)
240 self.assertIn("name: Safety gate", ci)
241 self.assertIn("Hermetic safety and authorization tests", ci)
242
243 def test_safety_gate_is_hermetic_for_config_home(self) -> None:
244 ci = load_ci()
245 start = ci.index("Hermetic safety and authorization tests")
246 next_step = ci.index("- name:", start + 1)
247 block = ci[start:next_step]
248 self.assertIn(
249 "sh scripts/with-hermetic-test-home.sh cargo nextest run "
250 "-p codewhale-engine -p codewhale-tui -p codewhale-runtime --lib --locked --no-tests=fail "
251 "-E 'test(auto_review) | test(authority) | test(sandbox)'", block
252 )
253 self.assertIn(
254 "sh scripts/with-hermetic-test-home.sh cargo test -p codewhale-execpolicy --locked",
255 block,
256 )
257 self.assertNotIn("CODEWHALE_HOME:", block)
258 self.assertIn("sh scripts/with-hermetic-test-home.test.sh", ci)
259
260 def test_ci_runs_only_on_dispatch(self) -> None:
261 ci = load_ci()
262 triggers = ci.split("\non:\n", 1)[1].split("\n\n", 1)[0]
263 self.assertEqual(re.findall(r"(?m)^ (\w+):", triggers), ["workflow_dispatch"])
264 self.assertNotIn("pull_request", ci)
265 self.assertNotIn("github.event_name == ", ci)
266
267 def test_shared_process_mode_is_manual_hosted_ubuntu_only_and_replaces_the_sharded_suite(self) -> None:
268 ci = load_ci()
269 self.assertIn("default: nextest", ci)
270 job = ci.split(" test:\n", 1)[1].split(" steps:\n", 1)[0]
271 self.assertIn("runs-on: ubuntu-24.04", job)
272 self.assertIn(SHARED_PROCESS_MODE, job)
273 for name in ("test-ubuntu", "test-macos", "test-windows"):
274 caller = ci.split(f" {name}:\n", 1)[1].split(" uses:", 1)[0]
275 self.assertIn("inputs.workspace_test_mode != 'shared-process-twice'", caller)
276 qualification = named_step(ci, "Shared-process workspace qualification")
277 self.assertIn("if: " + SHARED_PROCESS_MODE, qualification)
278 upload = named_step(ci, "Retain shared-process qualification evidence")
279 self.assertIn("if: always() && " + SHARED_PROCESS_MODE, upload)
280 self.assertIn("if-no-files-found: error", upload)
281 suite = (ROOT / ".github" / "workflows" / "ci-test-suite.yml").read_text(encoding="utf-8")
282 for name, command in (
283 ("Run tests", "cargo nextest run"),
284 ("Run doctests", "cargo test --workspace --all-features --locked --doc"),
285 ):
286 self.assertIn(command, named_step(suite, name))
287
288 def test_shared_process_runs_exact_command_twice_with_fresh_hermetic_homes(self) -> None:
289 proof = run_shared_process_fixture()
290 self.assertEqual(proof["result"].returncode, 0, proof["result"].stderr)
291 self.assertEqual(len(proof["calls"]), 2)
292 self.assertEqual(set(proof["evidence"]["required-tests.txt"].splitlines()), set(ISSUE_6698_TESTS))
293 for call in proof["calls"]:
294 self.assertEqual(call["args"], ["test", "--workspace", "--all-features", "--locked", "--", "--format=pretty"])
295 self.assertIsNone(call["threads"])
296 self.assertEqual(call["stack"], "16777216")
297 self.assertFalse(call["credential_present"])
298 self.assertTrue(call["tmpdir"].startswith("/tmp/cw69."))
299 self.assertLess(len(call["tmpdir"]), 30)
300 self.assertFalse(Path(call["home"]).exists(), "the actual wrapper must clean up its private home")
301 self.assertNotEqual(proof["calls"][0]["home"], proof["calls"][1]["home"])
302 self.assertNotEqual(proof["calls"][0]["tmpdir"], proof["calls"][1]["tmpdir"])
303 for run in (1, 2):
304 self.assertIn(f"run={run} cargo_exit=0 log_exit=0", proof["evidence"]["results.txt"])
305 for identity in ISSUE_6698_TESTS:
306 self.assertIn(f"test {identity} ... ok", proof["evidence"][f"run-{run}.log"])
307
308 def test_macos_budget_runs_on_every_full_dispatch(self) -> None:
309 job = load_ci().split(" macos-budget:\n", 1)[1].split(" steps:\n", 1)[0]
310 self.assertIn("runs-on: macos-latest", job)
311 self.assertIn(" if: needs.changes.outputs.scoped != 'true'\n", job)
312
313 def test_shared_process_retains_failed_first_run_and_still_runs_second_once(self) -> None:
314 proof = run_shared_process_fixture("first_failure")
315 self.assertNotEqual(proof["result"].returncode, 0)
316 self.assertEqual(len(proof["calls"]), 2)
317 self.assertIn("run=1 cargo_exit=101 log_exit=0", proof["evidence"]["results.txt"])
318 self.assertIn("run=2 cargo_exit=0 log_exit=0", proof["evidence"]["results.txt"])
319 self.assertIn("run-1.log", proof["evidence"])
320 self.assertIn("run-2.log", proof["evidence"])
321
322 def test_shared_process_cleans_readonly_directories_without_following_links(self) -> None:
323 proof = run_shared_process_fixture("readonly_cleanup")
324 self.assertEqual(proof["result"].returncode, 0, proof["result"].stderr)
325 self.assertEqual(len(proof["calls"]), 2)
326 self.assertEqual(proof["qualification_removed"], [True, True])
327 self.assertEqual(proof["outside"], {
328 "directory_mode": 0o500, "file_mode": 0o400,
329 "contents": "outside fixture must remain unchanged",
330 })
331 for run in (1, 2):
332 self.assertIn(f"run={run} permission_exit=0 cleanup_exit=0", proof["evidence"]["results.txt"])
333
334 def test_shared_process_cleanup_failure_retains_cargo_failure_and_runs_second(self) -> None:
335 proof = run_shared_process_fixture("cleanup_failure")
336 self.assertNotEqual(proof["result"].returncode, 0)
337 self.assertEqual(len(proof["calls"]), 2)
338 self.assertEqual(proof["qualification_removed"], [False, True])
339 results = proof["evidence"]["results.txt"]
340 self.assertIn("run=1 cargo_exit=101 log_exit=0", results)
341 self.assertIn("run=1 permission_exit=0 cleanup_exit=73", results)
342 self.assertIn("run=2 cargo_exit=0 log_exit=0", results)
343 self.assertIn("run=2 permission_exit=0 cleanup_exit=0", results)
344 self.assertIn("run-1.log", proof["evidence"])
345 self.assertIn("run-2.log", proof["evidence"])
346
347 def test_shared_process_missing_identity_is_not_a_pass(self) -> None:
348 proof = run_shared_process_fixture("missing_identity")
349 self.assertNotEqual(proof["result"].returncode, 0)
350 self.assertEqual(len(proof["calls"]), 2)
351 self.assertEqual(proof["evidence"]["results.txt"].count("result=missing_pass"), 2)
352
353 def test_shared_process_refuses_wrong_revision_and_changed_source(self) -> None:
354 for wrong_sha in ("not-a-sha", "0" * 40):
355 with self.subTest(expected_sha=wrong_sha):
356 proof = run_shared_process_fixture(expected_sha=wrong_sha)
357 self.assertNotEqual(proof["result"].returncode, 0)
358 self.assertEqual(proof["calls"], [])
359 self.assertIn("preflight-error.txt", proof["evidence"])
360 proof = run_shared_process_fixture("source_changed")
361 self.assertNotEqual(proof["result"].returncode, 0)
362 self.assertEqual(len(proof["calls"]), 1)
363 self.assertIn("run=1 source_changed=true", proof["evidence"]["results.txt"])
364 self.assertIn("run=2 not_run=source_changed", proof["evidence"]["results.txt"])
365
366
367 if __name__ == "__main__":
368 unittest.main()
369
369 lines PYTHON