Run every claude the loop starts in a Claude home generated outside the clone
CI / tests (pull_request) Successful in 4m45s

This commit is contained in:
2026-12-04 01:07:03 +01:00
parent 2460b9e132
commit 0203a8e0b3
48 changed files with 703 additions and 369 deletions
+3
View File
@@ -34,6 +34,8 @@ class FakeEffects:
# Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session.
self.tmux_calls: list[list[str]] = []
self.tmux_version = tmux_version
# Why a claude cannot run in the loop's Claude home; None while one can.
self.home_unready: str | None = None
self.windows = windows
# The checkout the session's @loop-root option names.
self.owner = owner
@@ -58,6 +60,7 @@ class FakeEffects:
def effects(self) -> Effects:
return Effects(
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
claude_home=lambda: self.home_unready,
claude_on_terminal=self.on_terminal_claude,
discard_typed=lambda: self.calls.append(("discard_typed", None)),
dm=self.dm,
+14 -5
View File
@@ -16,6 +16,7 @@ import typing
from notifier.notify import Backend, BACKENDS, notify
from loop_effects import child_shells
from loop_state.paths import claude_home, in_claude_home, RELEASE_ROOT, with_release_tools
from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
@@ -23,7 +24,7 @@ from project_config.settings import Notifier
from text_files.file_writes import replace_file
from forge.commands import Run, runner
from machine_load.slots import slot_folder
from loop_state.paths import with_release_tools
from claude_home.home import unready
# Seconds before a Python script build-release runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
@@ -52,6 +53,8 @@ class Streaming(typing.Protocol):
@dataclasses.dataclass(frozen=True)
class Effects:
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
# Builds or refreshes the loop's Claude home, as claude_home.home.unready does: why a claude cannot run there yet, else None.
claude_home: typing.Callable[[], str | None]
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
# Drops what was typed on the terminal and not yet read.
discard_typed: typing.Callable[[], None]
@@ -84,7 +87,7 @@ class Effects:
class StreamingClaude:
def __init__(self, args: list[str], cwd: str, env: dict[str, str]) -> None:
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env=with_release_tools({**os.environ, **env}), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, bufsize=0)
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env=claude_environment({**os.environ, **env}, pathlib.Path.home()), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, bufsize=0)
def lines(self, idle: float) -> typing.Iterable[str | None]:
# Reads the pipe's file descriptor itself. select cannot see what a buffered reader holds.
@@ -116,12 +119,13 @@ class StreamingClaude:
def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS, forge_timeout: float = FORGE_TIMEOUT) -> Effects:
"""The effects on this machine: the configs of its DM are under home, and tmux and the one-shot headless claude run in env, while a streaming claude and one on a terminal run in this process's environment plus what their caller adds. Every claude starts with the release's tools first on its `PATH`.
"""The effects on this machine: the configs of its DM are under home, and tmux and the one-shot headless claude run in env, while a streaming claude and one on a terminal run in this process's environment plus what their caller adds. Every claude starts in the loop's Claude home, with the release's tools first on its `PATH`.
A test hands in `backends` that don't send anything, in place of the notifiers build-release's DM goes through. It hands in a short `forge_timeout`, so a command that outlasts it ends quickly.
"""
return Effects(
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, env=with_release_tools(env), input=stdin, text=True),
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, env=claude_environment(env, home), input=stdin, text=True),
claude_home=lambda: unready(claude_home(env, home), RELEASE_ROOT, lambda args: subprocess.run(["claude", *args], capture_output=True, env=claude_environment(env, home), stdin=subprocess.DEVNULL, text=True), git_repo.git),
claude_on_terminal=claude_on_terminal,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
dm=lambda text, directory: notify(text, directory, home, env, backends),
@@ -143,12 +147,17 @@ def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends:
)
def claude_environment(env: typing.Mapping[str, str], home: pathlib.Path) -> dict[str, str]:
"""env as every claude the loop starts gets it: the loop's Claude home under home, or where env's XDG_DATA_HOME says, and the release's tools first on `PATH`."""
return in_claude_home(with_release_tools(env), home)
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
try:
return subprocess.run(["claude", *args], cwd=cwd, env=with_release_tools({**os.environ, **env})).returncode
return subprocess.run(["claude", *args], cwd=cwd, env=claude_environment({**os.environ, **env}, pathlib.Path.home())).returncode
finally:
signal.signal(signal.SIGINT, previous)
+39 -1
View File
@@ -14,8 +14,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_effects import child_shells
from loop_state.paths import claude_home, RELEASE_ROOT, without_xdg_folders
from failure import Failure
from loop_state.paths import RELEASE_ROOT
from loop_effects.effects import run_python, say, start_timer, StreamingClaude, system_effects
NOW = 1790000000
@@ -109,6 +109,14 @@ class ClaudeOnTerminal(unittest.TestCase):
system_effects(pathlib.Path.home(), os.environ).claude_on_terminal([], folder, {"PATH": f"{folder}:/usr/bin:/bin"})
self.assertEqual(pathlib.Path(folder, "path").read_text(), f"{RELEASE_ROOT}/bin:{folder}:/usr/bin:/bin\n")
def test_starts_claude_in_the_loops_claude_home(self):
with tempfile.TemporaryDirectory() as folder:
claude = pathlib.Path(folder, "claude")
claude.write_text('#!/bin/sh\necho "$CLAUDE_CONFIG_DIR" > home\n')
claude.chmod(0o755)
system_effects(pathlib.Path.home(), os.environ).claude_on_terminal([], folder, {"PATH": f"{folder}:/usr/bin:/bin", "XDG_DATA_HOME": "/x/data"})
self.assertEqual(pathlib.Path(folder, "home").read_text(), "/x/data/build-release/claude-home\n")
class HeadlessClaude(unittest.TestCase):
def test_runs_claude_in_the_folder_with_its_input_and_the_releases_tools_first_on_its_path(self):
@@ -119,6 +127,32 @@ class HeadlessClaude(unittest.TestCase):
done = system_effects(pathlib.Path.home(), os.environ | {"PATH": f"{folder}:/usr/bin:/bin"}).claude(["-p"], folder, "asked")
self.assertEqual(done.stdout, f"{os.path.realpath(folder)} -p asked {RELEASE_ROOT}/bin:{folder}:/usr/bin:/bin\n")
def test_runs_claude_in_the_loops_claude_home_under_the_home_folder_it_is_given(self):
with tempfile.TemporaryDirectory() as folder:
claude = pathlib.Path(folder, "claude")
claude.write_text('#!/bin/sh\necho "$CLAUDE_CONFIG_DIR"\n')
claude.chmod(0o755)
done = system_effects(pathlib.Path("/home/me"), without_xdg_folders(os.environ) | {"PATH": f"{folder}:/usr/bin:/bin"}).claude(["-p"], folder, "asked")
self.assertEqual(done.stdout, "/home/me/.local/share/build-release/claude-home\n")
class ClaudeHomeEffect(unittest.TestCase):
def test_builds_the_loops_claude_home_from_the_release_root_with_claude_run_in_that_home(self):
with tempfile.TemporaryDirectory() as folder:
claude = pathlib.Path(folder, "claude")
claude.write_text(f'#!/bin/sh\necho "$CLAUDE_CONFIG_DIR $*" >> {folder}/ran\necho \'{{"loggedIn": true}}\'\n')
claude.chmod(0o755)
home = pathlib.Path(folder, "home")
built = home / ".local" / "share" / "build-release" / "claude-home"
reason = system_effects(home, without_xdg_folders(os.environ) | {"PATH": f"{folder}:{os.environ['PATH']}"}).claude_home()
self.assertIsNone(reason)
self.assertEqual((built / "CLAUDE.md").resolve(), RELEASE_ROOT / "CLAUDE.md")
ran = pathlib.Path(folder, "ran").read_text().splitlines()
self.assertEqual(ran[-1], f"{built} auth status")
self.assertIn(f"{built} plugin install code-review@claude-plugins-official", ran)
class ForgeEffect(unittest.TestCase):
def test_runs_the_forges_cli_in_the_checkout_it_is_given(self):
@@ -349,6 +383,10 @@ class StreamingClaudeLines(unittest.TestCase):
streaming, folder = self.claude('echo "$PATH"')
self.assertEqual(list(streaming.lines(5)), [f"{RELEASE_ROOT}/bin:{folder}:{os.environ['PATH']}\n"])
def test_starts_claude_in_the_loops_claude_home(self):
streaming, _ = self.claude('echo "$CLAUDE_CONFIG_DIR"')
self.assertEqual(list(streaming.lines(5)), [f"{claude_home(os.environ, pathlib.Path.home())}\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))