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
-1
View File
@@ -1 +0,0 @@
/settings.json filter=settings
+2 -1
View File
@@ -61,6 +61,8 @@
!bin/chunk_preflight/*.py
!bin/claude_code/
!bin/claude_code/*.py
!bin/claude_home/
!bin/claude_home/*.py
!bin/command-patterns
!bin/command_lines/
!bin/command_lines/*.py
@@ -152,7 +154,6 @@
!bin/self-update
!bin/self_update/
!bin/self_update/*.py
!bin/settings_filter.py
!bin/setup.cfg
!bin/statusline.py
!bin/subagent-rung
+29 -42
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to, which a project's config names as `principles` and `standards`; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`, with the routing ladder they ship, `bin/model_routing/routing-ladder.json`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of build-release's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
My setup for Claude Code, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to, which a project's config names as `principles` and `standards`; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`, with the routing ladder they ship, `bin/model_routing/routing-ladder.json`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of build-release's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
## Goals
@@ -49,58 +49,45 @@ Me, and anyone who installs a release and runs it, on their own machines or on t
Take this checkout only onto a machine that is a sandbox with no direct access to a production environment, such as a dedicated VM: `settings.json` runs Claude Code with permissions bypassed and the dangerous-mode prompt skipped.
This release still installs into `~/.claude`, which goals 2 and 3 work to end.
Each machine holds two checkouts. `~/.claude` is the one Claude Code reads, and it holds only a release: its own `bin/self-update` moves it from tag to tag. Develop in a clone under `~/code`, where build-release runs this repo's chunks like any project's.
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place, then clone it for development:
Each machine holds two clones. `~/build-release` holds only a release, and its tools are the ones you run: its own `bin/self-update` moves it from tag to tag. Clone it anywhere but `~/.claude`; this README writes `~/build-release`. Develop in a clone under `~/code`, where build-release runs this repo's chunks like any project's.
```sh
mkdir -p ~/.claude && cd ~/.claude
git init
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
git fetch --tags origin
git checkout -f "$(git tag -l 'v*' --sort=-v:refname | head -n 1)"
git clone ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git ~/build-release
git -C ~/build-release checkout --detach "$(git -C ~/build-release tag -l 'v*' --sort=-v:refname | head -n 1)"
git clone ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git ~/code/claude-config
```
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and tmux 3.2 or later: build-release runs each chunk in its own window of a tmux session per project. build-release and build-epic stop and say so where either is older. For Rust projects, have `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs.
```sh
claude plugin marketplace add anthropics/claude-plugins-official
claude plugin install claude-security@claude-plugins-official
claude plugin install code-review@claude-plugins-official
claude plugin install rust-analyzer-lsp@claude-plugins-official
```
Run `build-release` by its path, `~/build-release/bin/build-release`: no step installs it. Every claude it starts, the interactive ones included, skips every permission prompt.
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit. Run this in each checkout, `~/.claude` and `~/code/claude-config`:
build-release and build-epic run every claude in the loop's Claude home, `~/.local/share/build-release/claude-home`, which they build when they start. The setup doesn't read or write your own `~/.claude`, and nothing in it loads in the loop's home. The loop's home holds:
```sh
git config filter.settings.clean bin/settings_filter.py
```
- links to the clone's `CLAUDE.md`, `rules/`, `agents/` and `skills/`;
- a `settings.json` generated from the clone's, whose hooks run the clone's tools;
- every plugin the clone's `settings.json` enables, which the command installs;
- what Claude Code keeps in its home: your sign-in there, the sessions and the memory files.
Then pick a model with `/model`.
Sign in to the loop's home once. Until you have, a command stops and prints the line to run, `CLAUDE_CONFIG_DIR=~/.local/share/build-release/claude-home claude`: type `/login` in the claude it opens. A model you pick there with `/model` stays in the generated `settings.json`. Your theme and status line are your own `~/.claude`'s. A command builds the home again once the clone holds another commit, as after `self-update`, and keeps the sign-in, the model and the sessions.
Run `build-release` by its path, `~/.claude/bin/build-release`: no step installs it. Every claude it starts, the interactive ones included, skips every permission prompt. build-release runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later.
The setup keeps each project's config, and what you choose for a project, in the config folder, `~/.config/build-release/`. Its tools keep their own state, such as transcripts, review reports and locks, in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` holds an absolute path, the config folder is `build-release/` under that path instead, and likewise the state folder under `XDG_STATE_HOME`; this README spells the defaults. Set such a variable in the environment Claude Code starts in, since rule-hook reads it there. `settings.json` names only the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`: where `XDG_STATE_HOME` moves that folder, add it there yourself, or an interactive session asks before a reviewer writes its report. Back up these four folders:
The setup keeps each project's config, and what you choose for a project, in the config folder, `~/.config/build-release/`. Its tools keep their own state, such as transcripts, review reports and locks, in the state folder, `~/.local/state/build-release/`. The loop's Claude home is in the data folder, `~/.local/share/build-release/`, which holds only what a command builds again or Claude Code writes. Where `XDG_CONFIG_HOME` holds an absolute path, the config folder is `build-release/` under that path instead, and likewise the state folder under `XDG_STATE_HOME` and the data folder under `XDG_DATA_HOME`; this README spells the defaults. Set such a variable in the environment Claude Code starts in, since rule-hook reads it there. `settings.json` names only the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`: where `XDG_STATE_HOME` moves that folder, add it to the loop's home's `settings.json` yourself, and again each time a command builds the home, or an interactive session asks before a reviewer writes its report. Back up these four folders:
- `~/.config/build-release/`: each project's config, a client project's plan and records, and `models.json`, the model of each project, which build-release and build-epic write. A project's `env-file`, if you keep it here as below, puts credentials in the backup, so keep the backup private.
- `~/.local/state/build-release/transcripts`: every transcript build-release keeps. Where you set `BUILD_RELEASE_TRANSCRIPTS`, back up the folder it names instead.
- `~/.local/state/build-release/build-epic-transcripts`: the transcripts of build-epic's chunks.
- `~/.local/state/build-release/larv-review`: each chunk's review reports.
Leave out Claude Code's memory files in `~/.claude/projects/<folder>/memory/`: Claude Code writes them, so they aren't part of this setup.
Leave out the data folder. A command builds the loop's Claude home again, and Claude Code writes the memory files in its `projects/<folder>/memory/`, so they aren't part of this setup.
To keep build-release's transcripts and the reports small, add a crontab line that gzips each transcript and review file 30 days after it last changed, and logs each run with its date:
```sh
17 4 * * * mkdir -p $HOME/.local/state/build-release && { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/build-release/compress-archives.log 2>&1
17 4 * * * mkdir -p $HOME/.local/state/build-release && { date; $HOME/build-release/bin/compress-archives; } >> $HOME/.local/state/build-release/compress-archives.log 2>&1
```
Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `BUILD_RELEASE_TRANSCRIPTS` or `XDG_STATE_HOME`, set `PATH` or that variable in the crontab too. With `XDG_STATE_HOME`, write its folder in place of `$HOME/.local/state` in the line as well.
To get build-release's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.config/build-release/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.config/build-release/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
To get build-release's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.config/build-release/<key>.env`, in the keys `~/build-release/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.config/build-release/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
### Set up a project
@@ -118,8 +105,8 @@ comprehension-history = "checkout:docs/comprehension-history.md"
reading-cost = "checkout:docs/reading-cost.md"
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "checkout:README.md"
principles = "~/.claude/principles"
standards = "~/.claude/skills/larv-review/standards"
principles = "~/build-release/principles"
standards = "~/build-release/skills/larv-review/standards"
```
`principles` and `standards` name the folders the reviewers hold the project to: the technical principles and the review standards. Both ship with this setup, at the paths above. A folder of your own replaces the shipped one. A standards folder must hold `quality.md`, `prose.md`, `comments.md` and `readme.md`, since the reviewers and the rules name those files.
@@ -170,7 +157,7 @@ mkdir -p ~/.config/build-release/acme && cd ~/.config/build-release/acme
git init
$EDITOR config.toml
git add config.toml && git commit -m "Add the config"
cd ~/code/acme-billing && ~/.claude/bin/project-config
cd ~/code/acme-billing && ~/build-release/bin/project-config
```
The last line prints each setting's path once the config is complete.
@@ -197,17 +184,17 @@ A project runs on the routing ladder this setup ships, `bin/model_routing/routin
## Update
Move `~/.claude` to the newest release:
Move `~/build-release` to the newest release:
```sh
~/.claude/bin/self-update
~/build-release/bin/self-update
```
It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `self-update` moves the clone it ships in, whatever the directory it is run from, and names that clone in each line that says what it did or why it refused. So run `~/.claude`'s copy, never the development clone's. `self-update --help` says what else it checks.
It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `self-update` moves the clone it ships in, whatever the directory it is run from, and names that clone in each line that says what it did or why it refused. So run `~/build-release`'s copy, never the development clone's. The next build-release or build-epic builds the loop's Claude home again from the new release. `self-update --help` says what else it checks.
It refuses while a file `~/.claude` tracks has an uncommitted change, such as a hook Claude Code wrote into `settings.json`; a model picked with `/model` is no such change. Read the change first, as in `git -C ~/.claude diff HEAD -- settings.json`. When it holds a credential, such as a token in `env` or `mcpServers`, move that out of the file: a token in `env` to the shell profile, a server in `mcpServers` to `~/.claude.json` with `claude mcp add --scope user`. Then carry the change into `~/code/claude-config` on a branch of its own, merge it through a PR, and cut a release.
It refuses while a file the clone tracks has an uncommitted change. Claude Code writes into the loop's home, never into the clone, so such a change is one you made. Carry it into `~/code/claude-config` on a branch of its own, merge it through a PR, and cut a release.
A release up to 0.17.0 holds no `self-update`. Move such a clone once with its own copy of the tool that release holds, `~/.claude/bin/deploy-release`, run without an argument.
A release up to 0.17.0 was a checkout in `~/.claude`, and `self-update` doesn't move one out of there. Clone the newest release as Install says, and sign in to the loop's home. In each project's config, write the new clone in place of `~/.claude` in `principles` and `standards`, and likewise in the crontab line. Nothing of the setup reads `~/.claude` after that, so the checkout there is yours to keep or remove.
## Release
@@ -229,7 +216,7 @@ It applies only those commits on the newest tag, tests them with `ci.sh`, tags a
## Tools
build-release, build-epic and `task-bench gather` put the release's tools first on the `PATH` of every claude they start, so this README and the rules name each tool bare, as in `metric-bench`. Install puts no tool on your shell's `PATH`: there, and in a claude you start from it yourself, call each by its path, `~/.claude/bin/<tool>`, from the project's checkout. Run `cut-release` from the development clone instead, as Release says. The tools under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
build-release, build-epic and `task-bench gather` put the release's tools first on the `PATH` of every claude they start, so this README and the rules name each tool bare, as in `metric-bench`. Install puts no tool on your shell's `PATH`: there, and in a claude you start from it yourself, call each by its path, `~/build-release/bin/<tool>`, from the project's checkout. Run `cut-release` from the development clone instead, as Release says. The tools under `~/build-release` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
- `build-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as build-release. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, build-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. It plans no issue your team filed a sub-task under: those sub-tasks run instead, each under a label of its own, and your team closes the issue. Then, where two or more issues may start, it scores each of them that holds no scores, and moves the issues that build-epic itself filed into order of score on the board. An open issue runs once a label names its repo or marks it as Claude's, in order of score, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. `build-epic <EPIC-KEY> --dry-run` prints what `build-epic <EPIC-KEY>` would write to Jira and which chunks it would start, and does neither; run it before the first real run on a team's epic. `--help` lists what it prints and leaves out. build-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `build-epic --help` states the flags and the contract.
- `build-epic-e2e` runs `build-epic` against a sandbox epic on a real Jira site, as Test says.
@@ -255,8 +242,7 @@ build-release, build-epic and `task-bench gather` put the release's tools first
- `run-tests [<pytest args>...]` runs this repo's test suite, as Test says.
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
- `self-update` moves the clone it ships in, a clone of a release, to the newest release, as Update says.
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `statusline.py` renders a status line for Claude Code. The loop's home sets none: to use it in your own sessions, name it as `statusLine` in your own `~/.claude/settings.json`.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, PHP, Python, Rust, TypeScript and JavaScript files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
@@ -287,8 +273,9 @@ build-release, build-epic and `task-bench gather` put the release's tools first
- `e2e/` holds `build-epic-e2e`.
- `build_release` runs `chunk-preflight` as a process of its own.
- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `build_epic` and `build_release` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included.
- `claude_home/` builds the loop's Claude home, as Install describes it, and says what keeps a claude from running there: a home it could not build, or nobody signed in. `loop_effects` runs it as the `claude_home` effect, which build-release and build-epic check before they start a chunk.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. build-release, build-epic, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds `paths.py`, the one module under `bin/` that resolves the setup's folders: the release root, which is the folder the running code ships in, the Claude home, the config folder and the state folder. `repo_checks` fails another module under `bin/`, tests aside, that names one as a quoted path part, such as `".claude"`, or finds the release root from `__file__`.
- `loop_state/` holds `paths.py`, the one module under `bin/` that resolves the setup's folders: the release root, which is the folder the running code ships in, the loop's Claude home, the config folder, the state folder and the data folder. `repo_checks` fails another module under `bin/`, tests aside, that names one as a quoted path part, such as `".claude"`, or finds the release root from `__file__`.
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for build-release, `build_epic`, `rule_hook`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for build-release through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `transcript_archive/` stores build-release's transcripts. Its `project_key.py` names each project's archive folder, build-release session and models-file entry.
@@ -326,7 +313,7 @@ build-release, build-epic and `task-bench gather` put the release's tools first
#### Tests and tools of one file
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them.
- `repo_checks/` tests the repo itself.
- `test_env.py` serves the tests.
+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()
+5 -4
View File
@@ -4,7 +4,7 @@ Each project principle states one rule that the decisions below apply; their ent
1. **Cut cost only where a measurement of archived chunks shows quality holds.** Chunk bundling, the round cap, which fixes rerun a pass, a reviewer of its own for each pass, the review a branch changing only Markdown no agent follows gets, the passes kept for the release review, review opt-outs, the security pass, compaction and the routing ladder all apply it.
2. **A measurement files or ranks work, and never blocks a merge.** The comprehension floor and check, and a reading-cost rise, apply it. A merge waits on a scoring run the plan calls for only until the run is recorded, whatever it scores.
3. **Each file has one writer.** `~/.config/build-release/models.json` is written only by `save_model`, which the entry points, build-release and build-epic, both call. `~/.claude.json` is Claude Code's, and `~/.claude` moves only through its own `self-update`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo.
3. **Each file has one writer.** `~/.config/build-release/models.json` is written only by `save_model`, which the entry points, build-release and build-epic, both call. The clone of a release moves only through its own `self-update`, and nothing else writes it. The loop's Claude home is `bin/claude_home`'s to build and Claude Code's to keep. The exception is that home's `settings.json`, which both write: a build replaces it with the clone's, and keeps only the `model` Claude Code wrote there.
4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it.
5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `cut-release`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere.
6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude build-release starts bypasses permissions inside its sandbox, each claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions bypass permissions with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried.
@@ -132,7 +132,8 @@ The cap is 5, `bin/plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: b
2026-11-20, lilleman's standalone-install plan. Serves goal 3, which keeps the setup out of the human's `~/.claude`, and goal 5: a home of its own keeps the loop's transcripts and token apart from the human's. The plan therefore runs every claude the loop starts in a home of its own, and doesn't load the setup with `--plugin-dir`, `--settings` and `--append-system-prompt-file` over the human's home. The probes ran on Claude Code 2.1.330, on throwaway homes, never the human's. A mock Messages API at `ANTHROPIC_BASE_URL` recorded each request and answered the first with a tool call that reads a file, so the system prompt and the tool results show what loaded, with no real token. Valid for Claude Code 2.1.330; repeat the probes when its version changes.
- **Loads from `$CLAUDE_CONFIG_DIR`:** `CLAUDE.md` (in the system prompt), `rules/*.md` (one with `paths:` entered the context after the model read a matching file, not before), `agents/`, `skills/`, the hooks of `settings.json` (a `SessionStart` hook ran) and plugins. `claude plugin marketplace add` and `claude plugin install` write to `<home>/plugins`, and the installed plugin's skill is listed. `.claude.json` lands in the home too, so the human's `~/.claude.json` stays theirs.
- **The loop's home signs in by `/login`.** 2026-12-03, lilleman, planning 0.18.0: the human signs in once inside the loop's home (item 483). Not tested: where that home keeps the sign-in. The token below stays the way a container signs in, as task-bench does.
- **The loop's home signs in by `/login`.** 2026-12-03, lilleman, planning 0.18.0: the human signs in once, in a claude started with `CLAUDE_CONFIG_DIR` naming the loop's home, over a long-lived token file they would have to make and keep. `bin/claude_home` asks `claude auth status` before a command starts a chunk. Probed on Claude Code 2.1.336 in a throwaway home: signed out, it prints JSON with `loggedIn: false` and exits 1. Not tested: where the home keeps the sign-in. The token below stays the way a container signs in, as task-bench does.
- **The loop's home is generated, outside the clone.** `bin/claude_home` builds it in the data folder, `~/.local/share/build-release/claude-home`, so the clone stays a clean checkout and Claude Code's writes never reach a commit. It links `CLAUDE.md`, `rules/`, `agents/` and `skills/` to the clone's, and writes `settings.json` from the clone's with the clone's path in place of `{clone}`, since a hook's command can't name a clone that lies anywhere. It builds the home again when the clone's commit or path changes, which covers a release's tag and a development clone alike. Probed on 2.1.336: `claude plugin install` finds a plugin only after `claude plugin marketplace add` of its marketplace; each exits 0 where its work is already done; and an install rewrites the home's `settings.json` in Claude Code's key order. Not tested: that a session loads the four through links, which needs a model request.
- **Signs in by `CLAUDE_CODE_OAUTH_TOKEN`:** the request carried `Authorization: Bearer <token>` with the `oauth-2025-04-20` beta, and `claude auth status` said `loggedIn: true, authMethod: oauth_token`. The home didn't hold a credentials file. Without the variable the home is `loggedIn: false`. Not tested: that Anthropic accepts a real token, since `claude setup-token` needs the human's browser sign-in. The authentication docs say the token lasts one year and can only make model requests; neither is tested, and the first real run shows whether it signs in.
- **`--bare` can't use that token.** With `CLAUDE_CODE_OAUTH_TOKEN`, it says `Not logged in · Please run /login` and doesn't send a request. With `ANTHROPIC_API_KEY` it signs in, but doesn't load anything from the home (`CLAUDE.md`, rules, agents or skills) and offers only Bash, Edit and Read. So a container that signs in by a long-lived token runs without `--bare`; its fresh home is empty, so nothing of the human's loads there either. The project's `CLAUDE.md` loads from the working folder, and its `AGENTS.md` only where the project has no `CLAUDE.md`.
- **Transcripts** land in `<home>/projects/<working folder's path, with each / as ->/<session id>.jsonl`. `--no-session-persistence` doesn't write one, only an empty `memory` folder, so a bench that uses it reads the run from `--output-format stream-json`.
@@ -838,9 +839,9 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc
2026-12-03, lilleman. Interactive sessions now start in `bypassPermissions` instead of auto mode: auto mode still asked for permission too often for a sandbox, where the sandbox, not the prompt, grants access. Valid while every machine taking this checkout is such a sandbox.
## settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
## settings.json: the tracked file sets what every machine shares, and a machine's model lives only in the copy generated in the loop's Claude home
2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and build-release picks each project's model in `~/.config/build-release/models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`.
2026-12-04, replacing the clean filter of 2026-10-21. Serves goal 2. Claude Code rewrites `"model"` in its home's `settings.json` on every `/model` and plugin install. While that home was the clone, a clean filter, `bin/settings_filter.py`, kept the model and Claude Code's key order out of every commit, and each machine ran one `git config` step to set it. The loop's home is now generated outside the clone, so Claude Code never writes the tracked file, and the filter and its step are gone. A build of the home keeps the `model` its `settings.json` holds and takes every other key from the clone. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on; build-release picks each project's model in `~/.config/build-release/models.json` anyway. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. The tracked file holds no theme or status line: those are the person's, in their own `~/.claude`. `bin/repo_checks/test_settings.py` holds the tracked file to no model and sorted keys. Valid while Claude Code writes the model it picks into its home's `settings.json`.
## task-bench: a bench takes 5 bugs and 5 runs per side, after a 2 × 2 pilot on a new setup, and at no affordable count does a chunk-sized change rise above the noise
+17
View File
@@ -4061,3 +4061,20 @@ Read most (opens and searches):
- `bin/loop_state/paths.py` 1
- `bin/repo_checks/test_gitignore.py` 1
- `bin/repo_checks/test_import_order.py` 1
## Reading cost, chunk f8e8bc3c9a97, finished 2026-12-03T23:35:33Z
197317 new input tokens before the first commit.
Read most (opens and searches):
- `bin/cut_release/test_cut_release.py` 13
- `README.md` 8
- `bin/self_update/test_self_update.py` 7
- `docs/decisions.md` 7
- `bin/cut_release/cut.py` 5
- `todo.md` 5
- `.gitignore` 3
- `bin/cut_release/patch.py` 3
- `CLAUDE.md` 2
- `bin/cut_release/trace.py` 2
+2 -8
View File
@@ -27,7 +27,7 @@
{
"hooks": [
{
"command": "~/.claude/bin/rule-hook",
"command": "{clone}/bin/rule-hook",
"timeout": 30,
"type": "command"
}
@@ -39,7 +39,7 @@
{
"hooks": [
{
"command": "~/.claude/bin/larv-review reviewer-context",
"command": "{clone}/bin/larv-review reviewer-context",
"timeout": 30,
"type": "command"
}
@@ -63,11 +63,5 @@
},
"skipDangerousModePermissionPrompt": true,
"skipWorkflowUsageWarning": true,
"statusLine": {
"command": "~/.claude/bin/statusline.py",
"refreshInterval": 30,
"type": "command"
},
"theme": "dark",
"tui": "fullscreen"
}
+53 -2
View File
@@ -6,17 +6,19 @@
`Bar = 0.1`
`Next ID = 581`
`Next ID = 583`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 581 | 0.18.0 | | | **Name each file of the setup, in everything a model or a person reads, by a path that holds wherever the clone lies, never by `~/.claude`.** | 3 | 2 | 3 | 6 | 6 | 2 by 8 | 0.8 |
| 483 | 0.18.0 | | owner | **Run every claude the loop starts in a Claude home that the commands generate under `~/.local/share/build-release/` and refresh when the clone's tag changes, with the enabled plugins installed there and the person signed in by `/login` in that home.** | 4 | 2 | 3 | 7 | 7 | 2 by 8 | 0.5 |
| 486 | 0.18.0 | 483 | owner | **Open an interactive claude with the setup loaded through one wrapper command, which sets the generated home and `PATH` and passes every argument on to claude.** | 2 | 1 | 1 | 2 | 3 | 2 by 2 | 0.5 |
| 577 | 0.18.0 | 483, 486 | owner | **Test in the gate that a container holding only a stock Claude Code runs a chunk from a clone, against a mock Messages API, and that the run leaves the container's own `~/.claude` as it was.** | 3 | 1 | 2 | 4 | 6 | 3 by 9, 2 by 5 | 5.2 |
| 577 | 0.18.0 | 483, 486, 581 | owner | **Test in the gate that a container holding only a stock Claude Code runs a chunk from a clone, against a mock Messages API, and that the run leaves the container's own `~/.claude` as it was.** | 3 | 1 | 2 | 4 | 6 | 3 by 9, 2 by 5 | 5.2 |
| 576 | 0.18.0 | | owner | **Name the project `dev-factory` in the README, the prose and the tools, and say in the changelog that the repo moved.** | 2 | 2 | 2 | 4 | 4 | 2 by 1, 6 by 1 | 0.4 |
| 578 | 0.18.0 | 576, 577 | owner | **Ship one chunk of this repo, to a merged pull request, from a clone of `main` that runs in the generated home, beside the untouched `~/.claude`.** | 1 | 2 | 1 | 2 | 1 | 2 by 4 | 1.2 |
| 582 | 0.18.0 | | | **Write the review folder under the state folder into the generated `settings.json`'s `additionalDirectories`, so a moved `XDG_STATE_HOME` needs no hand edit.** | 1 | 1 | 2 | 2 | 1 | 2 by 2 | 0.6 |
| 580 | 0.19.0 | | | **Call no scoring run for a release already cut whose last item the chunk moved to a later release.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 1.5 by 3 | 1.6 |
| 487 | 0.20.0 | 483 | owner | **Run larv-review's passes from a program that picks them from the diff and the item, counts rounds against the cap and decides each rerun, with each reviewer returning its findings as JSON against a schema.** | 4 | 2 | 3 | 7 | 8 | 1.1 by 5, 1.4 by 5 | 0.4 |
| 498 | 0.20.0 | 487 | owner | **Drive each chunk as a state machine in `build-release`, from preflight through implementing, review, the pull request and the merge to finishing its items, with the worker as one model step that ends in a result that code checks.** | 4 | 2 | 3 | 7 | 8 | 1.1 by 4, 1.4 by 4 | 0.3 |
@@ -103,6 +105,44 @@
## Details
### 581. Name each file of the setup, in everything a model or a person reads, by a path that holds wherever the clone lies, never by `~/.claude`.
Found while shipping the loop's generated Claude home. The loop's claudes now run in `~/.local/share/build-release/claude-home`, and the clone lies anywhere but `~/.claude`. What they read still sends them to the person's own home: `CLAUDE.md`, the files under `rules/`, `agents/`, `skills/` and `principles/` name `~/.claude/rules/…`, `~/.claude/skills/…`, `~/.claude/agents/` and `~/.claude/bin/<tool>`, about 14 files. So a worker in a clone elsewhere is told to read files that don't exist, and one whose `~/.claude` still holds an old checkout reads a stale release, which breaks goal 3. The same holds for:
- the config that `project-config --help` shows and `project_config/doubles.py` writes, whose `standards` is `~/.claude/skills/larv-review/standards`;
- the label `chunk_driver/project/records.py`'s `named` gives each rule the judge reads, `~/.claude/<file>`, and the judge's prompt and build-release's help, which name `~/.claude/CLAUDE.md` and `~/.claude/rules/`;
- each tool's help that names `~/.claude/bin/<tool>`;
- `task-bench gather`, whose claude runs in the person's own home: start it with `loop_effects`' `claude_environment`, after the `claude_home` effect says the home is ready.
Choose one spelling for a file of the setup that holds wherever the clone lies, and bench it as "Bench a syntax" asks. Two candidates: the loop's home, which then also links `bin/` and `principles/`; or the clone, which build-release's prompt names. `~/.claude` stays only where it means the person's own home, as in goal 3 and rule-hook's `.env` rule. README.md already writes the clone as `~/build-release`.
Touches:
- `CLAUDE.md`
- `rules/todo-items.md`
- `rules/decisions.md`
- `rules/goals-and-audience.md`
- `skills/larv-review/SKILL.md`
- `skills/larv-review/review-findings.md`
- `skills/larv-review/standards/prose.md`
- `skills/comprehension-panel/SKILL.md`
- `principles/technical-principles.md`
- `agents/override-reviewer.md`
- `agents/principles-auditor.md`
- `agents/product-owner-reviewer.md`
- `agents/prose-reviewer.md`
- `agents/stability-reviewer.md`
- `agents/systems-architect.md`
- `bin/project_config/main.py`: `(module)` (small)
- `bin/project_config/doubles.py`
- `bin/chunk_driver/project/records.py`: `named`
- `bin/agent_cycle/judge.py`
- `bin/build_release/loop/usage.py`
- `bin/task_bench/figures/gather.py`
- `bin/claude_home/home.py`: `LINKED` (small)
Which other tools' help names `~/.claude/bin/` is not predictable, so the list leaves those files out.
### 483. Run every claude the loop starts in a Claude home that the commands generate under `~/.local/share/build-release/` and refresh when the clone's tag changes, with the enabled plugins installed there and the person signed in by `/login` in that home.
Part of the standalone-install plan lilleman approved on 2026-11-20, as reshaped on 2026-12-03 when 0.18.0 was planned. The home sits outside the clone, so the clone stays a clean checkout. It holds links to the clone's `CLAUDE.md`, `rules/`, `agents/` and `skills/`, and a generated `settings.json` whose hooks point into the clone. Nothing of the person's own `~/.claude` loads there, and the setup never reads or writes it, which goal 3 holds. Any command builds or refreshes the home, installs the plugins `settings.json` enables, and then stops with one message naming what only the person can do: sign in, or install Python or tmux. lilleman chose `/login` inside the home over a long-lived token file. The person's theme, status line and `/model` stay in their own `~/.claude`. Claude Code then rewrites `model` in the generated `settings.json`, never in the tracked one, so remove `bin/settings_filter.py`, its `.gitattributes` line and Install's filter step if nothing else needs them. Revise the decision "Claude Code in a home of its own", which predates `/login` in the home. This repo develops itself through the loop from `~/.claude` at 0.17.0 until the release is cut, so the old layout needs no support in this change.
@@ -201,6 +241,17 @@ Touches:
- `README.md`
### 582. Write the review folder under the state folder into the generated `settings.json`'s `additionalDirectories`, so a moved `XDG_STATE_HOME` needs no hand edit.
Found while shipping the loop's generated Claude home. The tracked `settings.json` names the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`. Where `XDG_STATE_HOME` moves the state folder, README.md → Install asks the person to add the moved folder to the generated `settings.json` by hand, again after each build of the home. The code that builds the home can find the state folder through `loop_state.paths`, and write it.
Touches:
- `bin/claude_home/home.py`: `settings_written`, `unready` (small)
- `bin/loop_effects/effects.py`: `system_effects` (small)
- `settings.json`: lines 56-61
- `README.md`: `## Install` (small)
### 580. Call no scoring run for a release already cut whose last item the chunk moved to a later release.
When a chunk's first change moves its plan item out of a release already cut into the next one, as `CLAUDE.md` → "Working loop" asks, `larv-review needs-scoring-run <ID>` and `scoring-run-owed` still say the chunk "leaves release 0.17.0 with no plan item". The chunk then owes two scoring runs: eight seat launches and a task-bench run, hours of work. Item 579, a one-line change to an agent file, ran the full scoring twice for this reason.