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
+4
View File
@@ -3,6 +3,10 @@ import os
import pathlib
import sys
# Said before the first import of the setup's code, which an older Python cannot read.
if sys.version_info < (3, 14):
sys.exit(f"build-epic needs Python 3.14 or later as python3 on PATH; it found Python {sys.version.split()[0]}")
LAUNCHER = pathlib.Path(__file__).resolve()
sys.path.insert(0, str(LAUNCHER.parent))
+4
View File
@@ -3,6 +3,10 @@ import os
import pathlib
import sys
# Said before the first import of the setup's code, which an older Python cannot read.
if sys.version_info < (3, 14):
sys.exit(f"build-release needs Python 3.14 or later as python3 on PATH; it found Python {sys.version.split()[0]}")
LAUNCHER = pathlib.Path(__file__).resolve()
sys.path.insert(0, str(LAUNCHER.parent))
+3 -3
View File
@@ -122,9 +122,9 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
return Stop(0 if words in (["-h"], ["--help"]) else 1, HELP)
if writes or closes:
return epic_written(words[0], writes, paths, env, backend, stdin)
# Before anything starts: a clone, a claude session or a tmux window.
if not dry_run_asked and (reason := tmux.unusable(effects.tmux, chunk_prompt.DRIVER)):
return Stop(1, reason)
# Before anything starts: a clone, a claude session or a tmux window. One stop names everything that is the person's to do. A dry run opens no window, but its planning runs claude.
if needs := [reason for reason in (None if dry_run_asked else tmux.unusable(effects.tmux, chunk_prompt.DRIVER), effects.claude_home()) if reason]:
return Stop(1, "\n".join(needs))
config = load(paths.home, env)
if isinstance(config, Failure):
return Stop(1, config.reason)
+18 -2
View File
@@ -139,6 +139,22 @@ class TheCommand(BuildEpicTest):
self.assertEqual(code, 1)
self.assertIn("build-epic runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1", err)
def test_refuses_until_a_claude_can_run_in_the_loops_claude_home_and_names_all_that_is_the_persons_at_once(self) -> None:
fake = FakeEffects(tmux_version="tmux 3.1")
fake.home_unready = "nobody is signed in"
code, _, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 1)
self.assertIn("it found tmux 3.1\nnobody is signed in\n", err)
self.assertEqual(fake.calls, [])
def test_a_dry_run_too_refuses_until_a_claude_can_run_in_the_loops_claude_home(self) -> None:
fake = FakeEffects(on_terminal=False, tmux_version="")
fake.home_unready = "nobody is signed in"
code, _, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual(code, 1)
self.assertIn("nobody is signed in\n", err)
self.assertNotIn("tmux", err)
def test_starts_the_chunks_and_says_why_each_other_issue_waits(self) -> None:
fake = FakeEffects(on_terminal=False)
code, out, _ = self.run_main(["ABC-12"], fake, {"BUILD_RELEASE_WORKER_MODEL": "m"})
@@ -247,8 +263,8 @@ class ACycleOfAChunkWithoutARepo(BuildEpicTest):
def test_the_records_are_the_epics_scoring_and_decisions_then_the_humans_rules(self) -> None:
self.description = DESCRIPTION + "\n## Scoring\nE + I, bar 4.\n\n## Decisions\n### Merges squash\nAlways.\n"
(self.home / ".claude").mkdir()
(self.home / ".claude/CLAUDE.md").write_text("# Global\n", encoding="utf-8")
(self.home / ".local" / "share" / "build-release" / "claude-home").mkdir(parents=True)
(self.home / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("# Global\n", encoding="utf-8")
self.assertEqual(self.cycle().records, "From the epic ABC-12's description, ## Scoring:\nE + I, bar 4.\n\nFrom the epic ABC-12's description, ## Decisions:\n### Merges squash\nAlways.\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
def test_stops_where_a_section_of_the_epics_records_cannot_be_read(self) -> None:
+3 -3
View File
@@ -71,9 +71,9 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
loop_run = loop_run_from(argv, cwd, effects)
if isinstance(loop_run, Stop):
return loop_run
# Before anything starts: a worktree, a claude session or a tmux window.
if reason := tmux.unusable(effects.tmux, fresh_prompt.DRIVER):
return Stop(1, reason)
# Before anything starts: a worktree, a claude session or a tmux window. One stop names everything that is the person's to do.
if needs := [reason for reason in (tmux.unusable(effects.tmux, fresh_prompt.DRIVER), effects.claude_home()) if reason]:
return Stop(1, "\n".join(needs))
if loop_run.chunk is None:
return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks)
pane = env.get("TMUX_PANE")
+11 -2
View File
@@ -137,6 +137,15 @@ class WindowStarts(unittest.TestCase):
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), ""))
self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], []))
def test_refuses_to_start_anything_until_a_claude_can_run_in_the_loops_claude_home_and_names_all_that_is_the_persons_at_once(self):
fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c")
fake.home_unready = "nobody is signed in"
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\nnobody is signed in"), ""))
fake = FakeEffects(git=["/r\n"])
fake.home_unready = "nobody is signed in"
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "nobody is signed in"), ""))
self.assertEqual(self.asked, [])
def test_prints_the_help_without_tmux(self):
fake = FakeEffects(tmux_version="")
self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP))
@@ -172,7 +181,7 @@ class WindowStarts(unittest.TestCase):
run_cycle=lambda cycle: concluded.pop(0), closed_cycle=lambda *args: closed.pop(0), check_routing=lambda *args: None)
with contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME, {}), launcher, CWD, effects, taken)
loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME, {}), env=env, launcher=launcher, effects=effects)
loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".local" / "share" / "build-release" / "claude-home" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME, {}), env=env, launcher=launcher, effects=effects)
self.assertEqual(stop, Stop(0, ""))
self.assertEqual(cycles, [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
self.assertEqual(started, [(main.LoopRun(2, "/r", "do it", "", chunk="item-3"), True, loop.paths, env, launcher, effects)])
@@ -189,7 +198,7 @@ class WindowStarts(unittest.TestCase):
return lambda *args: calls.append((name, *args)) or answers[name](*args)
stop = main.run_loop(["--chunk", "item-3", "do it"], env, home, launcher, CWD, effects, steps(lambda *args: self.fail(args), **{name: step(name) for name in answers}))
self.loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=home, env=env, launcher=launcher, effects=effects)
self.loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".local" / "share" / "build-release" / "claude-home" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=home, env=env, launcher=launcher, effects=effects)
return stop, calls
def test_a_window_loop_hands_each_step_of_a_cycle_what_the_steps_before_it_made(self):
+1 -1
View File
@@ -56,7 +56,7 @@ class ExitContract(unittest.TestCase):
("agent_cycle/run.py", "close", "1", "failure.reason", read),
("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("build_release/loop/checkout.py", "checkout_root", "1", "found.reason", git),
("build_release/loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("build_release/loop/main.py", "run_loop", "1", "'\\n'.join(needs)", "tmux is missing or older than 3.2, the loop's Claude home cannot be built, or nobody is signed in there"),
("build_release/loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how build-release starts itself", "--chunk is given outside a tmux window"),
("build_release/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("build_release/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
+7 -2
View File
@@ -27,7 +27,11 @@ chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C, eit
that one chunk.
Words: the setup's CLAUDE.md → "Vocabulary".
build-release needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in
build-release runs every claude in the loop's Claude home, ~/.local/share/build-release/claude-home,
which it builds from the clone it ships in before it starts anything. Until someone has signed in
there, it stops and prints the line that does so. README.md → Install says what the home holds.
build-release needs tmux 3.2 or later, and checks that first too. Each chunk runs in
its own window of one tmux session per project, named loop-<key>, such as loop-claude-config. <key>
is the checkout's path relative to ~/code, or to / outside it, with a dash for each character other
than a letter, a digit, _ or -. The tmux session's @loop-root option names its checkout, and a
@@ -169,7 +173,8 @@ window closes, so the next build-release <task> reads the plan again.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- tmux is missing or older than 3.2
- tmux is missing or older than 3.2, the loop's Claude home cannot be built, or nobody is signed
in there
- --chunk is given outside a tmux window
- a chunk's window cannot be started, as when the project's config cannot be read, or the tmux
session runs another checkout's chunks
+35 -8
View File
@@ -54,6 +54,14 @@ FAKE_CLAUDE = """#!{python}
import json, os, pathlib, signal, sys, time
argv = sys.argv[1:]
# What claude_home.home asks while it builds the loop's Claude home: someone is signed in, and each plugin installs.
if argv[:1] == ["plugin"]:
sys.exit(0)
if argv == ["auth", "status"]:
print(json.dumps({{"loggedIn": os.environ.get("FAKE_CLAUDE_SIGNED_OUT") is None}}))
if os.environ.get("FAKE_CLAUDE_VANISHES"):
os.unlink(sys.argv[0])
sys.exit(0)
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
steps = json.loads(scenario.read_text())
@@ -78,7 +86,7 @@ def session():
def transcript():
return pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl"
return pathlib.Path(os.environ["CLAUDE_CONFIG_DIR"]) / "projects" / "-fake" / f"{{session()}}.jsonl"
def append(*entries):
@@ -328,7 +336,7 @@ class Checkout:
return self.home / ".config/build-release" / "models.json"
def transcripts(self):
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
return sorted((self.home / ".local/share/build-release/claude-home" / "projects").glob("*/*.jsonl"))
def archive(self):
return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".local/state/build-release" / "transcripts"))
@@ -442,8 +450,6 @@ class Cycles(unittest.TestCase):
(checkout.root / "sub").mkdir()
(checkout.root / "docs").mkdir()
(checkout.root / "docs" / "decisions.md").write_text("# Decisions\n")
(checkout.home / ".claude").mkdir()
(checkout.home / ".claude" / "CLAUDE.md").write_text("# Global instructions\n")
run = checkout.run([
worker(say="started"), judge(evidence="started"),
worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"),
@@ -767,7 +773,8 @@ class Cycles(unittest.TestCase):
def test_retries_a_worker_claude_cannot_start(self):
checkout = Checkout(self)
(checkout.temp / "fake-bin" / "claude").unlink()
# The claude that answers for the loop's Claude home is gone once the worker starts.
checkout.env["FAKE_CLAUDE_VANISHES"] = "1"
run = checkout.run([])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.sleeps, [60, 60])
@@ -907,6 +914,21 @@ class Windows(unittest.TestCase):
run = checkout.run([], argv=[TASK])
self.assertEqual((run.code, run.stderr), (1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
def test_builds_the_loops_claude_home_from_the_clone_then_refuses_to_start_until_someone_signs_in_there(self):
checkout = self.checkout()
checkout.env["FAKE_CLAUDE_SIGNED_OUT"] = "1"
checkout.env["FAKE_TMUX_VERSION"] = "tmux 3.1c"
home = checkout.home / ".local/share/build-release/claude-home"
run = checkout.run([], argv=[TASK])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.splitlines(), [
"build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c",
f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={home} claude` and type /login there, once",
])
self.assertEqual((home / "CLAUDE.md").resolve(), BIN.parent / "CLAUDE.md")
self.assertIn(f"{BIN}/rule-hook", (home / "settings.json").read_text())
self.assertFalse((checkout.home / ".claude").exists())
def test_marks_the_window_while_an_interrupt_waits_and_rings_its_bell(self):
checkout = self.checkout()
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?")], chunk="item-4")
@@ -1016,7 +1038,7 @@ class Interrupt(unittest.TestCase):
class Models(unittest.TestCase):
def catalog(self, checkout):
folder = checkout.home / ".claude" / "cache" / "model-catalog"
folder = checkout.home / ".local/share/build-release/claude-home" / "cache" / "model-catalog"
folder.mkdir(parents=True)
(folder / "old.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "old-model"}]}}, "fetchedAt": 1}))
(folder / "new.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "model-a", "name": "A"}, {"id": "model-b", "name": "B"}]}}, "fetchedAt": 2}))
@@ -1079,7 +1101,7 @@ class Models(unittest.TestCase):
checkout = Checkout(self)
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
self.catalog(checkout)
catalog = checkout.home / ".claude" / "cache" / "model-catalog" / "new.json"
catalog = checkout.home / ".local/share/build-release/claude-home" / "cache" / "model-catalog" / "new.json"
for shape in ({"catalog": {"config": {"models": []}}}, {"catalog": None}, {"catalog": {"config": []}}, {"catalog": {"config": {"models": "x"}}}):
with self.subTest(shape=shape):
catalog.write_text(json.dumps({**shape, "fetchedAt": 3}))
@@ -1103,8 +1125,13 @@ class Models(unittest.TestCase):
class Reload(unittest.TestCase):
def test_an_edit_takes_effect_at_the_next_cycle_boundary_once_it_answers_help(self):
checkout = Checkout(self)
copy = checkout.temp / "bin"
# A clone of its own, since the loop's Claude home is built from the commit and the settings.json of the clone the script ships in.
clone = checkout.temp / "clone"
copy = clone / "bin"
shutil.copytree(BIN, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*"))
(clone / "settings.json").write_text("{}\n")
for command in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "A release"]):
subprocess.run(["git", *command], check=True, cwd=clone, env=checkout.env)
checkout.script = copy / "build-release"
checkout.env["FAKE_CLAUDE_EDIT"] = str(copy)
run = checkout.run([
+6 -5
View File
@@ -24,6 +24,7 @@ from transcript_archive.read import latest_worker
from chunk_driver.this_loop import Loop
from transcript_archive.project_key import project_key
from model_routing.ladder_file import project_ladder_file, read_ladder
from loop_state.paths import RELEASE_ROOT
from model_routing.route import Route, route_from
from loop_effects.effects import say
from agent_cycle.stop import Stop
@@ -95,13 +96,13 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
def cycle_of(loop: Loop, routing: Routing, route: Route, archive_folder: pathlib.Path, *, task: str, facts: str, premises: str, records: str, unfinished_evidence: str, prompts: WorkerPrompts, taken_in: typing.Callable[[list[Entry]], TakenIn]) -> Cycle:
"""The cycle that runs in the loop's window on route. The keyword arguments are what the entry point alone knows; Cycle says what each is."""
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge=judge_rung(routing.ladder, routing.models.judge), premises=premises, project=routing.project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=task, prompts=prompts, taken_in=taken_in, unfinished_evidence=unfinished_evidence, window=loop.window)
return Cycle(config=setup_version(RELEASE_ROOT, loop.effects.git), effects=loop.effects, facts=facts, judge=judge_rung(routing.ladder, routing.models.judge), premises=premises, project=routing.project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=task, prompts=prompts, taken_in=taken_in, unfinished_evidence=unfinished_evidence, window=loop.window)
def setup_version(claude_dir: pathlib.Path, git: Git) -> str:
"""The release and commit of this setup that the worker's claude reads, as `v0.8.0 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. Where git can't tell, `unknown` and why."""
described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir))
commit = git("rev-parse", "HEAD", cwd=str(claude_dir))
def setup_version(clone: pathlib.Path, git: Git) -> str:
"""The release and commit of clone, the setup the worker's claude reads through its home's links, as `v0.8.0 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. Where git can't tell, `unknown` and why."""
described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(clone))
commit = git("rev-parse", "HEAD", cwd=str(clone))
if isinstance(described, Failure):
return unknown_version(described)
if isinstance(commit, Failure):
+2 -2
View File
@@ -21,7 +21,7 @@ from loop_effects.doubles import FakeEffects, NOW, STAMP
from git_cli import git_repo
from chunk_driver.project.model_choice import Models
from transcript_archive import outcomes, write
from loop_state.paths import paths_from
from loop_state.paths import paths_from, RELEASE_ROOT
from model_routing.ladder import ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from text_files.file_writes import replace_file
@@ -148,7 +148,7 @@ class CycleStart(unittest.TestCase):
cycle = cycle_start.cycle_of(loop, self.ROUTING, route, archive, task="the task", facts="the facts", premises="the premises", records="the records", unfinished_evidence="the evidence", prompts=prompts, taken_in=taken_in)
self.assertEqual(cycle, Cycle(config="v0.1.0 (abc)", effects=effects, facts="the facts", judge=Rung("judge-model"), premises="the premises", project=OPUS_PROJECT, project_archive=archive, records="the records", root="/r",
route=route, session=loop.session, task="the task", prompts=prompts, taken_in=taken_in, unfinished_evidence="the evidence", window=loop.window))
self.assertEqual(asked, ["/h/.claude", "/h/.claude"])
self.assertEqual(asked, [str(RELEASE_ROOT), str(RELEASE_ROOT)])
class Routes(unittest.TestCase):
View File
+112
View File
@@ -0,0 +1,112 @@
"""Builds the loop's Claude home: the folder every claude the loop starts reads in place of the person's own `~/.claude`.
The home lies outside the clone, so the clone stays a clean checkout. It holds links to the clone's LINKED files, a `settings.json` generated from the clone's, and what Claude Code itself keeps in its home: the plugins, the sign-in and the transcripts. docs/decisions.md → `Claude Code in a home of its own` says what loads from such a home.
"""
import collections.abc
import fcntl
import json
import pathlib
import shlex
import subprocess
import typing
from failure import Failure
from text_files.file_writes import replace_file
# What the home links to in the clone: the instruction files Claude Code reads from its home.
LINKED = ("CLAUDE.md", "agents", "rules", "skills")
# In a value of the clone's settings.json, the clone's folder. Every value that holds it is a shell command, such as a hook's.
CLONE = "{clone}"
# The file in the home that names the clone and the commit the home was built from.
BUILT_FROM = "built-from"
# Runs `claude` with these arguments in the home.
Claude = collections.abc.Callable[[list[str]], subprocess.CompletedProcess[str]]
class Git(typing.Protocol):
def __call__(self, *args: str, cwd: str | None = None) -> str | Failure: ...
def unready(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) -> str | None:
"""Builds the home from clone, or refreshes it where the clone's commit changed since. Then why a claude cannot run in the home yet, said for the person to act on; None where one can."""
try:
built = refreshed(home, clone, claude, git)
if isinstance(built, Failure):
return f"could not build the loop's Claude home, {home}: {built.reason}"
status = claude(["auth", "status"]).stdout
except OSError as failure:
return f"could not build the loop's Claude home, {home}: {failure}"
if signed_in(status):
return None
# /login is typed in a claude that runs in the home: lilleman chose it over a token file on 2026-12-03.
return f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={shlex.quote(str(home))} claude` and type /login there, once"
def signed_in(status: str) -> bool:
"""Whether `claude auth status` printed that someone is signed in, by a /login or by a token in the environment."""
try:
read = json.loads(status)
except ValueError:
return False
return isinstance(read, dict) and read.get("loggedIn") is True
def refreshed(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) -> Failure | None:
commit = git("rev-parse", "HEAD", cwd=str(clone))
if isinstance(commit, Failure):
return commit
built_from = f"{clone} at {commit.strip()}\n"
home.mkdir(parents=True, exist_ok=True)
# Several loops start at once after an update: one refreshes the home, and the others wait and find it done.
with open(home / ".refresh-lock", "w", encoding="utf-8") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
stamp = home / BUILT_FROM
if stamp.is_file() and stamp.read_text(encoding="utf-8") == built_from:
return None
# The stamp is written last, so a refresh that failed halfway runs again.
return linked(home, clone) or settings_written(home, clone) or plugins_installed(clone, claude) or replace_file(stamp, built_from.encode())
def linked(home: pathlib.Path, clone: pathlib.Path) -> Failure | None:
for name in LINKED:
link = home / name
# Only a link is replaced: a file or folder someone put there fails the build, and stays.
if link.is_symlink():
link.unlink()
link.symlink_to(clone / name)
return None
def settings_written(home: pathlib.Path, clone: pathlib.Path) -> Failure | None:
"""Writes the home's settings.json: the clone's, with the clone's folder in place of CLONE, and the model the home's file holds."""
settings = placed(json.loads((clone / "settings.json").read_text(encoding="utf-8")), shlex.quote(str(clone)))
generated = home / "settings.json"
# Claude Code writes a /model pick into the home's file, so a refresh keeps it.
if generated.is_file() and "model" in (old := json.loads(generated.read_text(encoding="utf-8"))):
settings["model"] = old["model"]
return replace_file(generated, (json.dumps(settings, indent=2, sort_keys=True) + "\n").encode())
def placed(value: typing.Any, clone: str) -> typing.Any:
if isinstance(value, str):
return value.replace(CLONE, clone)
if isinstance(value, list):
return [placed(each, clone) for each in value]
if isinstance(value, dict):
return {key: placed(each, clone) for key, each in value.items()}
return value
def plugins_installed(clone: pathlib.Path, claude: Claude) -> Failure | None:
"""Installs every plugin the clone's settings.json enables, each marketplace first: `claude plugin install` finds a plugin only in a marketplace already added."""
settings = json.loads((clone / "settings.json").read_text(encoding="utf-8"))
plugins = sorted(plugin for plugin, enabled in settings.get("enabledPlugins", {}).items() if enabled)
marketplaces = sorted({plugin.split("@")[-1] for plugin in plugins})
commands = [["plugin", "marketplace", "add", settings["extraKnownMarketplaces"][name]["source"]["repo"]] for name in marketplaces]
for command in commands + [["plugin", "install", plugin] for plugin in plugins]:
done = claude(command)
if done.returncode:
said = " ".join((done.stderr or done.stdout).split())
return Failure(f"claude {' '.join(command)} failed: {said}")
return None
+153
View File
@@ -0,0 +1,153 @@
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from claude_home.home import unready
SETTINGS = {
"enabledPlugins": {"code-review@official": True, "frontend-design@official": False, "lsp@other": True},
"extraKnownMarketplaces": {"official": {"source": {"repo": "anthropics/official", "source": "github"}}, "other": {"source": {"repo": "someone/other", "source": "github"}}, "unused": {"source": {"repo": "someone/unused", "source": "github"}}},
"hooks": {"PreToolUse": [{"hooks": [{"command": "{clone}/bin/rule-hook", "type": "command"}]}]},
"tui": "fullscreen",
}
SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "claude.ai"})
SIGNED_OUT = json.dumps({"loggedIn": False, "authMethod": "none"})
class Home(unittest.TestCase):
def setUp(self) -> None:
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
self.clone = self.temp / "the clone"
for folder in ("agents", "rules", "skills"):
(self.clone / folder).mkdir(parents=True)
(self.clone / "CLAUDE.md").write_text("# The setup's rules\n", encoding="utf-8")
(self.clone / "settings.json").write_text(json.dumps(SETTINGS), encoding="utf-8")
self.home = self.temp / "share" / "claude-home"
self.commit: str | Failure = "1a2b3c\n"
self.status = SIGNED_IN
# The exit code of each `claude plugin` command, by its last argument; 0 for one not named.
self.exits: dict[str, int] = {}
self.ran: list[list[str]] = []
def claude(self, args: list[str]) -> subprocess.CompletedProcess[str]:
self.ran.append(args)
if args == ["auth", "status"]:
return subprocess.CompletedProcess(args, 0 if self.status == SIGNED_IN else 1, self.status, "")
return subprocess.CompletedProcess(args, self.exits.get(args[-1], 0), "", f"no {args[-1]}\nin the marketplace\n")
def unready(self) -> str | None:
return unready(self.home, self.clone, self.claude, lambda *args, cwd=None: self.commit if (args, cwd) == (("rev-parse", "HEAD"), str(self.clone)) else Failure(f"unexpected git {args} in {cwd}"))
def settings(self) -> dict[str, object]:
read: dict[str, object] = json.loads((self.home / "settings.json").read_text(encoding="utf-8"))
return read
def test_a_new_home_links_the_clones_instruction_files(self) -> None:
self.assertIsNone(self.unready())
for name in ("CLAUDE.md", "agents", "rules", "skills"):
self.assertTrue((self.home / name).is_symlink(), name)
self.assertEqual((self.home / name).resolve(), (self.clone / name).resolve())
self.assertEqual((self.home / "CLAUDE.md").read_text(encoding="utf-8"), "# The setup's rules\n")
def test_the_generated_settings_name_the_clone_quoted_for_a_shell_and_leave_the_tracked_file_alone(self) -> None:
self.unready()
self.assertEqual(self.settings()["hooks"], {"PreToolUse": [{"hooks": [{"command": f"'{self.clone}'/bin/rule-hook", "type": "command"}]}]})
self.assertEqual(self.settings()["tui"], "fullscreen")
self.assertEqual(json.loads((self.clone / "settings.json").read_text(encoding="utf-8")), SETTINGS)
def test_it_adds_each_enabled_plugins_marketplace_then_installs_each_enabled_plugin(self) -> None:
self.unready()
self.assertEqual(self.ran, [
["plugin", "marketplace", "add", "anthropics/official"],
["plugin", "marketplace", "add", "someone/other"],
["plugin", "install", "code-review@official"],
["plugin", "install", "lsp@other"],
["auth", "status"],
])
def test_a_home_built_from_the_clones_commit_is_left_as_it_is(self) -> None:
self.unready()
(self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8")
self.ran.clear()
self.assertIsNone(self.unready())
self.assertEqual(self.ran, [["auth", "status"]])
self.assertEqual(self.settings(), {"model": "opus", "tui": "inline"})
def test_a_new_commit_refreshes_the_home_and_keeps_the_model_claude_code_wrote(self) -> None:
self.unready()
(self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8")
(self.clone / "settings.json").write_text(json.dumps({**SETTINGS, "tui": "compact"}), encoding="utf-8")
self.commit = "4d5e6f\n"
self.ran.clear()
self.assertIsNone(self.unready())
self.assertEqual(self.settings()["tui"], "compact")
self.assertEqual(self.settings()["model"], "opus")
self.assertIn(["plugin", "install", "lsp@other"], self.ran)
def test_a_clone_that_moved_refreshes_the_home(self) -> None:
self.unready()
moved = self.temp / "moved"
self.clone.rename(moved)
self.clone = moved
self.assertIsNone(self.unready())
self.assertEqual((self.home / "rules").resolve(), (moved / "rules").resolve())
def test_a_signed_out_home_says_how_to_sign_in(self) -> None:
self.status = SIGNED_OUT
self.assertEqual(self.unready(), f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={self.home} claude` and type /login there, once")
def test_a_status_that_is_no_json_reads_as_signed_out(self) -> None:
self.status = "Not logged in"
self.assertIn("nobody is signed in", self.unready() or "")
def test_a_plugin_that_does_not_install_stops_and_the_next_run_tries_again(self) -> None:
self.exits = {"lsp@other": 1}
self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: claude plugin install lsp@other failed: no lsp@other in the marketplace")
self.exits = {}
self.ran.clear()
self.assertIsNone(self.unready())
self.assertIn(["plugin", "install", "lsp@other"], self.ran)
def test_a_clone_whose_commit_git_cannot_tell_stops(self) -> None:
self.commit = Failure("not a git repository")
self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: not a git repository")
def test_a_file_in_a_links_place_stops(self) -> None:
(self.home / "rules").mkdir(parents=True)
(self.home / "rules" / "mine.md").write_text("", encoding="utf-8")
self.assertIn(f"could not build the loop's Claude home, {self.home}: ", self.unready() or "")
self.assertTrue((self.home / "rules" / "mine.md").exists())
def test_a_claude_that_cannot_start_stops(self) -> None:
def missing(args: list[str]) -> subprocess.CompletedProcess[str]:
raise FileNotFoundError(2, "No such file or directory", "claude")
reason = unready(self.home, self.clone, missing, lambda *args, cwd=None: "1a2b3c\n")
self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: [Errno 2] No such file or directory: 'claude'")
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -66,7 +66,7 @@ from agent_cycle.judge import Brief, judge_archived, judge_once
from chunk_driver.drivers import BUILD_RELEASE
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
from transcript_archive.project_key import checkout_of
from loop_state.paths import CLAUDE_HOME
from loop_state.paths import claude_home
from loop_effects.effects import Effects
from failure import Failure
from judge_replay.offline import final_message, LEARNERS, offline_report, RULES, Sample
@@ -171,7 +171,7 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, env: typing.Mapping[str, st
return verdict_kind(grounds)
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, BUILD_RELEASE, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
premises, records = read_premises(case.root, home, env), read_records(case.root, home, env, home / CLAUDE_HOME)
premises, records = read_premises(case.root, home, env), read_records(case.root, home, env, claude_home(env, home))
if isinstance(premises, Failure):
return verdict_kind(premises)
if isinstance(records, Failure):
+4 -4
View File
@@ -121,10 +121,10 @@ class Main(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
(self.home / ".claude").mkdir()
(self.home / ".local" / "share" / "build-release" / "claude-home").mkdir(parents=True)
(self.home / ".config/build-release").mkdir(parents=True)
(self.home / ".config/build-release" / "models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"}))
(self.home / ".claude" / "CLAUDE.md").write_text("Be kind.\n")
(self.home / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("Be kind.\n")
for key, verdicts in (("proj", (FINISHED, INTERRUPTED)), ("other", (FINISHED,))):
(self.home / "code" / key).mkdir(parents=True)
(self.home / "code" / key / "README.md").write_text("# p\n\n## Goals\n\n1. Ship.\n\n## Audience\n\nMe.\n")
@@ -146,7 +146,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
effects = Effects(claude=claude, claude_home=unused, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
@@ -388,7 +388,7 @@ class JudgeArchivedRuns(unittest.TestCase):
cwds.append(cwd)
return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
effects = Effects(claude=claude, claude_home=unused, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
grounds = grounds_of(prompt, self.ENTRIES)
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, BUILD_RELEASE, effects)), cwds
+2 -1
View File
@@ -176,6 +176,7 @@ import typing
from larv_review.reviewer_header import branch_summaries, reviewer_header
from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
from loop_state.paths import claude_home
from git_cli.git_repo import default_branch, git, top
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
@@ -241,7 +242,7 @@ COMMANDS = {
"agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home(), os.environ))),
"reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header),
"round-title": Command("round-title <pass>", lambda given: len(given) == 1 and given[0] in REVIEWERS, lambda given: with_default_branch(lambda default: printed(round_title(default, given[0], pathlib.Path.home(), os.environ)), stale_ok=True)),
"reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))),
"reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), claude_home(os.environ, pathlib.Path.home())))),
}
SHAPES = " | ".join(command.shape for command in COMMANDS.values())
USAGE = f"usage: larv-review {SHAPES}"
+2 -1
View File
@@ -5,6 +5,7 @@ import pathlib
from git_cli.git_repo import branch_titles, git, top
from review_rules.round_titles import cap, round_counts
from loop_state.paths import claude_home
from failure import Failure
from forge.commands import forge_of, runner
from record_store.stores import goals_store, local_file, store
@@ -123,7 +124,7 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path, e
goals = local_file(goals_store(config), folder / "goals.md")
if isinstance(goals, Failure):
return goals
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language, config.coding_conventions)
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), claude_home(env, home)), config.paths["working-rules"], decisions, config.language, config.coding_conventions)
if rerun and not launch.asked().exists():
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
written = write_inputs(launch, base, home, env, plan_listing(plan_store(config)))
+3 -4
View File
@@ -1337,8 +1337,8 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual(ran.stdout.splitlines()[-1], f"Principles: read {self.checkout}/docs/decisions.md first, up to `# Decisions`, for the project principles and the decision titles.")
def bare(self, agent):
(self.checkout.parent / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
(self.checkout.parent / ".claude" / "agents" / f"{agent}.md").write_text("---\nomitClaudeMd: true\n---\n")
(self.checkout.parent / ".local" / "share" / "build-release" / "claude-home" / "agents").mkdir(parents=True, exist_ok=True)
(self.checkout.parent / ".local" / "share" / "build-release" / "claude-home" / "agents" / f"{agent}.md").write_text("---\nomitClaudeMd: true\n---\n")
def test_reviewer_context_hands_a_reviewer_the_sections_or_what_kept_it_from_them(self):
def hook(agent):
@@ -1348,8 +1348,7 @@ class LarvReviewTool(unittest.TestCase):
missing = hook("prose-reviewer")
self.assertEqual((missing.returncode, missing.stderr), (0, ""))
self.assertIn("failed: could not read", json.loads(missing.stdout)["hookSpecificOutput"]["additionalContext"])
(self.checkout.parent / ".claude").mkdir(exist_ok=True)
(self.checkout.parent / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
(self.checkout.parent / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
ran = hook("prose-reviewer")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("## Prose\n\nShort.\n\n## Vocabulary\n\nWords.", json.loads(ran.stdout)["hookSpecificOutput"]["additionalContext"])
+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))
+22 -5
View File
@@ -10,7 +10,7 @@ RELEASE_ROOT = pathlib.Path(__file__).resolve().parents[2]
# Each folder below is named relative to the person's home folder.
# The Claude home: Claude Code's own folder, with its settings and transcripts. A release is deployed into it, so its CLAUDE.md, rules/ and agents/ are read from it.
# The person's own Claude home. No claude the loop starts runs there, and the setup doesn't read or write it: its name is for prose, and for the rule that keeps an agent out of its `.env`.
CLAUDE_HOME = ".claude"
# The name of the setup's own folder, in the config home and in the state home.
SETUP = "build-release"
@@ -20,6 +20,11 @@ XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
# The state home, which holds the state folder, unless the variable XDG_STATE_HOME names another.
STATE_HOME = ".local/state"
XDG_STATE_HOME = "XDG_STATE_HOME"
# The data home, which holds the data folder, unless the variable XDG_DATA_HOME names another.
DATA_HOME = ".local/share"
XDG_DATA_HOME = "XDG_DATA_HOME"
# The variable that names the home a claude runs in, in place of the person's own.
CLAUDE_CONFIG_DIR = "CLAUDE_CONFIG_DIR"
# Only a claude started through this has the tools on PATH. One a person starts by hand lacks them, as their shell does: the plan keeps short names such as `wait-for` out of a person's shell. README.md → Tools says how to call a tool there.
@@ -44,21 +49,33 @@ def state_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
return xdg_folder(env.get(XDG_STATE_HOME), home / STATE_HOME) / SETUP
def claude_home(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
"""The loop's Claude home, which claude_home.home builds in the data folder: every claude the loop starts keeps its settings, plugins, sign-in and transcripts there."""
# The data folder holds what the tools generate and can generate again, so it needs no backup.
return xdg_folder(env.get(XDG_DATA_HOME), home / DATA_HOME) / SETUP / "claude-home"
def in_claude_home(env: Mapping[str, str], home: pathlib.Path) -> dict[str, str]:
"""env with the loop's Claude home as the home a claude started in it runs in."""
return {**env, CLAUDE_CONFIG_DIR: str(claude_home(env, home))}
# The XDG Base Directory Specification calls a relative path in one of its variables invalid, to be ignored: https://specifications.freedesktop.org/basedir-spec/latest/
def xdg_folder(named: str | None, default: pathlib.Path) -> pathlib.Path:
return pathlib.Path(named) if named and os.path.isabs(named) else default
def without_xdg_folders(env: Mapping[str, str]) -> dict[str, str]:
"""env without the person's own config and state folders, so that both lie under the home folder a caller names."""
return {name: value for name, value in env.items() if name not in (XDG_CONFIG_HOME, XDG_STATE_HOME)}
"""env without the person's own config, state and data folders, so that each lies under the home folder a caller names."""
return {name: value for name, value in env.items() if name not in (XDG_CONFIG_HOME, XDG_STATE_HOME, XDG_DATA_HOME)}
@dataclasses.dataclass(frozen=True)
class Paths:
claude_code_transcripts: pathlib.Path
# The loop's Claude home, whose CLAUDE.md, rules/ and agents/ are links into the release root.
claude_dir: pathlib.Path
# The development clone of this setup, where a change to it is made: claude_dir holds only a release, docs/decisions.md → `deploy:`.
# The development clone of this setup, where a change to it is made.
config_clone: pathlib.Path
config_folder: pathlib.Path
home: pathlib.Path
@@ -68,7 +85,7 @@ class Paths:
def paths_from(home: pathlib.Path, env: Mapping[str, str]) -> Paths:
claude = home / CLAUDE_HOME
claude = claude_home(env, home)
config = config_folder(env, home)
return Paths(
claude_code_transcripts=claude / "projects",
+17 -2
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_state.paths import config_folder, paths_from, RELEASE_ROOT, state_folder, with_release_tools, without_xdg_folders
from loop_state.paths import claude_home, config_folder, in_claude_home, paths_from, RELEASE_ROOT, state_folder, with_release_tools, without_xdg_folders
TOOLS = str(RELEASE_ROOT / "bin")
@@ -45,7 +45,22 @@ class SetupFolders(unittest.TestCase):
self.assertEqual((found.config_folder, found.models_file, found.state_folder), (pathlib.Path("/x/config/build-release"), pathlib.Path("/x/config/build-release/models.json"), pathlib.Path("/x/state/build-release")))
def test_an_environment_without_the_xdg_folders_keeps_every_other_variable(self):
self.assertEqual(without_xdg_folders({"HOME": "/h", "XDG_CONFIG_HOME": "/c", "XDG_STATE_HOME": "/s", "XDG_DATA_HOME": "/d"}), {"HOME": "/h", "XDG_DATA_HOME": "/d"})
self.assertEqual(without_xdg_folders({"HOME": "/h", "XDG_CONFIG_HOME": "/c", "XDG_STATE_HOME": "/s", "XDG_DATA_HOME": "/d", "XDG_CACHE_HOME": "/k"}), {"HOME": "/h", "XDG_CACHE_HOME": "/k"})
class ClaudeHome(unittest.TestCase):
def test_the_loops_claude_home_lies_in_the_setups_folder_of_the_data_home(self):
self.assertEqual(claude_home({}, HOME), HOME / ".local" / "share" / "build-release" / "claude-home")
self.assertEqual(claude_home({"XDG_DATA_HOME": "/x/data"}, HOME), pathlib.Path("/x/data/build-release/claude-home"))
self.assertEqual(claude_home({"XDG_DATA_HOME": "data"}, HOME), HOME / ".local" / "share" / "build-release" / "claude-home")
def test_claude_codes_own_files_are_in_the_loops_claude_home_and_none_in_the_persons(self):
found = paths_from(HOME, {"XDG_DATA_HOME": "/x/data"})
home = pathlib.Path("/x/data/build-release/claude-home")
self.assertEqual((found.claude_dir, found.claude_code_transcripts, found.model_catalog), (home, home / "projects", home / "cache" / "model-catalog"))
def test_a_claude_started_in_the_loops_home_is_told_so_and_keeps_every_other_variable(self):
self.assertEqual(in_claude_home({"PATH": "/bin", "CLAUDE_CONFIG_DIR": "/elsewhere"}, HOME), {"PATH": "/bin", "CLAUDE_CONFIG_DIR": "/home/me/.local/share/build-release/claude-home"})
if __name__ == "__main__":
-20
View File
@@ -1,20 +0,0 @@
import json
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks import ROOT
class Install(unittest.TestCase):
def test_the_readme_adds_each_settings_marketplace_and_installs_every_enabled_plugin(self):
settings = json.loads((ROOT / "settings.json").read_text(encoding="utf-8"))
readme = (ROOT / "README.md").read_text(encoding="utf-8")
for plugin, enabled in settings["enabledPlugins"].items():
if enabled:
self.assertIn(f"claude plugin install {plugin}\n", readme)
# settings.json declares the marketplace, or `claude plugin marketplace add` writes it there.
marketplace = settings["extraKnownMarketplaces"][plugin.split("@")[1]]["source"]["repo"]
self.assertIn(f"claude plugin marketplace add {marketplace}\n", readme)
+31
View File
@@ -0,0 +1,31 @@
import pathlib
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks import ROOT
# Runs a launcher as a Python of the version in argv[2] would, up to its first import of the setup's own code.
AS_VERSION = "import sys; launcher = sys.argv[1]; sys.version_info = tuple(map(int, sys.argv[2].split('.'))); sys.version = sys.argv[2] + ' (main)'; sys.argv = [launcher, '--help']; exec(compile(open(launcher).read(), launcher, 'exec'), {'__file__': launcher, '__name__': '__main__'})"
class LauncherPython(unittest.TestCase):
def ran(self, tool: str, version: str) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, "-c", AS_VERSION, str(ROOT / "bin" / tool), version], capture_output=True, text=True)
def test_a_command_that_starts_claudes_names_the_python_it_needs_where_python3_is_older(self) -> None:
for tool in ("build-epic", "build-release"):
with self.subTest(tool):
ran = self.ran(tool, "3.13.9")
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (1, "", f"{tool} needs Python 3.14 or later as python3 on PATH; it found Python 3.13.9\n"))
def test_it_starts_on_the_python_it_needs(self) -> None:
for tool in ("build-epic", "build-release"):
with self.subTest(tool):
ran = self.ran(tool, "3.14.0")
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
self.assertIn(f"usage: {tool}", ran.stdout)
+2 -1
View File
@@ -11,7 +11,8 @@ RESOLVED_ELSEWHERE = re.compile(
r"""["']\.claude["'/]"""
r"""|["']\.config["'/]"""
r"""|["']\.local["'/]"""
r"""|["']XDG_(CONFIG|STATE)_HOME["']"""
r"""|["']XDG_(CONFIG|DATA|STATE)_HOME["']"""
r"""|["']CLAUDE_CONFIG_DIR["']"""
r"""|__file__\)\.resolve\(\)\.parents\["""
)
+27 -14
View File
@@ -5,22 +5,35 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from settings_filter import cleaned
from git_cli.git_repo import git
from claude_home.home import CLONE
from repo_checks import ROOT
INSTALL = "git config filter.settings.clean bin/settings_filter.py"
class Settings(unittest.TestCase):
def test_the_stored_settings_hold_no_model_and_sorted_keys(self):
# The index, not the working file: the working file holds this machine's model in Claude Code's key order.
stored = git("show", ":settings.json", cwd=str(ROOT))
self.assertIsInstance(stored, str, stored)
fix = f"commit settings.json with the filter on: {INSTALL}"
self.assertNotIn("model", json.loads(stored), fix)
self.assertEqual(stored, cleaned(json.loads(stored)), fix)
def setUp(self) -> None:
self.text = (ROOT / "settings.json").read_text(encoding="utf-8")
self.settings = json.loads(self.text)
def test_the_readme_installs_the_filter_git_attributes_names_for_the_root_settings_only(self):
self.assertEqual("/settings.json filter=settings\n", (ROOT / ".gitattributes").read_text(encoding="utf-8"))
self.assertIn(f"{INSTALL}\n", (ROOT / "README.md").read_text(encoding="utf-8"))
def test_the_tracked_settings_hold_no_model_and_sorted_keys(self) -> None:
# A model belongs to the generated settings.json in the loop's Claude home, where /model writes it.
self.assertNotIn("model", self.settings)
self.assertEqual(self.text, json.dumps(self.settings, indent=2, sort_keys=True) + "\n")
def test_every_hook_runs_a_tool_of_the_clone(self) -> None:
commands = [hook["command"] for groups in self.settings["hooks"].values() for group in groups for hook in group["hooks"]]
self.assertTrue(commands)
for command in commands:
self.assertTrue(command.startswith(f"{CLONE}/bin/"), command)
self.assertTrue((ROOT / "bin" / command.split()[0].removeprefix(f"{CLONE}/bin/")).is_file(), command)
def test_the_persons_theme_and_status_line_are_not_set(self) -> None:
self.assertNotIn("theme", self.settings)
self.assertNotIn("statusLine", self.settings)
def test_every_enabled_plugins_marketplace_names_the_repo_the_home_adds_it_from(self) -> None:
enabled = [plugin for plugin, enabled in self.settings["enabledPlugins"].items() if enabled]
self.assertTrue(enabled)
for plugin in enabled:
self.assertRegex(self.settings["extraKnownMarketplaces"][plugin.split("@")[1]]["source"]["repo"], r"^[\w.-]+/[\w.-]+$", plugin)
+2 -2
View File
@@ -10,6 +10,7 @@ import typing
from review_replay.rounds import authored_by, lost_inputs, reviewed_path, Round
from review_replay.changes import Change
from loop_state.paths import claude_home, STATE_HOME
from claude_code.reply import claude_reply, Limited
from git_cli.git_repo import default_ref
from loop_effects.effects import Effects
@@ -21,7 +22,6 @@ from review_rules.reviewer_context import principles_line, reviewer_context
from text_files.compressed import read_stored, SUFFIX
from review_rules.review_folder import reports_folder, review_folder
from model_routing.ladder import Rung
from loop_state.paths import STATE_HOME
from claude_code.entries import structured_output
# Where, under the home folder, the review folders were until 0.18.0: the prompt of a round archived before then names its review folder there.
@@ -133,7 +133,7 @@ def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, copies: Copies
args += ["--settings", json.dumps({"env": change.env})]
if not change.without_instruction_files:
return args, prompt
context = reviewer_context(home)
context = reviewer_context(claude_home(env, home))
if isinstance(context, Failure):
return context
config = located(checkout, home, env)
+9 -9
View File
@@ -119,8 +119,8 @@ class Sample(unittest.TestCase):
class Launch(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
(self.home / ".claude").mkdir()
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
(self.home / ".local" / "share" / "build-release" / "claude-home").mkdir(parents=True)
(self.home / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
self.clone = self.home / "clone"
self.reports = self.home / "reports"
self.clone.mkdir()
@@ -135,7 +135,7 @@ class Launch(unittest.TestCase):
(self.clone / "AGENTS.md").write_text("")
args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT)
self.assertEqual(args, ["--agent", "prose-reviewer", *REFERENCE.flags(), "--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})])
self.assertEqual(prompt, f"{reviewer_context(self.home)}\n\nReview it.\nPrinciples: read {self.clone}/AGENTS.md first, for the project principles and the decision titles.")
self.assertEqual(prompt, f"{reviewer_context(self.home / ".local" / "share" / "build-release" / "claude-home")}\n\nReview it.\nPrinciples: read {self.clone}/AGENTS.md first, for the project principles and the decision titles.")
def test_names_a_record_outside_the_checkout_where_it_stands(self):
self.config.write_text(self.config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"'))
@@ -159,7 +159,7 @@ class Launch(unittest.TestCase):
self.assertIn("no config names the checkout", replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT).reason)
def test_fails_without_the_sections_to_hand_over(self):
(self.home / ".claude" / "CLAUDE.md").write_text("")
(self.home / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("")
self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT), Failure)
@@ -205,7 +205,7 @@ class Main(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.archive = self.home / ".local/state/build-release" / "transcripts"
(self.home / ".claude").mkdir()
(self.home / ".local" / "share" / "build-release" / "claude-home").mkdir(parents=True)
(self.home / ".config/build-release").mkdir(parents=True)
(self.home / ".config/build-release" / "models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"}))
origin, self.checkout = self.home / "origin.git", self.home / "code" / "proj"
@@ -220,7 +220,7 @@ class Main(unittest.TestCase):
write_config(self.home, self.checkout)
for key in ("proj", "other"):
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
(self.home / ".local" / "share" / "build-release" / "claude-home" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
# The fixture holds one round.
self.limits = {"enough_rounds": 1}
self.reviews = []
@@ -270,7 +270,7 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=system_effects(pathlib.Path.home(), os.environ).git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
effects = Effects(claude=claude, claude_home=unused, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=system_effects(pathlib.Path.home(), os.environ).git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, env, self.home, effects, **self.limits)
@@ -325,7 +325,7 @@ class Main(unittest.TestCase):
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 4)
context = reviewer_context(self.home)
context = reviewer_context(self.home / ".local" / "share" / "build-release" / "claude-home")
self.assertEqual([prompt.startswith(context) for *_, prompt, _ in self.reviews], [False, False, False, True])
self.assertEqual(out, (
f"Replayed 1 stability rounds of claude-opus-5-5 projects, which hold 2 🔴 and 🟡 findings, four times on {REFERENCE}: three {changes.OMIT.unchanged}, one {changes.OMIT.changed}.\n"
@@ -349,7 +349,7 @@ class Main(unittest.TestCase):
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--bash-ceiling"], lambda rung: {"found": next(finds)})
self.assertEqual(code, 0, err)
self.assertEqual(self.review_settings, [None, None, None, {"BASH_MAX_OUTPUT_LENGTH": "6000"}])
context = reviewer_context(self.home)
context = reviewer_context(self.home / ".local" / "share" / "build-release" / "claude-home")
self.assertEqual([prompt.startswith(context) for *_, prompt, _ in self.reviews], [False] * 4)
self.assertEqual(out, (
f"Replayed 1 stability rounds of claude-opus-5-5 projects, which hold 2 🔴 and 🟡 findings, four times on {REFERENCE}: three as archived, one under a Bash ceiling of 6,000 characters.\n"
+9 -10
View File
@@ -3,7 +3,6 @@ import json
import pathlib
import re
from loop_state.paths import CLAUDE_HOME
from failure import Failure
from review_rules.review_passes import REVIEWERS
from text_files.markdown_text import section
@@ -13,9 +12,9 @@ SECTIONS = ("Shared goal", "Prose", "Vocabulary")
# The text calls the file the setup's, the word that file uses for the release's rules, and names no install folder: a release may be installed anywhere.
def reviewer_context(home: pathlib.Path) -> str | Failure:
"""SECTIONS of the CLAUDE.md under home, as a reviewer is told them; a Failure where the file or a section is missing."""
path = home / CLAUDE_HOME / "CLAUDE.md"
def reviewer_context(claude_dir: pathlib.Path) -> str | Failure:
"""SECTIONS of the CLAUDE.md in claude_dir, the loop's Claude home, as a reviewer is told them; a Failure where the file or a section is missing."""
path = claude_dir / "CLAUDE.md"
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
@@ -26,27 +25,27 @@ def reviewer_context(home: pathlib.Path) -> str | Failure:
return "\n\n".join(["You start without the setup's `CLAUDE.md`. These sections of it hold for you:", *("\n".join([f"## {name}", *lines]).strip() for name, lines in found.items() if lines is not None)])
def starts_bare(agent: str, home: pathlib.Path) -> bool:
"""Whether agent is a reviewer whose definition under home starts it without the instruction files."""
def starts_bare(agent: str, claude_dir: pathlib.Path) -> bool:
"""Whether agent is a reviewer whose definition in claude_dir, the loop's Claude home, starts it without the instruction files."""
if agent not in REVIEWERS.values():
return False
try:
text = (home / CLAUDE_HOME / "agents" / f"{agent}.md").read_text(encoding="utf-8")
text = (claude_dir / "agents" / f"{agent}.md").read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return False
frontmatter = text.split("---\n")[1] if text.startswith("---\n") else ""
return "omitClaudeMd: true" in frontmatter.splitlines()
def hook_reply(given: str, home: pathlib.Path) -> str:
def hook_reply(given: str, claude_dir: pathlib.Path) -> str:
"""What the SubagentStart hook prints for its input given: the context for a reviewer that starts without the instruction files, and no text for any other agent."""
try:
read = json.loads(given)
except ValueError:
return ""
if not isinstance(read, dict) or not isinstance(agent := read.get("agent_type"), str) or not starts_bare(agent, home):
if not isinstance(read, dict) or not isinstance(agent := read.get("agent_type"), str) or not starts_bare(agent, claude_dir):
return ""
context = reviewer_context(home)
context = reviewer_context(claude_dir)
if isinstance(context, Failure):
# Claude Code starts the subagent whatever a SubagentStart hook exits with, and shows its stderr to no headless run, so the reviewer's report is where the worker can see the failure.
context = f"You start without the setup's `CLAUDE.md`, and the hook that hands you three of its sections failed: {context.reason}. Open your report by saying so."
+25 -26
View File
@@ -16,26 +16,25 @@ CLAUDE_MD = "# Global\n\n## Working loop\n\nThe worker's.\n\n## Shared goal\n\nC
class ReviewerContext(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
(self.home / ".claude").mkdir()
(self.home / ".claude" / "CLAUDE.md").write_text(CLAUDE_MD)
(self.home / ".claude" / "agents").mkdir()
self.claude_dir = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
(self.claude_dir / "CLAUDE.md").write_text(CLAUDE_MD)
(self.claude_dir / "agents").mkdir()
for agent in REVIEWERS.values():
(self.home / ".claude" / "agents" / f"{agent}.md").write_text(f"---\nname: {agent}\nomitClaudeMd: true\n---\n\nReview.\n")
(self.claude_dir / "agents" / f"{agent}.md").write_text(f"---\nname: {agent}\nomitClaudeMd: true\n---\n\nReview.\n")
def test_holds_the_shared_goal_prose_and_vocabulary_sections_and_none_of_the_workers(self):
self.assertEqual(reviewer_context(self.home), "You start without the setup's `CLAUDE.md`. These sections of it hold for you:\n\n## Shared goal\n\nCode health.\n\n## Prose\n\nWrite short.\n\n## Vocabulary\n\n- **chunk** — a unit.")
self.assertEqual(reviewer_context(self.claude_dir), "You start without the setup's `CLAUDE.md`. These sections of it hold for you:\n\n## Shared goal\n\nCode health.\n\n## Prose\n\nWrite short.\n\n## Vocabulary\n\n- **chunk** — a unit.")
def test_a_heading_inside_a_code_fence_does_not_end_a_section(self):
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose\n\np\n\n## Vocabulary\n\nv\n")
self.assertIn("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose", reviewer_context(self.home))
(self.claude_dir / "CLAUDE.md").write_text("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose\n\np\n\n## Vocabulary\n\nv\n")
self.assertIn("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose", reviewer_context(self.claude_dir))
def test_fails_on_a_missing_section_or_file(self):
(self.home / ".claude" / "CLAUDE.md").write_text("## Prose\n\nWrite short.\n")
self.assertEqual(reviewer_context(self.home), Failure(f"{self.home / '.claude' / 'CLAUDE.md'} holds no section Shared goal, Vocabulary"))
(self.home / ".claude" / "CLAUDE.md").unlink()
path = self.home / ".claude" / "CLAUDE.md"
self.assertIn(f"could not read {path}: ", reviewer_context(self.home).reason)
(self.claude_dir / "CLAUDE.md").write_text("## Prose\n\nWrite short.\n")
self.assertEqual(reviewer_context(self.claude_dir), Failure(f"{self.claude_dir / 'CLAUDE.md'} holds no section Shared goal, Vocabulary"))
(self.claude_dir / "CLAUDE.md").unlink()
path = self.claude_dir / "CLAUDE.md"
self.assertIn(f"could not read {path}: ", reviewer_context(self.claude_dir).reason)
def test_the_repos_claude_md_holds_each_section(self):
headings = [line[3:] for line in (REPO / "CLAUDE.md").read_text().splitlines() if line.startswith("## ")]
@@ -44,29 +43,29 @@ class ReviewerContext(unittest.TestCase):
def test_the_hook_hands_a_reviewer_the_context_and_any_other_agent_nothing(self):
for agent in REVIEWERS.values():
with self.subTest(agent=agent):
reply = hook_reply(json.dumps({"hook_event_name": "SubagentStart", "agent_type": agent}), self.home)
self.assertEqual(json.loads(reply), {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": reviewer_context(self.home)}})
reply = hook_reply(json.dumps({"hook_event_name": "SubagentStart", "agent_type": agent}), self.claude_dir)
self.assertEqual(json.loads(reply), {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": reviewer_context(self.claude_dir)}})
for given in (json.dumps({"agent_type": "Explore"}), json.dumps({}), json.dumps([]), "no json"):
with self.subTest(given=given):
self.assertEqual(hook_reply(given, self.home), "")
self.assertEqual(hook_reply(given, self.claude_dir), "")
def test_the_hook_hands_nothing_to_a_reviewer_whose_definition_keeps_the_instruction_files(self):
given = json.dumps({"agent_type": "prose-reviewer"})
for kept in ("---\nname: prose-reviewer\n---\n\nomitClaudeMd: true\n", "---\nname: prose-reviewer\nomitClaudeMd: false\n---\n", "omitClaudeMd: true\n", b"\xff"):
with self.subTest(kept=kept):
path = self.home / ".claude" / "agents" / "prose-reviewer.md"
path = self.claude_dir / "agents" / "prose-reviewer.md"
path.write_bytes(kept) if isinstance(kept, bytes) else path.write_text(kept)
self.assertEqual(hook_reply(given, self.home), "")
(self.home / ".claude" / "agents" / "prose-reviewer.md").unlink()
self.assertEqual(hook_reply(given, self.home), "")
self.assertTrue(starts_bare("stability-reviewer", self.home))
(self.home / ".claude" / "agents" / "Explore.md").write_text("---\nomitClaudeMd: true\n---\n")
self.assertFalse(starts_bare("Explore", self.home))
self.assertEqual(hook_reply(given, self.claude_dir), "")
(self.claude_dir / "agents" / "prose-reviewer.md").unlink()
self.assertEqual(hook_reply(given, self.claude_dir), "")
self.assertTrue(starts_bare("stability-reviewer", self.claude_dir))
(self.claude_dir / "agents" / "Explore.md").write_text("---\nomitClaudeMd: true\n---\n")
self.assertFalse(starts_bare("Explore", self.claude_dir))
def test_the_hook_tells_a_reviewer_to_report_that_a_section_is_missing(self):
path = self.home / ".claude" / "CLAUDE.md"
path = self.claude_dir / "CLAUDE.md"
path.write_text("## Prose\n\nWrite short.\n")
reply = json.loads(hook_reply(json.dumps({"agent_type": "prose-reviewer"}), self.home))
reply = json.loads(hook_reply(json.dumps({"agent_type": "prose-reviewer"}), self.claude_dir))
self.assertEqual(reply["hookSpecificOutput"]["additionalContext"], f"You start without the setup's `CLAUDE.md`, and the hook that hands you three of its sections failed: {path} holds no section Shared goal, Vocabulary. Open your report by saying so.")
@@ -97,7 +96,7 @@ class Reviewers(unittest.TestCase):
def test_settings_run_the_hook_as_each_subagent_starts(self):
hooks = json.loads((REPO / "settings.json").read_text())["hooks"]["SubagentStart"]
self.assertEqual(hooks, [{"hooks": [{"command": "~/.claude/bin/larv-review reviewer-context", "timeout": 30, "type": "command"}]}])
self.assertEqual(hooks, [{"hooks": [{"command": "{clone}/bin/larv-review reviewer-context", "timeout": 30, "type": "command"}]}])
if __name__ == "__main__":
+1 -1
View File
@@ -101,7 +101,7 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
command = text(call.given, "command")
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home, environ, call.tool == "Monitor") + read_breaches(call, home) + env_file_breaches(call, home, environ)
if call.tool == "Read":
return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home, environ) + transcript_breaches(call, home)
return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home, environ) + transcript_breaches(call, home, environ)
if call.tool == "Grep":
# Only env-file-read checks a Grep, and it takes no override, so no marker or log line concerns the call.
return "", "", env_file_breaches(call, home, environ)
+2 -2
View File
@@ -100,8 +100,8 @@ RULES: dict[RuleName, Rule] = {
),
# A Read carries no text for a marker, so no marker waives it.
"transcript-read": Rule(
"an agent never reads a session transcript under ~/.claude/projects with Read, since the file holds every tool result of its session, and reading it costs far more than the lines the agent needs; the agent prints only those lines with grep or jq; the `tool-results/` files that Claude Code saves a long Bash result to are not transcripts and may be read",
"a Read call whose file is a `.jsonl` file under ~/.claude/projects; a Grep or a Bash command that reads one is not checked",
"an agent never reads a session transcript of a Claude home with Read, since the file holds every tool result of its session, and reading it costs far more than the lines the agent needs; the agent prints only those lines with grep or jq; the `tool-results/` files that Claude Code saves a long Bash result to are not transcripts and may be read",
"a Read call whose file is a `.jsonl` file under `projects` in the loop's Claude home, ~/.local/share/build-release/claude-home unless `XDG_DATA_HOME` holds an absolute path, or under ~/.claude/projects; a Grep or a Bash command that reads one is not checked",
overridable=False,
),
}
+5
View File
@@ -1646,6 +1646,11 @@ class TranscriptRead(unittest.TestCase):
self.assertEqual(self.breached("Read", {"file_path": self.TRANSCRIPT}), ["transcript-read"])
self.assertEqual(self.breached("Read", {"file_path": "/home/h/.claude/projects/-home-h-code-acme/abc-123/subagents/agent-a1.jsonl"}), ["transcript-read"])
def test_a_read_of_a_transcript_in_the_loops_claude_home_is_refused(self):
self.assertEqual(self.breached("Read", {"file_path": "/home/h/.local/share/build-release/claude-home/projects/-home-h-code-acme/abc-123.jsonl"}), ["transcript-read"])
found = breaches_of(Call("Read", {"file_path": "/x/data/build-release/claude-home/projects/-r/abc-123.jsonl"}, "/r"), self.HOME, {"XDG_DATA_HOME": "/x/data"})
self.assertEqual([breach.rule for breach in found[2]], ["transcript-read"])
def test_a_read_spelt_from_home_or_from_the_working_directory_is_refused(self):
self.assertEqual(self.breached("Read", {"file_path": "~/.claude/projects/-home-h-code-acme/abc-123.jsonl"}), ["transcript-read"])
self.assertEqual(self.breached("Read", {"file_path": "abc-123.jsonl"}, "/home/h/.claude/projects/-home-h-code-acme"), ["transcript-read"])
+9 -5
View File
@@ -1,20 +1,24 @@
"""Whether a Read asks for a session transcript under ~/.claude/projects, for the `transcript-read` rule.
"""Whether a Read asks for a session transcript, for the `transcript-read` rule.
A transcript is a `.jsonl` file there, a session's own or a subagent's. It holds every tool result of its session, so reading one costs far more than the lines a task needs. The files Claude Code saves a long Bash result to, under the session's `tool-results/` folder, are `.txt` files and pass: the model is handed their path to read."""
A transcript is a `.jsonl` file under the `projects` folder of a Claude home, the loop's or the person's own, a session's own or a subagent's. It holds every tool result of its session, so reading one costs far more than the lines a task needs. The files Claude Code saves a long Bash result to, under the session's `tool-results/` folder, are `.txt` files and pass: the model is handed their path to read."""
import pathlib
import posixpath
import typing
from rule_hook.rules import Breach
from rule_hook.call import Call, text
from loop_state.paths import CLAUDE_HOME
from loop_state.paths import CLAUDE_HOME, claude_home
from command_lines.shell_command import resolved
READS = "the call reads {}, a session transcript that holds every tool result of its session; print only the lines you need with grep or jq"
def transcript_breaches(call: Call, home: str) -> list[Breach]:
def transcript_breaches(call: Call, home: str, env: typing.Mapping[str, str]) -> list[Breach]:
if call.tool != "Read":
return []
path = resolved(call.cwd, text(call.given, "file_path"), home)
if path.endswith(".jsonl") and path.startswith(posixpath.join(home, CLAUDE_HOME, "projects") + "/"):
# The path is only compared: no file of either home is read.
homes = (posixpath.join(home, CLAUDE_HOME), str(claude_home(env, pathlib.Path(home))))
if path.endswith(".jsonl") and path.startswith(tuple(posixpath.join(each, "projects") + "/" for each in homes)):
return [Breach("transcript-read", READS.format(path), call.cwd)]
return []
+3 -5
View File
@@ -6,13 +6,11 @@ Run it by its path in a clone of a release, as in <clone>/bin/self-update. It fe
tags and checks out the newest v* tag, detached, so the clone holds only what a release holds.
Development happens in another clone, such as ~/code/claude-config. It prints the clone and the version it moved
from and to, then CHANGELOG.md's section for each version since, so you can do what each asks, such
as a new step under Install. Where the move changed settings.json, it asks you to pick the model
again with /model, since git's clean filter keeps the model out of every commit.
as a new step under Install.
It refuses, exit 1, and leaves the clone as it was where a file the clone tracks has an
uncommitted change the newest tag doesn't hold: such as a hook Claude Code wrote into settings.json.
Merge the change through the development clone and cut a release first. A model picked with /model
is no such change. It also refuses where the newest tag doesn't hold the clone's commit, since
uncommitted change the newest tag doesn't hold. Merge the change through the development clone
and cut a release first. It also refuses where the newest tag doesn't hold the clone's commit, since
the move would drop work no release holds. Untracked files, such as Claude Code's sessions and
memory, stay as they are.
"""
+2 -13
View File
@@ -15,9 +15,6 @@ def moved_to_newest(clone: str) -> str | Failure:
return tag
if tag is None:
return Failure(f"{clone}'s origin has no v* tag to move to")
# Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged.
if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=clone), Failure):
return refreshed
listed = git("diff", "--name-only", "-z", "HEAD", cwd=clone)
if isinstance(listed, Failure):
return listed
@@ -34,15 +31,9 @@ def moved_to_newest(clone: str) -> str | Failure:
return f"{clone} is already on {tag}, the newest release."
if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=clone), Failure):
return Failure(f"{tag} doesn't hold {clone}'s commit, so the move would drop work no release holds: cut a release that holds it first")
settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=clone), Failure)
# The tag holds each uncommitted change, so undoing them doesn't lose anything, and lets the move below take the tag's copy.
# A settings.json the clean filter shows unchanged may still differ on disk, by a model pick or Claude Code's key order, which checkout refuses to overwrite; the pick is asked for again below.
tracked = git("ls-files", "-z", "--", "settings.json", cwd=clone)
if isinstance(tracked, Failure):
return tracked
set_aside = sorted({*changed, *names(tracked)} if settings_changed else set(changed))
if set_aside:
restored = git("checkout", "--quiet", "HEAD", "--", *set_aside, cwd=clone)
if changed:
restored = git("checkout", "--quiet", "HEAD", "--", *changed, cwd=clone)
if isinstance(restored, Failure):
return restored
moved = git("checkout", "--quiet", "--detach", tag, cwd=clone)
@@ -50,8 +41,6 @@ def moved_to_newest(clone: str) -> str | Failure:
return moved
changelog = git("show", f"{tag}:CHANGELOG.md", cwd=clone)
lines = [f"Moved {clone} from {old_tag or 'an untagged commit'} to {tag}."]
if settings_changed:
lines.append("settings.json changed: pick the model again with /model.")
if not isinstance(changelog, Failure):
lines += newer_sections(changelog, old_tag)
return "\n\n".join(lines)
+1 -35
View File
@@ -77,9 +77,8 @@ class SelfUpdate(unittest.TestCase):
self.assertIn("## 0.2.0\n\n- Second.", ran.stdout)
self.assertNotIn("First.", ran.stdout)
self.assertNotIn("Later.", ran.stdout)
self.assertNotIn("/model", ran.stdout)
def test_stops_with_gits_error_where_the_index_cannot_be_refreshed(self):
def test_stops_with_gits_error_where_the_index_cannot_be_read(self):
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
(self.target / ".git" / "index").write_bytes(b"DIRC")
ran = self.update()
@@ -132,36 +131,3 @@ class SelfUpdate(unittest.TestCase):
self.assertEqual(ran.returncode, 1)
self.assertIn(f"v0.1.0 doesn't hold {self.target}'s commit", ran.stderr)
self.assertEqual(self.git(self.target, "branch", "--show-current").strip(), "main")
def test_takes_a_model_picked_with_the_clean_filter_set_as_no_change(self):
self.release("0.2.0", "- Second.\n", '{\n "theme": "dark"\n}\n')
self.git(self.target, "fetch", "-q", "--tags", "origin")
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {BIN / 'settings_filter.py'}")
(self.target / "settings.json").write_text('{"model": "claude-opus-5-5", "theme": "dark"}\n')
self.release("0.3.0", "- Third.\n", '{\n "theme": "dark"\n}\n')
ran = self.update()
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.head(), "v0.3.0")
self.assertIn('"model"', (self.target / "settings.json").read_text(), "a release that leaves settings.json as it was keeps the pick")
def test_moves_a_settings_json_that_differs_only_by_a_model_pick_and_key_order_where_the_release_changes_it(self):
self.release("0.2.0", "- Second.\n", '{\n "permissions": {},\n "theme": "dark"\n}\n')
self.git(self.target, "fetch", "-q", "--tags", "origin")
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {BIN / 'settings_filter.py'}")
(self.target / "settings.json").write_text('{\n "theme": "dark",\n "model": "opus",\n "permissions": {}\n}\n')
self.release("0.3.0", "- Third.\n", '{\n "permissions": {},\n "theme": "light"\n}\n')
ran = self.update()
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.head(), "v0.3.0")
self.assertEqual((self.target / "settings.json").read_text(), '{\n "permissions": {},\n "theme": "light"\n}\n')
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
def test_asks_for_the_model_again_where_the_release_changes_settings_json(self):
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
ran = self.update()
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env python3
"""Git's clean filter for settings.json: drop "model" and sort every key.
Claude Code rewrites settings.json, in its own key order, whenever a model is
picked or a plugin installed. Each machine owns its model, so neither the
model nor Claude Code's key order reaches a commit.
"""
import json
import sys
def cleaned(settings: dict[str, object]) -> str:
"""settings.json as git stores it: without "model", every key sorted."""
kept = {key: value for key, value in settings.items() if key != "model"}
return json.dumps(kept, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
def main() -> int:
# On a non-zero exit git warns and stores the file as written.
try:
settings = json.loads(sys.stdin.read())
except ValueError as error:
print(f"settings_filter.py: {error}", file=sys.stderr)
return 1
if not isinstance(settings, dict):
print("settings_filter.py: settings.json holds no JSON object", file=sys.stderr)
return 1
sys.stdout.write(cleaned(settings))
return 0
if __name__ == "__main__":
sys.exit(main())
-82
View File
@@ -1,82 +0,0 @@
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from settings_filter import cleaned
from test_env import isolated_env
from repo_checks import ROOT
FILTER = pathlib.Path(__file__).resolve().parent / "settings_filter.py"
PICKED = json.dumps({"theme": "dark", "model": "opus[1m]", "env": {}}, indent=2)
class Clean(unittest.TestCase):
def test_drops_the_model_and_sorts_every_key(self):
written = {"theme": "dark", "model": "opus[1m]", "env": {"B": "1", "A": "2"}}
self.assertEqual(cleaned(written), '{\n "env": {\n "A": "2",\n "B": "1"\n },\n "theme": "dark"\n}\n')
def test_keeps_text_outside_ascii(self):
self.assertEqual(cleaned({"name": "Lilleman på Larv"}), '{\n "name": "Lilleman på Larv"\n}\n')
def test_a_file_that_holds_no_json_object_exits_1_naming_the_tool(self):
for written in ("{", "[]"):
with self.subTest(written=written):
ran = subprocess.run([sys.executable, FILTER], input=written, capture_output=True, text=True)
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("settings_filter.py: ", ran.stderr)
class Checkout(unittest.TestCase):
"""A repo as README → Install leaves it, checked out at tag v1; tag v2 doesn't change settings.json."""
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.repo = pathlib.Path(temp.name)
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
self.git("init", "-q")
(self.repo / "bin").mkdir()
(self.repo / "bin" / "settings_filter.py").symlink_to(FILTER)
(self.repo / ".gitattributes").write_text((ROOT / ".gitattributes").read_text())
self.git("config", "filter.settings.clean", "bin/settings_filter.py")
self.settings = self.repo / "settings.json"
self.settings.write_text(cleaned({"env": {}, "theme": "dark"}))
(self.repo / ".claude").mkdir()
(self.repo / ".claude" / "settings.json").write_text('{\n "model": "claude-opus-5-5"\n}\n')
self.git("add", ".")
self.git("commit", "-qm", "settings")
self.git("tag", "v1")
(self.repo / "other").write_text("")
self.git("add", "other")
self.git("commit", "-qm", "a tag that leaves settings.json alone")
self.git("tag", "v2")
self.git("checkout", "-q", "v1")
def git(self, *args):
return subprocess.run(["git", "-C", self.repo, "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, env=self.env, text=True).stdout
def test_a_model_pick_in_claude_codes_key_order_leaves_nothing_to_commit(self):
self.settings.write_text(PICKED)
self.assertEqual(self.git("diff"), "")
# git status lists a file whose size changed until it is staged; staging adds no change.
self.git("add", "settings.json")
self.assertEqual(self.git("status", "--porcelain"), "")
def test_a_staged_pick_outlasts_an_update_to_a_tag_that_leaves_settings_json_alone(self):
self.settings.write_text(PICKED)
self.git("add", "settings.json")
self.git("checkout", "-q", "-f", "v2")
self.assertEqual(self.settings.read_text(), PICKED)
def test_the_repos_own_harness_settings_keep_their_model(self):
self.assertEqual(self.git("show", ":.claude/settings.json"), '{\n "model": "claude-opus-5-5"\n}\n')
if __name__ == "__main__":
unittest.main()