Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+4 -5
View File
@@ -7,8 +7,8 @@ import os
import pathlib
import signal
import stat
import typing
from machine_load.slots import slot_folder
# The command names of a shell claude starts for a Bash call.
SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"})
@@ -149,15 +149,14 @@ def holds_slot(pid: int, slots: pathlib.Path) -> bool:
return any(has_slot(each, slots) for each in descendants(pid))
def shells_of(claude_pid: int) -> list[Shell]:
"""The shells that are children of claude_pid; none where /proc doesn't exist, as off Linux."""
def shells_of(claude_pid: int, slots: pathlib.Path, children: typing.Callable[[int], list[int]]) -> list[Shell]:
"""The shells that are children of claude_pid, which children lists as children_of does, each knowing whether it holds a heavy slot in the folder slots; none where /proc doesn't exist, as off Linux."""
if not os.path.isdir("/proc"):
return []
slots = slot_folder(os.environ, pathlib.Path.home())
booted = boot_time()
ticks = os.sysconf("SC_CLK_TCK")
shells = []
for pid in children_of(claude_pid):
for pid in children(claude_pid):
found = parent_and_start(pid)
if found is None or found[2] not in SHELL_NAMES:
continue
+4
View File
@@ -9,6 +9,7 @@ from loop_effects.effects import Effects
from claude_code import entries
from failure import Failure
from machine_load import memory
from text_files.file_writes import replace_file
from loop_effects.child_shells import Shell
@@ -51,6 +52,8 @@ class FakeEffects:
self.terminal_folders: list[str] = []
# Each timer started, as its delay and action, which a test runs where the timer fires.
self.timers: list[tuple[float, typing.Callable[[], None]]] = []
# What writes a file: the real writer, until a test sets one that fails.
self.replace_file: typing.Callable[[pathlib.Path, bytes], Failure | None] = replace_file
def effects(self) -> Effects:
return Effects(
@@ -66,6 +69,7 @@ class FakeEffects:
now=lambda: NOW,
on_terminal=lambda: self.terminal,
python=lambda args, cwd: self.answer("python", (args, cwd)),
replace_file=lambda path, data: self.replace_file(path, data),
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
stream_claude=self.stream,
timer=self.timer,
+17 -9
View File
@@ -20,6 +20,8 @@ from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
from project_config.settings import Notifier
from text_files.file_writes import replace_file
from machine_load.slots import slot_folder
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
@@ -62,6 +64,8 @@ class Effects:
on_terminal: typing.Callable[[], bool]
# Runs a Python script in a directory, as run_python does.
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
# Writes a file whole, as text_files.file_writes.replace_file does.
replace_file: typing.Callable[[pathlib.Path, bytes], Failure | None]
sleep: typing.Callable[[float], None]
stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming]
# Starts a timer, as start_timer does.
@@ -96,7 +100,7 @@ class StreamingClaude:
yield pending.decode("utf-8", errors="replace")
def shells(self) -> list[child_shells.Shell]:
return child_shells.shells_of(self.proc.pid)
return child_shells.shells_of(self.proc.pid, slot_folder(os.environ, pathlib.Path.home()), child_shells.children_of)
def stop(self, shell: child_shells.Shell) -> None:
child_shells.stop(shell)
@@ -105,13 +109,16 @@ class StreamingClaude:
return self.proc.wait()
def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS) -> Effects:
"""The effects on this machine; `backends` are the notifiers loop-claude's DM can go through, where a test swaps in one that sends nowhere."""
def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS) -> Effects:
"""The effects on this machine: the configs of its DM are under home, and tmux runs in env.
A test hands in `backends`, the notifiers loop-claude's DM can go through, that send nowhere.
"""
return Effects(
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
claude_on_terminal=claude_on_terminal,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
dm=lambda text, directory: notify(text, directory, pathlib.Path.home(), backends),
dm=lambda text, directory: notify(text, directory, home, backends),
execv=os.execv,
git=git_repo.git,
input=input,
@@ -120,11 +127,12 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC
now=time.time,
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
replace_file=replace_file,
sleep=time.sleep,
stream_claude=StreamingClaude,
timer=start_timer,
tmux=run_tmux,
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode,
tmux=lambda args: run_tmux(args, env),
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args], env=env).returncode,
)
@@ -162,11 +170,11 @@ def start_timer(delay: float, action: typing.Callable[[], None]) -> typing.Calla
return stop
def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]:
"""Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
def run_tmux(args: list[str], env: typing.Mapping[str, str] | None) -> subprocess.CompletedProcess[str]:
"""Runs tmux in env, else in this process's environment, and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
command = ["tmux", *args]
try:
return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
return subprocess.run(command, capture_output=True, encoding="utf-8", env=env, errors="replace", stdin=subprocess.DEVNULL)
except OSError as failure:
return subprocess.CompletedProcess(command, 127, "", f"could not start: {failure}")
+23 -26
View File
@@ -10,7 +10,6 @@ import tempfile
import threading
import time
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -24,7 +23,7 @@ STAMP = f"<{NOW}>"
def clocked():
"""The system's effects on a clock stopped at NOW, which renders a time as <seconds>."""
return dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW)
return dataclasses.replace(system_effects(pathlib.Path.home(), os.environ), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW)
def ticks(pid):
@@ -78,13 +77,10 @@ class Said(unittest.TestCase):
class LocalTime(unittest.TestCase):
def test_renders_seconds_in_the_machines_zone(self):
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
self.addCleanup(time.tzset)
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
zone.start()
self.addCleanup(zone.stop)
time.tzset()
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. A process reads its zone as it starts, so the clock runs in one of its own.
script = f"import os\nimport pathlib\nimport sys\nsys.path.insert(0, {str(pathlib.Path(__file__).resolve().parents[1])!r})\nfrom loop_effects.effects import system_effects\nprint(system_effects(pathlib.Path.home(), os.environ).local_time({NOW}))"
ran = subprocess.run([sys.executable, "-c", script], capture_output=True, check=True, env=os.environ | {"TZ": "XXX-2"}, text=True)
self.assertEqual(ran.stdout, "2026-09-21 16:13:20\n")
@@ -98,7 +94,7 @@ class ClaudeOnTerminal(unittest.TestCase):
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
claude.chmod(0o755)
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
code = system_effects(pathlib.Path.home(), os.environ).claude_on_terminal([], folder, {"PATH": folder})
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
@@ -110,27 +106,28 @@ class TmuxEffect(unittest.TestCase):
tmux = pathlib.Path(folder, "tmux")
tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n")
tmux.chmod(0o755)
return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
return system_effects(pathlib.Path.home(), os.environ | {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
def test_runs_tmux_and_returns_what_it_printed(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
done = system_effects().tmux(["list-windows", "-t", "=loop-proj"])
with tempfile.TemporaryDirectory() as folder:
done = self.fake_tmux(folder).tmux(["list-windows", "-t", "=loop-proj"])
self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n"))
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
with tempfile.TemporaryDirectory() as folder:
effects = self.fake_tmux(folder)
pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n")
self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd")
self.assertEqual(effects.tmux(["list-windows"]).stdout, "caf\ufffd")
def test_reads_a_tmux_that_cannot_start_as_exit_127(self):
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}):
done = system_effects().tmux(["-V"])
with tempfile.TemporaryDirectory() as folder:
done = system_effects(pathlib.Path.home(), os.environ | {"PATH": folder}).tmux(["-V"])
self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, ""))
self.assertIn("could not start", done.stderr)
def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(self.fake_tmux(folder).tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
class PythonEffect(unittest.TestCase):
@@ -169,8 +166,8 @@ class ChildShells(unittest.TestCase):
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
def shell_of(self, proc):
[found] = [each for each in child_shells.shells_of(os.getpid()) if each.pid == proc.pid]
def shell_of(self, proc, slots=pathlib.Path("/no-slots")):
[found] = [each for each in child_shells.shells_of(os.getpid(), slots, child_shells.children_of) if each.pid == proc.pid]
return found
def test_reads_a_child_shells_command_and_whether_a_busy_tool_runs_below_it(self):
@@ -189,12 +186,12 @@ class ChildShells(unittest.TestCase):
def test_a_shell_below_which_a_process_holds_a_heavy_slot_file_holds_a_slot_and_runs_no_busy_tool(self):
# run-heavy replaces itself with its command, which keeps the slot's file open.
with tempfile.TemporaryDirectory() as state, unittest.mock.patch.dict(os.environ, {"XDG_STATE_HOME": state}):
with tempfile.TemporaryDirectory() as state:
slot = pathlib.Path(state, "run-heavy", "slot-0")
slot.parent.mkdir()
holding = self.started(f"exec 9>{slot}; sleep 60; true")
plain = self.started("sleep 60; true")
self.assertEqual([(self.shell_of(each).holds_slot, self.shell_of(each).runs_busy_tool) for each in (holding, plain)], [(True, False), (False, False)])
self.assertEqual([(self.shell_of(each, slot.parent).holds_slot, self.shell_of(each, slot.parent).runs_busy_tool) for each in (holding, plain)], [(True, False), (False, False)])
def test_a_shell_written_output_is_the_modified_time_of_its_output_file_and_else_its_start(self):
with tempfile.NamedTemporaryFile() as output:
@@ -264,8 +261,8 @@ class ChildShells(unittest.TestCase):
self.assertFalse(child_shells.has_slot(2**30, pathlib.Path("/")))
shell = self.started("sleep 60; true")
real = child_shells.children_of
with unittest.mock.patch.object(child_shells, "children_of", side_effect=lambda pid: [2**30, shell.pid] if pid == os.getpid() else real(pid)):
self.assertEqual([each.pid for each in child_shells.shells_of(os.getpid())], [shell.pid])
children = lambda pid: [2**30, shell.pid] if pid == os.getpid() else real(pid)
self.assertEqual([each.pid for each in child_shells.shells_of(os.getpid(), pathlib.Path("/no-slots"), children)], [shell.pid])
def test_command_of_takes_the_text_of_the_last_eval_wrapper_and_else_the_whole_line(self):
wrapped = ["/bin/bash", "-c", "source /s && eval 'echo a && eval b < /dev/null' < /dev/null && pwd -P >| /t"]
@@ -330,7 +327,7 @@ class Timer(unittest.TestCase):
self.assertTrue(ran.wait(10))
def test_the_systems_timer_runs_on_a_daemon_thread_so_a_loop_that_exits_while_it_waits_does_not_wait_for_it(self):
self.assertIs(system_effects().timer, start_timer)
self.assertIs(system_effects(pathlib.Path.home(), os.environ).timer, start_timer)
before = set(threading.enumerate())
stop = start_timer(60, lambda: None)
self.addCleanup(stop)