Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions fork-kit/agent-guards/tests/bg-guard.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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."""

Expand Down
63 changes: 58 additions & 5 deletions fork-kit/agent-guards/tests/guards_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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):
Expand Down Expand Up @@ -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/<name> (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/<name> (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):
Expand Down
Loading