| 1 | |
| 2 | import json |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import signal |
| 6 | import subprocess |
| 7 | import sys |
| 8 | import tempfile |
| 9 | import time |
| 10 | |
| 11 | def until(condition, message, timeout=5): |
| 12 | deadline = time.monotonic() + timeout |
| 13 | while time.monotonic() < deadline: |
| 14 | if condition(): |
| 15 | return |
| 16 | time.sleep(0.025) |
| 17 | raise AssertionError(message) |
| 18 | |
| 19 | def verify(supervisor, crash): |
| 20 | with tempfile.TemporaryDirectory(prefix="cage-supervisor-") as directory: |
| 21 | root = Path(directory) |
| 22 | child = ( |
| 23 | "import os,time,pathlib;" |
| 24 | "pathlib.Path('tool.pid').write_text(str(os.getpid()));" |
| 25 | "time.sleep(1.8);pathlib.Path('late-write').write_text('unexpected')" |
| 26 | ) |
| 27 | middle = ( |
| 28 | "import sys,subprocess; " |
| 29 | f"p=subprocess.Popen([sys.executable,'-c',{child!r}],start_new_session=True);p.wait()" |
| 30 | ) |
| 31 | cli = ( |
| 32 | "import os,sys,subprocess,pathlib;sys.stdin.read();" |
| 33 | "pathlib.Path('cli.pid').write_text(str(os.getpid()));" |
| 34 | f"p=subprocess.Popen([sys.executable,'-c',{middle!r}],start_new_session=True);p.wait()" |
| 35 | ) |
| 36 | proc = subprocess.Popen( |
| 37 | [sys.executable, "-I", supervisor, directory, sys.executable, "-c", cli], |
| 38 | stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) |
| 39 | with proc: |
| 40 | proc.stdin.write(json.dumps("synthetic approved command").encode() + b"\n") |
| 41 | proc.stdin.flush() |
| 42 | until(lambda: (root / "tool.pid").is_file(), "tool did not start") |
| 43 | if crash: |
| 44 | os.kill(int((root / "cli.pid").read_text()), signal.SIGKILL) |
| 45 | else: |
| 46 | proc.stdin.close() |
| 47 | code = proc.wait(timeout=6) |
| 48 | if code == 0: |
| 49 | raise AssertionError("interrupted CLI reported success") |
| 50 | until(lambda: not Path("/proc", (root / "tool.pid").read_text()).exists(), |
| 51 | "detached tool survived supervision") |
| 52 | time.sleep(1.9) |
| 53 | if (root / "late-write").exists(): |
| 54 | raise AssertionError("tool changed project after termination") |
| 55 | |
| 56 | if __name__ == "__main__": |
| 57 | if not sys.platform.startswith("linux"): |
| 58 | raise SystemExit("run inside an isolated Linux guest") |
| 59 | for crash in (False, True): |
| 60 | verify(str(Path(sys.argv[1]).resolve()), crash) |
| 61 | print("CLI crash: PASS" if crash else "SSH disconnect: PASS") |