From cff76d2172582285a5c075a0c5bd49d5942242fb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 05:02:06 +0100 Subject: [PATCH] Kill the mutants of the child-shell reader and the streamed claude, and end a command at its last terminator --- bin/loop_claude/test_loop_claude.py | 11 +++- bin/loop_effects/child_shells.py | 4 +- bin/loop_effects/test_effects.py | 79 ++++++++++++++++++++++++++++- 3 files changed, 89 insertions(+), 5 deletions(-) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index d8047970..4e92dd62 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -787,8 +787,10 @@ class LingeringWorkers(unittest.TestCase): fake = FakeEffects(streams=[streamed]) effects = dataclasses.replace(fake.effects(), now=lambda: clock[0]) with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said: - worker.run_worker("/r", [], {}, pathlib.Path(folder), effects) - record = pathlib.Path(folder, lingering_workers.RECORD) + # The archive folder of a project's first stop doesn't exist yet. + archive = pathlib.Path(folder, "transcripts", "project") + worker.run_worker("/r", [], {}, archive, effects) + record = archive / lingering_workers.RECORD return streamed, said.getvalue(), record.read_text() if record.exists() else "" def shell(self, written=NOW - 1000, runs_busy_tool=False): @@ -821,6 +823,11 @@ class LingeringWorkers(unittest.TestCase): self.assertEqual(self.worker_with(self.RESULT, None, held=[kept])[0].stopped, []) self.assertEqual(self.worker_with(self.RESULT, None, held=[stopped])[0].stopped, [stopped]) + def test_a_worker_reads_on_past_a_check_that_found_it_still_working(self): + clock = [NOW] + effects = dataclasses.replace(FakeEffects(streams=[Streamed(0, None, self.RESULT, clock=clock)]).effects(), now=lambda: clock[0]) + self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), effects)) + def test_a_stop_that_cannot_be_recorded_is_said_on_stderr_and_every_shell_is_still_stopped(self): clock = [NOW] held = [self.shell(), self.shell()] diff --git a/bin/loop_effects/child_shells.py b/bin/loop_effects/child_shells.py index a3dee018..1bbde362 100644 --- a/bin/loop_effects/child_shells.py +++ b/bin/loop_effects/child_shells.py @@ -78,10 +78,10 @@ def output_written(pid: int, started: float) -> float: def command_of(shell_argv: list[str]) -> str: - """What a shell runs: the text of its command line after Claude Code's `eval '`, up to the first ` < /dev/null`, which a call that began in the foreground lacks; the whole line where it holds no `eval`.""" + """What a shell runs: the text of its command line after Claude Code's `eval '`, up to the last ` < /dev/null`, which a call that began in the foreground lacks; the whole line where it holds no `eval`.""" line = " ".join(shell_argv) _, found, command = line.partition(" && eval ") - return (command.split(" < /dev/null", 1)[0].removeprefix("'").removesuffix("'") if found else line)[:COMMAND_CHARS] + return (command.rsplit(" < /dev/null", 1)[0].removeprefix("'").removesuffix("'") if found else line)[:COMMAND_CHARS] def holds_slot(pid: int, slots: pathlib.Path) -> bool: diff --git a/bin/loop_effects/test_effects.py b/bin/loop_effects/test_effects.py index f598aeeb..9351e7f2 100644 --- a/bin/loop_effects/test_effects.py +++ b/bin/loop_effects/test_effects.py @@ -14,7 +14,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from loop_effects import child_shells -from loop_effects.effects import run_python, say, system_effects +from loop_effects.effects import run_python, say, StreamingClaude, system_effects NOW = 1790000000 # How a line said at NOW opens, with clocked's local_time. @@ -196,3 +196,80 @@ class ChildShells(unittest.TestCase): self.assertEqual(shell.wait(timeout=5), -signal.SIGTERM) self.wait_until(lambda: not os.path.exists(f"/proc/{below}")) self.assertIsNone(other.poll()) + + def test_reads_the_parent_and_name_of_a_process_whose_name_holds_parentheses(self): + with open("/proc/self/comm") as handle: + before = handle.read().strip() + self.addCleanup(lambda: pathlib.Path("/proc/self/comm").write_text(before)) + pathlib.Path("/proc/self/comm").write_text("a) (b") + parent, _, name = child_shells.parent_and_start(os.getpid()) + self.assertEqual((parent, name), (os.getppid(), "a) (b")) + + def test_reads_every_argument_of_a_process_including_bytes_that_are_not_utf8(self): + proc = subprocess.Popen(["sh", "-c", "sleep 60; true", "\udcffX"]) + self.addCleanup(lambda: (proc.kill(), proc.wait())) + self.wait_until(lambda: child_shells.argv_of(proc.pid)[:2] == ["sh", "-c"]) + self.assertEqual(child_shells.argv_of(proc.pid), ["sh", "-c", "sleep 60; true", "\ufffdX"]) + self.assertEqual(child_shells.argv_of(2**30), []) + + def test_finds_a_process_below_a_process_below_a_shell(self): + shell = self.started("bash -c 'sleep 60; true'; true") + self.wait_until(lambda: len(child_shells.descendants(shell.pid)) == 2) + + def test_a_process_that_is_gone_holds_no_slot_and_a_vanished_child_does_not_hide_the_shells_after_it(self): + self.assertFalse(child_shells.holds_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]) + + 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"] + self.assertEqual(child_shells.command_of(wrapped), "echo a && eval b < /dev/null") + self.assertEqual(child_shells.command_of(["sleep", "60"]), "sleep 60") + self.assertEqual(child_shells.command_of(["bash", "-c", "x" * 400]), "bash -c " + "x" * 292) + + +class StreamingClaudeLines(unittest.TestCase): + def claude(self, script, args=()): + """A StreamingClaude whose `claude` is a shell script.""" + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + tool = pathlib.Path(folder.name, "claude") + tool.write_text("#!/bin/sh\n" + script) + tool.chmod(0o755) + streaming = StreamingClaude(list(args), folder.name, {"PATH": f"{folder.name}:{os.environ['PATH']}", "MARK": "marked"}) + self.addCleanup(lambda: (streaming.proc.kill(), streaming.proc.wait())) + return streaming, folder.name + + def test_yields_each_line_with_its_newline_and_the_last_one_without_and_replaces_bytes_that_are_not_utf8(self): + streaming, _ = self.claude("printf 'one\\ntwo\\n\\377-tail'") + self.assertEqual(list(streaming.lines(5)), ["one\n", "two\n", "\ufffd-tail"]) + self.assertEqual(streaming.wait(), 0) + + def test_runs_claude_in_the_folder_with_the_arguments_and_the_environment_and_without_input(self): + streaming, folder = self.claude('echo "$PWD $MARK $*"; if read -r line; then echo data; else echo eof; fi', ["-p", "hi"]) + self.assertEqual(list(streaming.lines(5)), [f"{os.path.realpath(folder)} marked -p hi\n", "eof\n"]) + + def test_yields_none_whenever_the_idle_time_passes_without_a_line(self): + streaming, _ = self.claude("sleep 1; echo late") + seen = list(streaming.lines(0.1)) + self.assertEqual([each for each in seen if each is not None], ["late\n"]) + self.assertIn(None, seen[: seen.index("late\n")]) + + def test_lists_the_shells_below_claude_and_stops_one(self): + streaming, _ = self.claude("bash -c 'sleep 60; true' &\necho ready\nwait") + lines = streaming.lines(5) + self.assertEqual(next(lines), "ready\n") + self.wait_for_shells(streaming) + [shell] = streaming.shells() + self.assertEqual(shell.command, "bash -c sleep 60; true") + streaming.stop(shell) + self.assertEqual(streaming.wait(), 0) + + def wait_for_shells(self, streaming): + for _ in range(100): + if streaming.shells(): + return + time.sleep(0.05) + self.fail("the shell did not start")