From e00c1b75e396faa5039632978e85d42e5471b712 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:12:34 +0000 Subject: [PATCH] agent-guards tests: hook runs never see the agent that runs the tests config.test.py failed 4 of 15 when an agent ran the suites while another of its own commands ran in the background. The shared fixture ran each hook as a plain child of the test, so bg-guard walked up the process tree to that agent's real Claude Code, found the other command and blocked a Stop event the tests expect to pass quietly. bg-guard.test.py's "no claude parent" case failed the same way. guards_fixture.run_hook now starts every hook under a stand-in Claude Code (/bin/sh named `claude`, nothing else under it), or with parent=None re-parented away so no `claude` is above it at all; the whole process group is killed afterwards. A new bg-guard test runs the fixture from inside a stand-in agent with a background command: the old way blocks, both fixture modes pass. Co-Authored-By: Claude Opus 5.5 --- fork-kit/agent-guards/tests/bg-guard.test.py | 38 ++++++++++- fork-kit/agent-guards/tests/guards_fixture.py | 63 +++++++++++++++++-- 2 files changed, 93 insertions(+), 8 deletions(-) diff --git a/fork-kit/agent-guards/tests/bg-guard.test.py b/fork-kit/agent-guards/tests/bg-guard.test.py index cfb8982d6b072..19237ca6d50af 100644 --- a/fork-kit/agent-guards/tests/bg-guard.test.py +++ b/fork-kit/agent-guards/tests/bg-guard.test.py @@ -32,13 +32,16 @@ def stop(self, sid='s1', busy=True, parent=True, event=None): os.path.join(fx.BIN, HOOK)] env = dict(os.environ, HOME=self.home, BG_EVENT=ev, BG_PY=argv[0], BG_RUNNER=argv[4], BG_LIB=argv[5], BG_MACHINE=argv[6], BG_UID=argv[7], BG_HOOK=argv[8]) - if not parent: - r = subprocess.run(argv, input=ev, capture_output=True, text=True, timeout=60, env=env) - return r + if not parent: # no `claude` above it, also when an agent runs this test + return fx.run_hook(HOOK, ev, self.machine, env=env, parent=None) # a simple command in a pipeline: the shell forks and execs it, so the hook's parent is `claude` script = (BUSY if busy else '') + 'printf "%s" "$BG_EVENT" | "$BG_PY" -I -B -c "$BG_RUNNER" "$BG_LIB" ' \ '"$BG_MACHINE" "$BG_UID" "$BG_HOOK"; r=$?; ' \ + ('kill $B 2>/dev/null; ' if busy else '') + 'exit $r' + return self.under_claude(script, env) + + def under_claude(self, script, env): + """`script` run by the stand-in `claude`, in a process group of its own, ended whole afterwards.""" p = subprocess.Popen([self.claude, '-c', script], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, start_new_session=True) try: @@ -108,6 +111,35 @@ def test_odd_input_passes(self): self.assert_passed(r) +class UnderAnAgent(Base): + """config.test.py failed 4 of 15 when an agent ran the suites with another command of its own in the background: + the shared fixture ran each hook as a child of the test, so bg-guard walked up to that agent's Claude Code, found + the other command and blocked. Here the tests themselves run under such an agent (the stand-in `claude` with a + background command): a hook run as the fixture once ran it blocks; the fixture's runs now never see that agent.""" + + CHILD = '''import json, os, subprocess, sys +sys.path.insert(0, sys.argv[1]) +import guards_fixture as fx +ev = {"hook_event_name": "Stop", "session_id": "under-an-agent"} +old = subprocess.run([sys.executable, "-I", "-B", "-c", fx.RUNNER, fx.LIB, fx.NO_MACHINE, str(os.geteuid()), + os.path.join(fx.BIN, "bg-guard")], input=json.dumps(ev), capture_output=True, text=True, + timeout=60) +runs = [old] + [fx.run_hook("bg-guard", ev, parent=p) for p in ("claude", None)] +print(json.dumps([[r.returncode, r.stdout, r.stderr] for r in runs])) +''' + + def test_the_fixtures_hook_runs_never_see_the_agent_that_runs_the_tests(self): + script = BUSY + '"$BG_PY" -I -B -c "$BG_CHILD" "$BG_TESTS"; r=$?; kill $B 2>/dev/null; exit $r' + env = dict(os.environ, HOME=self.home, BG_PY=sys.executable, BG_CHILD=self.CHILD, + BG_TESTS=os.path.dirname(os.path.abspath(__file__))) + r = self.under_claude(script, env) + self.assertEqual(r.returncode, 0, r.stderr) + old, standin, orphan = (subprocess.CompletedProcess([], *x) for x in json.loads(r.stdout)) + self.assert_blocked(old) # the agent and its background command are there + self.assert_passed(standin) + self.assert_passed(orphan) + + class Count(Base): """count_block itself: the lock, and a count file that is garbled.""" diff --git a/fork-kit/agent-guards/tests/guards_fixture.py b/fork-kit/agent-guards/tests/guards_fixture.py index 614a843dbd2ed..a3f691f2da61b 100644 --- a/fork-kit/agent-guards/tests/guards_fixture.py +++ b/fork-kit/agent-guards/tests/guards_fixture.py @@ -4,8 +4,13 @@ kit's config at a file in a temporary folder (or at one that is not there: the built-in defaults), owned by the user who runs the test, through config.MACHINE_PATH and config.OWNER_UID, the two names that are there for tests. In a separate process the same is done by RUNNER, which then runs the hook file as __main__. No root, no network. + +A hook's answer never depends on who runs the test: run_hook starts it under a stand-in Claude Code (a /bin/sh named +`claude`) with nothing else running under it, or with no `claude` above it at all. Without that, bg-guard walked up +to the real Claude Code of an agent running the tests and blocked whenever that agent had another command running in +the background (config.test.py failed 4 of 15 that way while several suites ran at once). """ -import importlib.machinery, importlib.util, json, os, subprocess, sys +import importlib.machinery, importlib.util, json, os, signal, subprocess, sys sys.dont_write_bytecode = True # the CI runner has no -B: no __pycache__ beside the hooks @@ -23,6 +28,31 @@ sys.argv = [hook] + sys.argv[5:] runpy.run_path(hook, run_name='__main__') ''' +# argv: a stand-in Claude Code that runs "$@" as a child (not exec: `; exit $?` after it) and nothing else +STAND_IN = '"$@"; exit $?' +# argv: run argv[1:] with no `claude` above it: the middle process ends at once, so the one below it is re-parented +# (to init or a subreaper) before it starts the command, and reports the command's exit status through a pipe +ORPHAN = '''import os, sys +r, w = os.pipe() +middle = os.fork() +if middle == 0: + me = os.getpid() + if os.fork(): + os._exit(0) + os.close(r) + while os.getppid() == me: + os.sched_yield() + pid = os.fork() + if pid == 0: + os.execv(sys.argv[1], sys.argv[1:]) + os.write(w, str(os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])).encode()) + os._exit(0) +os.close(w) +os.waitpid(middle, 0) +with os.fdopen(r) as f: + code = f.read() +sys.exit(int(code) if code else 125) +''' def machine_file(folder, section=None, text=None, mode=0o644): @@ -55,13 +85,36 @@ def load_hook(name, machine=NO_MACHINE): return mod -def run_hook(name, event, machine=NO_MACHINE, env=None, cwd=None, timeout=60, args=(), hook=None): - """Run bin/ (or the file `hook`) in a new process with `event` (a dict, or text) on stdin.""" +def run_hook(name, event, machine=NO_MACHINE, env=None, cwd=None, timeout=60, args=(), hook=None, parent='claude'): + """Run bin/ (or the file `hook`) in a new process with `event` (a dict, or text) on stdin. Its parent is a + stand-in Claude Code with nothing else under it (parent='claude'), or it has no `claude` above it (parent=None). + The whole process group is killed afterwards; past `timeout` that raises subprocess.TimeoutExpired.""" text = event if isinstance(event, str) else json.dumps(event) argv = [sys.executable, '-I', '-B', '-c', RUNNER, LIB, machine, str(os.geteuid()), hook or os.path.join(BIN, name), *args] - return subprocess.run(argv, input=text, capture_output=True, text=True, timeout=timeout, cwd=cwd, - env=env if env is not None else dict(os.environ)) + if parent == 'claude': + argv, exe = ['claude', '-c', STAND_IN, 'claude', *argv], '/bin/sh' + elif parent is None: + argv, exe = [sys.executable, '-I', '-B', '-c', ORPHAN, *argv], None + else: + raise ValueError(f'parent: {parent!r}') + p = subprocess.Popen(argv, executable=exe, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, cwd=cwd, env=env if env is not None else dict(os.environ), start_new_session=True) + try: + out, err = p.communicate(text, timeout=timeout) + except subprocess.TimeoutExpired: + _kill(p) + p.communicate() + raise + _kill(p) # anything the hook left running + return subprocess.CompletedProcess(argv, p.returncode, out, err) + + +def _kill(p): + try: + os.killpg(p.pid, signal.SIGKILL) + except OSError: + pass def answer(r):