Compare commits

..

67 Commits

Author SHA1 Message Date
lilleman 59ef9e209b Ground the judge's quote with markdown emphasis and whitespace ignored 2026-09-30 16:39:33 +02:00
lilleman 8e6b7239b3 Give a subagent the least its job needs, stated in its prompt 2026-09-29 10:59:46 +02:00
lilleman f454afd2c5 Point the rebuild's remaining items at rebuild's todo.md 2026-09-28 10:27:36 +02:00
lilleman fa014b1e13 Require the human's approval before the rebuild merges into main 2026-09-28 10:27:19 +02:00
lilleman 9b88254f54 Plan the rebuild of loop-claude and the review process on the rebuild branch 2026-09-28 03:46:41 +02:00
lilleman add0e1ccc4 File the 2026-09-28 panel's places 2026-09-28 01:01:50 +02:00
lilleman 9bad381dae Send an external auto-reviewer's behavior-changing fix back through §5 2026-09-28 00:55:56 +02:00
lilleman 2cab114cc3 Close every file loop-claude and its tests open 2026-09-28 00:53:28 +02:00
lilleman d36953dbd8 Define chunk in loop-claude --help 2026-09-28 00:47:24 +02:00
lilleman 8c434ebf7a Scope the judge's own-question rule to questions the agent raised 2026-09-28 00:42:02 +02:00
lilleman d8eebeddc8 Leave prose copies to "Comments and documentation" 2026-09-28 00:39:58 +02:00
lilleman e7d0440dc5 Gate the comprehension floor on every dimension and the overall 2026-09-28 00:39:14 +02:00
lilleman 0a6200341b Keep the fits-in-a-head thresholds in one list 2026-09-28 00:37:08 +02:00
lilleman d9f9e25ec0 Split larv-review's re-entry rules into the passes they re-enter 2026-09-28 00:36:13 +02:00
lilleman 90a18258cd Open every todo item with a bold one-sentence tagline 2026-09-27 23:35:20 +02:00
lilleman 93fde45870 Move the review protocol into principles/, beside the rules the reviewers already read 2026-09-27 22:51:04 +02:00
lilleman 53b6ffdff1 Name the test class ProjectName and the argv helper model_args 2026-09-27 22:49:43 +02:00
lilleman 37d31b9ab1 Rename granted, model and project for what they hold and return 2026-09-27 22:48:36 +02:00
lilleman 482932a5d0 Name a CHANGELOG line among the prose one spelling per goal covers 2026-09-27 22:43:39 +02:00
lilleman c96d92a3ff Name README.md and loop-claude --help for what the first release holds, and the write failure beside the read 2026-09-27 17:13:58 +02:00
lilleman bf9fd520c1 Reword the unreleased changelog so no line restates loop-claude --help 2026-09-27 17:12:54 +02:00
lilleman 43b04895c7 Leave the exit rule and the architect's re-check to the protocol, and file the prose pass's judge findings 2026-09-27 17:11:34 +02:00
lilleman 5537dbebe6 Name an unquoted verdict's question without claiming an interrupt 2026-09-27 17:09:44 +02:00
lilleman a0e2ac08c1 Expect an unquoted verdict's failure to name its question 2026-09-27 17:09:42 +02:00
lilleman 12170796d3 Spell the interrupt one way in loop-claude's help and failures, and let the protocol own the round-cap stop 2026-09-27 17:08:44 +02:00
lilleman 53438fd75d Expect an unquoted verdict's failure to name the interrupt 2026-09-27 17:08:37 +02:00
lilleman eba75e9fa7 Define worker and judge under Vocabulary and spell the interrupt one way 2026-09-27 17:06:57 +02:00
lilleman d2401599a7 Expect the judge's verdict to name the interrupt field 2026-09-27 17:06:33 +02:00
lilleman f397cf75a0 Say at judge what its flags buy and at archive why the stamp is the mtime 2026-09-27 17:05:02 +02:00
lilleman 8241b047a3 Record why every worktree of the checkout is trusted before an interrupt 2026-09-27 17:03:05 +02:00
lilleman 869aa03733 Check typed's interruption only over the text parts non_text cleared 2026-09-27 17:01:12 +02:00
lilleman 82cd7cbd8e Name each clause of typed for the entry kind it drops 2026-09-27 16:59:41 +02:00
lilleman 1f99088145 Say in run_cycle that the interrupt appends to the transcript and archive skips a written stamp 2026-09-27 16:58:17 +02:00
lilleman 6628d33987 Put the three-strikes rule in strike, shared by the worker and the judge 2026-09-27 16:56:06 +02:00
lilleman 5280ef2800 Drop run_cycle's docstring and tick the item off todo.md 2026-09-27 16:55:15 +02:00
lilleman ac09b29872 Judge once per pass of the interrupt loop 2026-09-27 16:54:42 +02:00
lilleman 70d816c830 Test the judge's and the transcript's Stop from run_cycle 2026-09-27 16:54:39 +02:00
lilleman 1a1ee613af Return every failure to main and exit only there 2026-09-27 16:52:46 +02:00
lilleman 23dd9956ea Test that every failure returns to main and exits only there 2026-09-27 16:52:10 +02:00
lilleman 63c37c54c9 Build and validate the reload state in one unit 2026-09-27 16:50:32 +02:00
lilleman d4cd4ffeac Run Claude Code on Opus with the 1M context window 2026-09-27 16:42:11 +02:00
lilleman 82f1a208bf Keep the mode of ~/.claude.json and the models file when loop-claude rewrites them 2026-09-27 15:07:09 +02:00
lilleman 4b2ebc95a5 Plan 0.1.0 by the dimension each item lifts, and record every dimension and the overall at 7.0 as its bar 2026-09-27 14:43:52 +02:00
lilleman ef4f088311 File the unclosed files the floor rerun surfaces 2026-09-27 14:36:04 +02:00
lilleman 406ef2b34a Skip the floor rerun when this run is on the floor, and drop the env-var guard 2026-09-27 14:36:04 +02:00
lilleman cb3bc8b3e1 Check for uv before running the floor suite, so its message is the only line 2026-09-27 14:34:27 +02:00
lilleman 9f8b413d51 Name python3 in Install, correct the panel and trust-shape entries, and delete the prose the sweep found copied 2026-09-27 14:34:07 +02:00
lilleman 7f155e933d Run the whole suite on the floor interpreter, so a 3.11-only call fails it too 2026-09-27 14:34:07 +02:00
lilleman c106c8e5f9 Read README as UTF-8 in the floor test 2026-09-27 14:34:07 +02:00
lilleman 4474d42d38 Compile the floor check from bytes so the interpreter picks the encoding, and keep the changelog line to the consumer's fact 2026-09-27 14:34:07 +02:00
lilleman f2437dfe10 Name the Python floor in README's Install and file the 2026-09-26 panel's places 2026-09-27 14:34:07 +02:00
lilleman e5921c7ef1 Test in its own module that every bin/ file compiles on the Python README names 2026-09-27 14:34:07 +02:00
lilleman 04869eba24 Record Python 3.11 as the floor bin/ parses on 2026-09-27 14:34:07 +02:00
lilleman 7ef4ff95b0 Test that every bin/ file compiles on the Python the decision log names as the floor 2026-09-27 14:34:07 +02:00
lilleman a670bcee7b Show the headless hint as the object to merge into the models file 2026-09-26 20:00:24 +02:00
lilleman 413aa2f638 Pin that one override still asks, and say where the catalog and the entry go 2026-09-26 19:59:43 +02:00
lilleman d4ae61a685 Say which file an edit to takes effect at the cycle boundary 2026-09-26 19:58:11 +02:00
lilleman d1ef542114 Echo the saved model, skip the ask when both overrides are set, and say when no catalog is cached 2026-09-26 19:58:05 +02:00
lilleman c80ba075ab Record that each project's model lives in loop-claude's own file 2026-09-26 19:53:19 +02:00
lilleman 17960e9bf3 Keep models another loop saved, exit when the save fails, and survive a malformed catalog 2026-09-26 19:53:11 +02:00
lilleman 99dc0cf0da Run loop-claude on a model saved per project, asking for it on the first run 2026-09-26 19:45:33 +02:00
lilleman 7d99d49ffb Quote the projects key in the wrong-shape message and record the one-message decline 2026-09-26 15:17:37 +02:00
lilleman c40c2d5ffa State the guard as the invariant it holds and keep entry for transcript lines 2026-09-26 15:15:46 +02:00
lilleman fe1a0f03ca Say could not read when the trust file is not an object whose projects maps paths to objects 2026-09-26 15:13:18 +02:00
lilleman df2b010fee Test that a trust file of the wrong shape is reported as unreadable 2026-09-26 15:13:11 +02:00
lilleman 0ccbfa4a3b Say how the copy is rejected for a value and for prose 2026-09-26 15:11:32 +02:00
lilleman 7122e69785 Say one spelling in two places is the same case, its copy rejected by naming the place that keeps it 2026-09-26 15:10:34 +02:00
20 changed files with 641 additions and 321 deletions
+15 -3
View File
@@ -1,14 +1,26 @@
# Working here
**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. larv-review leaves a PR from `rebuild` into main ready and unmerged.
Decisions live in `docs/decisions.md`:
- larv-review: a project under the comprehension floor is fixed at the capping dimension
- loop-claude: a judge decides interrupts, not the worker's self-report
- loop-claude: one session per project, at a fixed id
- loop-claude: the trust file is rewritten before an interrupt
- loop-claude: a reload into an older file is unsupported
- loop-claude: every worktree of the checkout is trusted before an interrupt
- loop-claude: a wrong-shape trust file gets one message, naming the shape
- bin/: the Python floor is README's Install prerequisite
- bin/: host python, no container
- comprehension floor: the 2026-09-25 four-seat score is the ratchet, and 0.1.0 waits on what caps it
- larv-review: a re-entered loop takes a fresh round cap
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
- loop-claude: the five section headers stay
- vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
- larv-review: a re-entered loop takes a fresh round cap
- loop-claude: a reload into an older file is unsupported
- loop-claude: a CR-only README.md is reported at line 1
- loop-claude: each project's model lives in loop-claude's own file
- rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole
- review: the round cap counts a pass's runs per chunk
- loop-claude: the judge is retried alone, on its own counter
- loop-claude: the judge loads `CLAUDE.md`
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
+3 -10
View File
@@ -2,15 +2,8 @@
## Unreleased
- The checkout holds `CLAUDE.md`, `AGENTS.md`, `settings.json`, `statusline.sh`, agents, skills and principles; credentials, transcripts and memory files never sync.
- `loop-claude <task>` runs a project's next chunk cycle after cycle, interrupting only for a decision that is yours or a release ready to cut.
- `loop-claude` exits 1 when the worker or the judge fails three times running, saying why: the worker's exit code, the signal that killed it, or an exit 0 without a result event; a verdict missing a field or quoting nothing in the transcript.
- `loop-claude` exits 2 when an interrupt gets no answer, saying why: stdin or stdout is not a terminal, or nothing was typed. Rerunning resumes the session.
- `loop-claude` archives each session's transcript under `~/.claude/loop-claude-transcripts/`, one folder per project; `LOOP_CLAUDE_TRANSCRIPTS` overrides the root.
- `loop-claude` runs at the checkout root wherever inside the checkout it is started.
- `loop-claude` says why when it cannot read `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
- `loop-claude` takes an edit to itself at the next cycle boundary once the edited file answers `--help`, and exits 1 when the edited file cannot read the running loop's state.
- `loop-claude --help` names the Claude Code version its transcript, session and trust handling were observed on; check it first when an upgrade breaks a cycle.
- `loop-claude` runs the model each project's settings pick; `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL` override it.
- First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does.
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
+9 -5
View File
@@ -8,14 +8,16 @@ Shorter is better, none is best — chat output, commit messages, comments, docs
- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
- **looping reviewer** — a reviewer rerun in rounds until no 🔴 and no 🟡 stand: stability, product-owner and a forge's auto-reviewer.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **looping reviewer** — a reviewer rerun in rounds: stability, product-owner and a forge's auto-reviewer.
- **plan** — `todo.md`.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`.
- **release** — a semver version the human cuts.
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
- **round cap** — the rounds one loop of a looping reviewer may take; a 🔴 or 🟡 open past it stops the loop at `needs input`.
- **round cap** — the rounds one loop of a looping reviewer may take.
- **session** — a Claude Code session: one id, what `claude --resume` continues.
- **trigger** — a sign that a change carries an architectural decision the decision log does not hold, so the architecture pass is warranted; `larv-review` §2 lists them.
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
## Prose
@@ -46,7 +48,8 @@ Apply it as a question to any design that routes A through B, or has A reach int
- When two spellings reach the same result, make one work and reject the other. Supporting both needs a stated reason, written down.
- Reject the redundant spelling as early as possible — at load, parse or compile, not at use — and have the error name the spelling to use instead: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`.
- Where the two spellings can *disagree*, this is a correctness rule. A caveat in the README does not close it.
- Applies to data formats, config, CLI flags and public APIs alike.
- One spelling in two places is two spellings: reject the copied value at load and name the place that keeps it.
- Applies to data formats, config, CLI flags, public APIs and prose alike, a CHANGELOG line included.
## Working loop
@@ -68,6 +71,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app <tool> …`.
- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match").
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
- Give a subagent the least its job needs, stated in its prompt: one that only reads — a prose or doc review — uses the Read tool alone, no shell; one that probes builds under a throwaway image tag it removes, writes only to the session scratchpad, and never removes an image or file it did not create.
- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds.
- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.)
@@ -110,7 +114,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise.
**Every decision links to a goal.** An entry names the goal it serves; one that cannot is a missing goal, and an entry already in the repo with no goal behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how.
**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link; N copies drift, whether they are comments or READMEs. Don't summarize what's behind the link or restate the identifier's own name.
**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name.
**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays.
@@ -135,7 +139,7 @@ Default to NO comment. Delete one that is any of:
**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all, and adding a section is a deliberate act you must justify. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
### Todo items (`todo.md`, tickets, plans)
- Write each item as the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `Accept undefined in MetadataValue and drop such keys on output`. BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
### Package README (what someone finds on npm or GitHub)
+3 -3
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project and every review to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`.
## Goals
@@ -15,7 +15,7 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
## Install
Check out the latest tag in `~/.claude`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`.
Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`.
## Release
@@ -25,7 +25,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
Test: `python3 -m unittest discover -s bin -p 'test_*.py'`
Test, with `uv` on `PATH`: `python3 -m unittest discover -s bin -p 'test_*.py'`
## Tracking a new file
+2 -2
View File
@@ -48,7 +48,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
## Your Output Format
Verdict, severities, rounds and declines: ~/.claude/agents/review-protocol.md. After the verdict:
Verdict, severities, rounds and declines: ~/.claude/principles/review-protocol.md. After the verdict:
**Surface affected**: <one line>
@@ -76,4 +76,4 @@ For each concern: state the problem from the customer's POV, the persona affecte
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs.
Per ~/.claude/principles/review-protocol.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs.
+2 -2
View File
@@ -127,7 +127,7 @@ Every PR gets at least this sweep; for sensitive surfaces also recommend the ded
## Output Format
Verdict, severities, rounds and declines: ~/.claude/agents/review-protocol.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows:
Verdict, severities, rounds and declines: ~/.claude/principles/review-protocol.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows:
### 🔴 Critical Issues (must fix)
Issues that will or very likely will cause bugs, crashes, data loss, or security vulnerabilities. Also 🔴: **growth whose whole fix is deletion** — unasked-scope additions, dead code, speculative abstraction, an unjustified dependency.
@@ -172,4 +172,4 @@ For each finding:
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it.
Per ~/.claude/principles/review-protocol.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it.
+5 -4
View File
@@ -1,6 +1,6 @@
---
name: systems-architect
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (cyclomatic complexity and method size as review prompts, per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent establishes or repairs those before evaluating fitness.\\n</commentary>\\n</example>"
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent establishes or repairs those before evaluating fitness.\\n</commentary>\\n</example>"
---
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
@@ -39,10 +39,11 @@ Short-term pragmatism on these points compounds into long-term decay. Push back
## Fits in a head
Working memory holds about seven chunks (Code That Fits in Your Head). So at every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away: a system of a handful of components, a component of a handful of modules, a method tracking at most ~7 things. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation.
Working memory holds about seven chunks (Code That Fits in Your Head). So at every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation.
The thresholds, each a prompt and never a verdict:
- a new developer explains what the system does from its structure in under 30 minutes
- a system of a handful of components; a component of a handful of modules
- a call chain reaches persistence or response in at most ~7 hops
- a method: cyclomatic complexity at most **7**; fits an **80×24 terminal window** (~24 lines); at most **~7 things a reader must track at once** (variables, branches, in-flight states — the chunks of working memory)
@@ -164,7 +165,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded (README or the relevant alternative).
**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/agents/review-protocol.md. A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation.
**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/principles/review-protocol.md. A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation.
**Re-checks are scoped, not fresh reviews.** When invoked to verify your own earlier findings (e.g. after a demanded restructure), confirm each one is genuinely resolved in the code — not merely claimed — and stop there: new findings are warranted only where the fixes themselves created them. Decisions recorded in `docs/decisions.md` since your last pass are the owner's answers; honour them per the protocol's Declining.
@@ -214,7 +215,7 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here:
Per ~/.claude/principles/review-protocol.md. What clears the bar here:
- Established architectural patterns (e.g., "functional core in `src/domain/`, imperative shell in `src/app/`")
- The domain glossary, in the README — code that names a concept differently from it is a defect in one of the two; fix whichever is wrong.
- Rejected alternatives, and requirement trades offered and declined, so they are not re-offered
+291 -146
View File
@@ -5,26 +5,32 @@ usage: loop-claude <task>
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads
the transcript against them. A question only the human can answer, or a release ready to cut, is an
interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json.
An unfinished chunk resumes the same session next cycle; a finished one starts a fresh session.
the transcript against them and rules whether the chunk, the smallest PR-able change, is finished.
A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume`
on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes
its session next cycle; the next chunk starts a fresh session.
Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Exit 1: no task, not inside a checkout, no premises, claude leaves no transcript, a reload with
unreadable state, or the worker or the judge fails three times running. A worker fails when claude
exits non-zero, is killed, or ends without a result event; a judge when its verdict misses a field
or quotes nothing in the transcript.
Exit 2: the human is needed and stdin or stdout is not a terminal, or the interrupt ended without
them typing anything. Rerunning resumes any open session.
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times
running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a
judge when its verdict misses a field or quotes nothing in the transcript.
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session.
Each project has one session, "A <path> loop-claude", <path> being the checkout relative to ~/code,
or to / outside it, deleted when the chunk finishes. Its transcript is archived under
$LOOP_CLAUDE_TRANSCRIPTS/<path>/ (default ~/.claude/loop-claude-transcripts) whenever the human is
asked and when the chunk finishes. LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL override the
model the project's Claude Code settings pick. A change to this file takes effect at the next cycle
boundary, once the new file answers --help.
$LOOP_CLAUDE_TRANSCRIPTS/<path>/ (default ~/.claude/loop-claude-transcripts) at every interrupt and
when the chunk finishes.
Claude Code internals this rests on, observed on 2.1.282:
Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json
and read each cycle; a project without an entry, as on its first run, is asked for one.
LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the
interrupt; with both set, nothing is asked.
A change to this script takes effect at the next cycle boundary, once the new script answers --help.
Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283:
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
folder and <session-id>.superseded-*/ and .orphaned-*.jsonl siblings belong to the same session.
- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one
@@ -34,10 +40,15 @@ Claude Code internals this rests on, observed on 2.1.282:
- `claude -p --output-format json --json-schema` returns the verdict under "structured_output".
- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words.
- ~/.claude.json holds projects.<path>.hasTrustDialogAccepted per checkout.
- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest
file has the highest fetchedAt.
"""
import dataclasses
import glob
import itertools
import json
import os
import pathlib
import shutil
import subprocess
import sys
@@ -45,12 +56,12 @@ import time
import uuid
ARCHIVE = os.path.expanduser(os.environ.get("LOOP_CLAUDE_TRANSCRIPTS", "~/.claude/loop-claude-transcripts"))
RELOAD_BASELINE = open(__file__, encoding="utf-8").read()
RELOAD_BASELINE = pathlib.Path(__file__).read_text(encoding="utf-8")
RELOAD_FLAG = "--reloaded"
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
JUDGE_RULES = (
"Decide whether the human must now be interrupted. ask=true when any of these appear:\n"
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
"- it carried on under an assumption that decides the deliverable and that the human could "
"reasonably reject; a caveat about transient state it then handled is not one\n"
@@ -59,12 +70,11 @@ JUDGE_RULES = (
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives the README text does not discriminate between - it does not "
"rule the rejected one out - and the choice materially changes the deliverable\n"
"ask=false otherwise. A sensible preference is not a derivation. Bookkeeping the agent settled "
"silently - what to document, wording, where a note goes - is not on its own a reason to "
"interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there.\n"
"The question must be one the agent itself raised. Never construct a question from facts the agent "
"stated. When ask=true, quote the agent's own wording where it already framed the question.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
"not yet run, CI not yet reported."
@@ -72,110 +82,107 @@ JUDGE_RULES = (
JUDGE_SCHEMA = {
"properties": {
"ask": {"type": "boolean"},
"evidence": {"description": "A verbatim quote from the transcript of the line that raises the question. Empty when ask is false.", "type": "string"},
"evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"},
"finished": {"type": "boolean"},
"question": {"description": "The single question to put to the human. Empty when ask is false.", "type": "string"},
"interrupt": {"type": "boolean"},
"question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"},
},
"required": ["ask", "evidence", "finished", "question"],
"required": ["evidence", "finished", "interrupt", "question"],
"type": "object",
}
@dataclasses.dataclass(frozen=True)
class Stop:
code: int
reason: str
def main():
argv = sys.argv[1:]
if argv[:1] == [RELOAD_FLAG]:
state = reloaded_state(argv[1:])
else:
state = {"cycle_number": 0, "failures": 0, "root": "", "task": " ".join(argv)}
if state["task"] in ("", "-h", "--help"):
print(__doc__.strip())
sys.exit(0 if state["task"] else 1)
task = state["task"]
root = state["root"] or checkout_root()
cycle_number, failures = state["cycle_number"], state["failures"]
try:
stop = run_loop(sys.argv[1:])
except KeyboardInterrupt:
stop = Stop(130, "")
if stop.reason:
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
sys.exit(stop.code)
def run_loop(argv):
state = loop_state(argv)
if isinstance(state, Stop):
return state
while True:
reload_if_edited(root, task, cycle_number, failures)
cycle_number += 1
premises = read_premises(root)
name = session_name(root)
print(f"\n=== cycle {cycle_number} ===", flush=True)
failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name))
if not failure:
failures = 0
continue
failures += 1
if failures == 3:
sys.exit(f"the worker failed three times running: {failure}")
print(f"retrying the worker in a minute: {failure}", file=sys.stderr)
time.sleep(60)
reload_if_edited(state)
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
premises = read_premises(state.root)
if isinstance(premises, Stop):
return premises
chosen = project_model(state.root)
if isinstance(chosen, Stop):
return chosen
name = session_name(state.root)
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), chosen)
if isinstance(failure, Stop):
return failure
state = dataclasses.replace(state, failures=state.failures + 1 if failure else 0)
if failure and (stop := strike("worker", state.failures, failure)):
return stop
def run_cycle(root, task, premises, name, session_id):
if failure := run_worker(root, worker_args(task, name, session_id, resuming=session_open(session_id))):
def strike(who, failures, failure):
if failures == 3:
return Stop(1, f"the {who} failed three times running: {failure}")
print(f"retrying the {who} in a minute: {failure}", file=sys.stderr)
time.sleep(60)
def run_cycle(root, task, premises, name, session_id, chosen):
if failure := run_worker(root, worker_args(task, name, session_id, chosen, resuming=session_open(session_id))):
return failure
path = session_file(session_id)
if not path:
sys.exit(f"claude left no transcript for session {session_id}")
verdict = judge(root, task, premises, render(entries(path)))
while verdict["ask"]:
archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if failure := interrupt(root, session_id, path, verdict["question"]):
print(failure, file=sys.stderr)
sys.exit(2)
verdict = judge(root, task, premises, render(entries(path)))
return Stop(1, f"claude left no transcript for session {session_id}")
# The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote.
while True:
verdict = judge(root, task, premises, render(entries(path)), chosen)
if isinstance(verdict, Stop):
return verdict
if not verdict["interrupt"]:
break
archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}")
if failure := interrupt(root, session_id, chosen, path, verdict["question"]):
return Stop(2, failure)
if verdict["finished"]:
archive(root, path, f"Task: {task}\n\nVerdict: finished")
delete_transcript_files(path)
return ""
def reload_if_edited(root, task, cycle_number, failures):
try:
source = open(__file__, encoding="utf-8").read()
except OSError as failure:
print(f"keeping the running script: {failure}", file=sys.stderr)
return
if source == RELOAD_BASELINE:
return
trial = subprocess.run([sys.executable, __file__, "--help"], capture_output=True, text=True)
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
return
state = {"cycle_number": cycle_number, "failures": failures, "root": root, "task": task}
os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(state)])
def reloaded_state(handed):
state = parse(handed[0]) if len(handed) == 1 else None
if not state or {"cycle_number", "failures", "root"} - state.keys() or not isinstance(state.get("task"), str) or not state["task"]:
sys.exit(f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
return state
def checkout_root():
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
if found.returncode != 0:
sys.exit(found.stderr.strip())
return Stop(1, found.stderr.strip())
return found.stdout.strip()
def read_premises(root):
try:
found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read())
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
except OSError as failure:
sys.exit(f"README.md in {root}: {failure.strerror} - no premises.")
return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
sys.exit(f"README.md is not UTF-8 on line {line} - no premises.")
return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.")
for name in ("Goals", "Audience"):
bodies = found.get(name, [])
if not bodies:
sys.exit(f"README.md has no ## {name} heading - no premises.")
return Stop(1, f"README.md has no ## {name} heading - no premises.")
if len(bodies) > 1:
sys.exit(f"README.md has ## {name} more than once - no premises.")
return Stop(1, f"README.md has ## {name} more than once - no premises.")
if not bodies[0]:
sys.exit(f"README.md has nothing under ## {name} - no premises.")
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
@@ -195,18 +202,19 @@ def sections(text):
def session_name(root):
# "A " is the human's cue in the session picker that the session is the loop's.
return f"A {project(root)} loop-claude"
return f"A {project_name(root)} loop-claude"
def archive(root, path, note):
folder = os.path.join(ARCHIVE, project(root))
# Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written.
folder = os.path.join(ARCHIVE, project_name(root))
try:
stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
make_private(folder)
dest = os.path.join(folder, f"{stamp}.md")
if not os.path.exists(dest):
with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy:
copy.write(f"# {stamp} {project(root)}\n\n{note}\n\n{render(entries(path))}\n")
copy.write(f"# {stamp} {project_name(root)}\n\n{note}\n\n{render(entries(path))}\n")
print(f"transcript: {dest}", file=sys.stderr)
except OSError as failure:
print(f"could not archive the transcript: {failure}", file=sys.stderr)
@@ -220,14 +228,148 @@ def make_private(folder):
os.umask(mask)
def model(variable):
return ["--model", os.environ[variable]] if os.environ.get(variable) else []
def replace_json(path, data, **dump):
staged = f"{path}.{os.getpid()}"
try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:
os.fchmod(handle.fileno(), mode)
json.dump(data, handle, **dump)
os.replace(staged, path)
except OSError as failure:
if os.path.exists(staged):
os.remove(staged)
return failure
return None
def project(root):
def model_args(variable, chosen):
return ["--model", os.environ.get(variable) or chosen]
def project_name(root):
return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/")
# The reload
@dataclasses.dataclass(frozen=True)
class LoopState:
cycle_number: int
failures: int
root: str
task: str
def loop_state(argv):
if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv)
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root()
return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
handed = parse(argv[1]) if len(argv) == 2 else None
shape = {field.name: field.type for field in dataclasses.fields(LoopState)}
if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]):
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
return LoopState(**handed)
def reload_if_edited(state):
try:
source = pathlib.Path(__file__).read_text(encoding="utf-8")
except OSError as failure:
print(f"keeping the running script: {failure}", file=sys.stderr)
return
if source == RELOAD_BASELINE:
return
trial = subprocess.run([sys.executable, __file__, "--help"], capture_output=True, text=True)
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
return
os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
# ~/.claude/loop-claude-models.json
def project_model(root):
if os.environ.get("LOOP_CLAUDE_JUDGE_MODEL") and os.environ.get("LOOP_CLAUDE_WORKER_MODEL"):
return ""
saved = os.path.expanduser("~/.claude/loop-claude-models.json")
name = project_name(root)
models = read_models(saved)
if isinstance(models, Stop):
return models
if chosen := models.get(name):
return chosen
chosen = ask_model(name, saved)
if isinstance(chosen, Stop):
return chosen
# Reread: another loop may have saved its project while this one waited on the human.
models = read_models(saved)
if isinstance(models, Stop):
return models
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
return Stop(1, f"could not save the model in {saved}: {failure.strerror}")
print(f"{name} runs on {chosen}", file=sys.stderr)
return chosen
def read_models(saved):
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
except FileNotFoundError:
return {}
except (OSError, ValueError) as failure:
return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
return models
def ask_model(name, saved):
if not (sys.stdin.isatty() and sys.stdout.isatty()):
return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"<model>\"}} into {saved}")
offered = catalog()
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr)
if not offered:
print(" no model catalog cached in ~/.claude/cache/model-catalog", file=sys.stderr)
while True:
try:
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
except EOFError:
print(file=sys.stderr)
return Stop(2, "no model picked")
if not answer:
continue
if not (offered and answer.isdecimal()):
return answer
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
print(f"pick 1 to {len(offered)}", file=sys.stderr)
def catalog():
newest = {}
for path in glob.glob(os.path.expanduser("~/.claude/cache/model-catalog/*.json")):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
# The transcript file
@@ -249,9 +391,10 @@ def delete_transcript_files(path):
def entries(path):
for raw in open(path, encoding="utf-8"):
if entry := parse(raw):
yield entry
with open(path, encoding="utf-8") as handle:
for raw in handle:
if entry := parse(raw):
yield entry
def parse(raw):
@@ -270,31 +413,34 @@ def human_turns(entries):
def typed(entry):
"""A human turn: a "user" entry, not isMeta, not promptSource "sdk" (the loop's own prompts), whose message.content is a string not starting with "<" (<command-name> and its kind) or one or more text parts, none starting with "[Request interrupted"."""
if entry.get("type") != "user" or entry.get("isMeta") or entry.get("promptSource") == "sdk":
if entry.get("type") != "user":
return False
content = entry.get("message", {}).get("content")
if isinstance(content, str):
return not content.startswith("<")
parts = content if isinstance(content, list) else []
return bool(parts) and all(isinstance(part, dict) and part.get("type") == "text" and not part.get("text", "").startswith("[Request interrupted") for part in parts)
meta = entry.get("isMeta")
loop_prompt = entry.get("promptSource") == "sdk"
command = isinstance(content, str) and content.startswith("<")
no_content = not isinstance(content, str) and not parts
non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts)
interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts)
return not (meta or loop_prompt or command or no_content or non_text or interruption)
# "assistant" entries and stream-json
def run_worker(root, args):
proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
done = False
for raw in proc.stdout:
event = parse(raw) or {}
if event.get("type") == "result":
done = True
elif event.get("type") == "assistant":
for part in event.get("message", {}).get("content", []):
if line := said(part, 160):
print(line, flush=True)
code = proc.wait()
with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc:
done = False
for raw in proc.stdout:
event = parse(raw) or {}
if event.get("type") == "result":
done = True
elif event.get("type") == "assistant":
for part in event.get("message", {}).get("content", []):
if line := said(part, 160):
print(line, flush=True)
code = proc.wait()
if code < 0:
return f"claude killed by signal {-code}"
if code:
@@ -302,7 +448,7 @@ def run_worker(root, args):
return "" if done else "claude exited 0 without a result event"
def worker_args(task, name, session_id, resuming):
def worker_args(task, name, session_id, chosen, resuming):
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
else:
@@ -312,7 +458,7 @@ def worker_args(task, name, session_id, resuming):
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
*model("LOOP_CLAUDE_WORKER_MODEL"),
*model_args("LOOP_CLAUDE_WORKER_MODEL", chosen),
]
@@ -339,37 +485,36 @@ def said(part, limit=400):
# --json-schema verdicts
def judge(root, task, premises, transcript):
def judge(root, task, premises, transcript, chosen):
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
args = [
"-p",
"--json-schema", json.dumps(JUDGE_SCHEMA),
*model("LOOP_CLAUDE_JUDGE_MODEL"),
*model_args("LOOP_CLAUDE_JUDGE_MODEL", chosen),
"--no-session-persistence",
"--output-format", "json",
"--permission-mode", "bypassPermissions",
"--tools", "",
]
prompt = judge_prompt(task, premises, transcript)
for attempt in range(3):
for failures in itertools.count(1):
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None
if not complete(verdict):
failure = proc.stderr.strip() or "the judge returned no verdict"
elif not grounded(verdict, transcript):
failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, asking: {verdict['question']}"
failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}"
else:
return verdict
if attempt == 2:
sys.exit(f"the judge failed three times running: {failure}")
print(f"retrying the judge in a minute: {failure}", file=sys.stderr)
time.sleep(60)
if stop := strike("judge", failures, failure):
return stop
def judge_prompt(task, premises, transcript):
return (
f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
# The tail, where an ask or a finish lands; the session's transcript grows cycle over cycle.
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
f"{JUDGE_RULES}"
)
@@ -380,22 +525,27 @@ def complete(verdict):
def grounded(verdict, transcript):
if not verdict["ask"]:
if not verdict["interrupt"]:
return True
evidence = verdict["evidence"]
return evidence.strip() != "" and evidence in transcript
evidence = plain(verdict["evidence"])
return evidence != "" and evidence in plain(transcript)
def plain(text):
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
# ~/.claude.json
def interrupt(root, session_id, path, question):
def interrupt(root, session_id, chosen, path, question):
print(f"\n{question}", file=sys.stderr)
if not (sys.stdin.isatty() and sys.stdout.isatty()):
return "stdin or stdout is not a terminal"
trust(checkouts(root))
before = human_turns(entries(path))
subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
subprocess.run(["claude", *model_args("LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
@@ -415,25 +565,20 @@ def trust(paths):
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
return
projects = data.setdefault("projects", {})
granted = [path for path in paths if not projects.get(path, {}).get("hasTrustDialogAccepted")]
if not granted:
projects = data.setdefault("projects", {}) if isinstance(data, dict) else None
if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()):
print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr)
return
for path in granted:
untrusted = [path for path in paths if not projects.get(path, {}).get("hasTrustDialogAccepted")]
if not untrusted:
return
for path in untrusted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
staged = f"{config}.loop-claude"
try:
with open(staged, "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2)
os.replace(staged, config)
except OSError as failure:
if failure := replace_json(config, data, indent=2):
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr)
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
main()
+199 -85
View File
@@ -30,6 +30,15 @@ def human(content):
return {"type": "user", "message": {"content": content}}
@contextlib.contextmanager
def umask(mask):
previous = os.umask(mask)
try:
yield
finally:
os.umask(previous)
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
@@ -38,10 +47,10 @@ class Sections(unittest.TestCase):
class ReadPremises(unittest.TestCase):
def exit_message(self, root):
with self.assertRaises(SystemExit) as stopped:
loop.read_premises(root)
self.assertTrue(stopped.exception.code.endswith("no premises."))
return stopped.exception.code
stop = loop.read_premises(root)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.endswith("no premises."))
return stop.reason
def test_names_what_is_missing(self):
texts = {
@@ -57,13 +66,13 @@ class ReadPremises(unittest.TestCase):
os.mkdir(readme)
self.assertIn("Is a directory", self.exit_message(root))
os.rmdir(readme)
open(readme, "wb").write(b"# T\n## Goals\n1. g\xff\n## Audience\nme\n")
pathlib.Path(readme).write_bytes(b"# T\n## Goals\n1. g\xff\n## Audience\nme\n")
self.assertIn("README.md is not UTF-8 on line 3", self.exit_message(root))
for text, missing in texts.items():
with self.subTest(missing=missing):
open(readme, "w").write(text)
pathlib.Path(readme).write_text(text)
self.assertIn(missing, self.exit_message(root))
open(readme, "w").write("# T\n## Goals\n1. g\n## Audience\nme\n")
pathlib.Path(readme).write_text("# T\n## Goals\n1. g\n## Audience\nme\n")
self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme")
@@ -100,9 +109,7 @@ class CheckoutRoot(unittest.TestCase):
def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
root = os.getcwd()
with self.assertRaises(SystemExit) as stopped:
loop.checkout_root()
self.assertTrue(stopped.exception.code)
self.assertEqual(loop.checkout_root().code, 1)
subprocess.run(["git", "init", "-q"], check=True)
os.makedirs("a/b")
with contextlib.chdir("a/b"):
@@ -112,38 +119,107 @@ class CheckoutRoot(unittest.TestCase):
self.assertEqual(loop.checkouts(root), [root])
class Project(unittest.TestCase):
class ProjectName(unittest.TestCase):
def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self):
with unittest.mock.patch.dict(os.environ, {"HOME": "/h"}):
self.assertEqual(loop.project("/h/code/a/b"), "a/b")
self.assertEqual(loop.project_name("/h/code/a/b"), "a/b")
self.assertEqual(loop.session_name("/h/code/a/b"), "A a/b loop-claude")
self.assertEqual(loop.project("/h/code"), "h/code")
self.assertEqual(loop.project("/srv/x"), "srv/x")
self.assertEqual(loop.project_name("/h/code"), "h/code")
self.assertEqual(loop.project_name("/srv/x"), "srv/x")
self.assertEqual(loop.session_name("/srv/x"), "A srv/x loop-claude")
class WorkerArgs(unittest.TestCase):
def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self):
args = loop.worker_args("the task", "A name", SESSION_ID, resuming=False)
args = loop.worker_args("the task", "A name", SESSION_ID, "m", resuming=False)
self.assertIn("--session-id", args)
self.assertEqual(args[args.index("--name") + 1], "A name")
self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR"))
def test_a_resumed_cycle_reuses_the_session(self):
args = loop.worker_args("paint the fence", "A name", SESSION_ID, resuming=True)
args = loop.worker_args("paint the fence", "A name", SESSION_ID, "m", resuming=True)
self.assertEqual(args[args.index("--resume") + 1], SESSION_ID)
self.assertNotIn("--name", args)
self.assertNotIn("paint the fence", args[1])
def test_the_project_settings_pick_the_model_unless_the_environment_names_one(self):
def test_the_project_model_runs_unless_the_environment_names_one(self):
with unittest.mock.patch.dict(os.environ):
os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None)
self.assertNotIn("--model", loop.worker_args("t", "n", SESSION_ID, resuming=False))
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}):
args = loop.worker_args("t", "n", SESSION_ID, resuming=False)
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1")
class ProjectModel(unittest.TestCase):
def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022):
for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"):
os.environ.pop(variable, None)
saved = pathlib.Path(home, ".claude", "loop-claude-models.json")
catalog = pathlib.Path(home, ".claude", "cache", "model-catalog")
catalog.mkdir(parents=True)
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
stop = loop.project_model("/srv/a")
self.assertEqual(stop.code, 2)
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', stop.reason)
self.assertFalse(saved.exists())
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a"), "")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a").code, 2)
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed,
):
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
self.assertEqual(typed.call_count, 3)
self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue())
self.assertIn("pick 1 to 2", sys.stderr.getvalue())
self.assertIn("srv/a runs on claude-sonnet-5", sys.stderr.getvalue())
self.assertNotIn("claude-opus-5)", sys.stderr.getvalue())
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600)
saved.chmod(0o640)
def saved_elsewhere_while_asking(prompt):
saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"}))
return "opus[1m]"
typed.side_effect = saved_elsewhere_while_asking
self.assertEqual(loop.project_model("/srv/b"), "opus[1m]")
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
self.assertEqual(typed.call_count, 4)
typed.side_effect = EOFError
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked"))
typed.side_effect = ["sonnet"]
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied"))
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}):
catalog.joinpath("new.json").write_text(json.dumps(shape))
with self.subTest(shape=shape):
self.assertEqual(loop.catalog(), [])
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch("builtins.input", side_effect=["1"]) as typed,
):
self.assertEqual(loop.project_model("/srv/e"), "1")
self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ")
self.assertIn("no model catalog cached", sys.stderr.getvalue())
for broken in ("{", "[]", '{"srv/a": 1}'):
saved.write_text(broken)
with self.subTest(broken=broken):
stop = loop.project_model("/srv/a")
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
self.assertEqual(saved.read_text(), broken)
class JudgePrompt(unittest.TestCase):
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
prompt = loop.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
@@ -156,7 +232,7 @@ class Archive(unittest.TestCase):
def test_keeps_the_copy_and_every_folder_it_creates_as_private_as_the_transcript(self):
with tempfile.TemporaryDirectory() as root:
transcript = os.path.join(root, "session.jsonl")
open(transcript, "w").write(json.dumps(assistant({"type": "text", "text": "said"})) + "\n")
pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n")
loop.ARCHIVE = os.path.join(root, "deep", "archive")
loop.archive("/srv/a/b", transcript, "note")
[copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names]
@@ -165,7 +241,7 @@ class Archive(unittest.TestCase):
while folder != root:
self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder)
folder = os.path.dirname(folder)
self.assertIn("said", open(copy).read())
self.assertIn("said", pathlib.Path(copy).read_text())
class Said(unittest.TestCase):
@@ -182,10 +258,10 @@ class DeleteTranscriptFiles(unittest.TestCase):
root = os.path.join(home, ".claude", "projects", "p")
os.makedirs(root)
transcript = os.path.join(root, f"{SESSION_ID}.jsonl")
open(transcript, "w").write("{}\n")
pathlib.Path(transcript).write_text("{}\n")
os.makedirs(os.path.join(root, SESSION_ID, "subagents"))
os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results"))
open(os.path.join(root, f"{SESSION_ID}.orphaned-1-ab.jsonl"), "w").write("{}\n")
pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n")
self.assertTrue(loop.session_open(SESSION_ID))
loop.delete_transcript_files(transcript)
self.assertEqual(os.listdir(root), [])
@@ -196,25 +272,30 @@ class Interrupt(unittest.TestCase):
def test_says_whether_no_terminal_or_nothing_typed_ended_it(self):
with tempfile.TemporaryDirectory() as root:
transcript = os.path.join(root, "session.jsonl")
open(transcript, "w").write("{}\n")
pathlib.Path(transcript).write_text("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "stdin or stdout is not a terminal")
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "stdin or stdout is not a terminal")
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything")
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "the interrupt ended without the human typing anything")
mocks["checkouts"].assert_called_with(root)
self.assertEqual(run.call_args.kwargs["cwd"], root)
run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n")
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "")
self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m")
def type_a_turn(*args, **kwargs):
with open(transcript, "a") as handle:
handle.write(json.dumps(human("typed")) + "\n")
run.side_effect = type_a_turn
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "")
class Trust(unittest.TestCase):
def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022):
config = pathlib.Path(home, ".claude.json")
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
@@ -223,8 +304,15 @@ class Trust(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
self.assertIn(f"could not read {config}: ", err.getvalue())
for shape in ([], {"projects": []}, {"projects": {"/a": 1}}):
config.write_text(json.dumps(shape))
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n")
self.assertEqual(json.loads(config.read_text()), shape)
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
config.write_text(json.dumps(data))
config.chmod(0o600)
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
self.assertEqual(err.getvalue(), "")
@@ -241,6 +329,8 @@ class Trust(unittest.TestCase):
loop.trust(["/c"])
self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n")
self.assertEqual(json.loads(config.read_text()), data)
self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
self.assertEqual(os.listdir(home), [".claude.json"])
class Parse(unittest.TestCase):
@@ -252,36 +342,44 @@ class Parse(unittest.TestCase):
class Grounded(unittest.TestCase):
def test_an_interrupt_must_quote_the_transcript(self):
self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything"))
self.assertTrue(loop.grounded({"ask": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(loop.grounded({"ask": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(loop.grounded({"ask": True, "evidence": ""}, "the transcript"))
self.assertFalse(loop.grounded({"ask": True, "evidence": " "}, "the transcript"))
self.assertTrue(loop.grounded({"interrupt": False, "evidence": ""}, "anything"))
self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": ""}, "the transcript"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": " "}, "the transcript"))
def test_a_quote_may_drop_markdown_emphasis_and_reflow_whitespace(self):
transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it."
self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Your step:\n```\n./run.sh\n```\nRun it."}, transcript))
self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Your step: ``` ./run.sh ``` Run it."}, transcript))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": "**"}, transcript))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertTrue(loop.complete({"ask": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(loop.complete({"ask": False}))
self.assertTrue(loop.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(loop.complete({"interrupt": False}))
self.assertFalse(loop.complete(None))
STUB_CLAUDE = """#!/usr/bin/env python3
import json, os, sys
import json, os, pathlib, sys
args = sys.argv[1:]
open(os.environ["STUB_CALLS"], "a").write(json.dumps([os.getcwd(), *args]) + "\\n")
with open(os.environ["STUB_CALLS"], "a") as calls:
calls.write(json.dumps([os.getcwd(), *args]) + "\\n")
if "--json-schema" in args:
plan = open(os.environ["STUB_VERDICTS"]).read().split()
open(os.environ["STUB_VERDICTS"], "w").write(" ".join(plan[1:]))
plan = pathlib.Path(os.environ["STUB_VERDICTS"]).read_text().split()
pathlib.Path(os.environ["STUB_VERDICTS"]).write_text(" ".join(plan[1:]))
if plan[0] == "fail":
sys.exit(1)
ask = plan[0] in ("ask", "unquoted")
print(json.dumps({"structured_output": {"ask": ask, "evidence": {"ask": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if ask else ""}}))
interrupt = plan[0] in ("interrupt", "unquoted")
print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}}))
else:
flag = "--session-id" if "--session-id" in args else "--resume"
folder = os.path.expanduser("~/.claude/projects/p")
os.makedirs(folder, exist_ok=True)
open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a").write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n")
with open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a") as transcript:
transcript.write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n")
print(json.dumps({"type": "result"}))
"""
@@ -298,7 +396,7 @@ class RunWorker(unittest.TestCase):
}
with unittest.mock.patch.dict(os.environ, {"PATH": f"{bin}:{os.environ['PATH']}"}), unittest.mock.patch.object(sys, "stdout", io.StringIO()):
for failure, script in scripts.items():
open(stub, "w").write(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n")
pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n")
os.chmod(stub, 0o700)
self.assertEqual(loop.run_worker(bin, []), failure)
@@ -307,89 +405,105 @@ class RunCycle(unittest.TestCase):
def test_resumes_until_the_judge_calls_the_chunk_finished_and_rejudges_a_failed_or_unquoted_verdict(self):
with tempfile.TemporaryDirectory() as home:
stub = os.path.join(home, "claude")
open(stub, "w").write(STUB_CLAUDE)
pathlib.Path(stub).write_text(STUB_CLAUDE)
os.chmod(stub, 0o700)
calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts")
open(verdicts, "w").write("fail continue finished unquoted continue")
pathlib.Path(verdicts).write_text("fail continue finished unquoted continue")
loop.ARCHIVE = os.path.join(home, "archive")
environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts}
with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False):
for _ in range(3):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID), "")
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID)
self.assertEqual(stopped.exception.code, 2)
said = "".join(str(call.args[0]) for call in stderr.write.call_args_list)
self.assertIn(f"transcript: {loop.ARCHIVE}", said)
self.assertIn("not a terminal", said)
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
pathlib.Path(verdicts).write_text("interrupt")
with unittest.mock.patch("sys.stderr") as stderr:
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal"))
self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
pathlib.Path(verdicts).write_text("interrupt fail fail fail")
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(loop, "interrupt", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5").code, 1)
with unittest.mock.patch.object(loop, "session_file", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(1, f"claude left no transcript for session {SESSION_ID}"))
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
open(verdicts, "w").write(plan)
with self.assertRaises(SystemExit) as stopped:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID)
self.assertTrue(stopped.exception.code.startswith("the judge "))
pathlib.Path(verdicts).write_text(plan)
stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the judge "))
if plan.startswith("unquoted"):
self.assertIn("asking: q?", stopped.exception.code)
self.assertEqual(open(verdicts).read(), "")
self.assertEqual({json.loads(line)[0] for line in open(calls)}, {home})
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--resume"])
self.assertIn("for the question: q?", stop.reason)
self.assertEqual(pathlib.Path(verdicts).read_text(), "")
self.assertEqual({json.loads(line)[0] for line in pathlib.Path(calls).read_text().splitlines()}, {home})
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines()) if "--json-schema" not in args]
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(sleep.call_count, 6)
self.assertEqual(sleep.call_count, 8)
self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"})
class Reload(unittest.TestCase):
def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_state_as_one_json_argument(self):
with tempfile.TemporaryDirectory() as root:
script = os.path.join(root, "loop-claude")
open(script, "w").write(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n"))
pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n"))
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
loop.reload_if_edited("/r", "do it", cycle_number=1, failures=0)
loop.reload_if_edited(loop.LoopState(1, 0, "/r", "do it"))
execv.assert_not_called()
open(script, "w").write(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
environment = dict(os.environ)
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
loop.reload_if_edited("/r", "do it", cycle_number=1, failures=2)
loop.reload_if_edited(loop.LoopState(1, 2, "/r", "do it"))
execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})])
self.assertEqual(dict(os.environ), environment)
class Main(unittest.TestCase):
def test_exits_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})]):
with self.subTest(handed=handed), unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, *handed]), self.assertRaises(SystemExit) as stopped:
def test_exits_only_here_with_the_stop_the_loop_returned(self):
for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")):
with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
self.assertEqual(stopped.exception.code, code)
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n")
with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, 130)
class RunLoop(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
with self.subTest(handed=handed):
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
def test_resumes_the_root_and_counters_a_reload_handed_over(self):
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle")]
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
stopped = loop.Stop(1, "stopped")
with contextlib.ExitStack() as stack:
mocks = [stack.enter_context(patch) for patch in patches]
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]))
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
mocks[3].side_effect = SystemExit(0)
with self.assertRaises(SystemExit):
loop.main()
mocks[3].return_value = stopped
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped)
mocks[0].assert_not_called()
mocks[1].assert_called_once_with("/r")
mocks[2].assert_called_once_with("/r", "do it", 3, 2)
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
self.assertEqual(mocks[3].call_args.args[0], "/r")
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"]))
mocks[4].assert_called_once_with("/r")
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
mocks[0].return_value = "/s"
with self.assertRaises(SystemExit):
loop.main()
self.assertEqual(loop.run_loop(["do", "it"]), stopped)
mocks[0].assert_called_once_with()
mocks[1].assert_called_with("/s")
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
for leaf in (0, 1, 4):
with self.subTest(leaf=leaf):
mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}")
self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value)
mocks[leaf].return_value = "/s"
mocks[3].return_value = None
mocks[3].side_effect = ["claude exited 3"] * 3
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]))
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
sleep = stack.enter_context(unittest.mock.patch("time.sleep"))
with self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3"))
self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
self.assertEqual(sleep.call_count, 2)
self.assertEqual(stopped.exception.code, "the worker failed three times running: claude exited 3")
if __name__ == "__main__":
+23
View File
@@ -0,0 +1,23 @@
import pathlib
import re
import shutil
import subprocess
import sys
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
class PythonFloor(unittest.TestCase):
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(named, "README.md's Install names `Python 3.N or newer`")
floor = (3, int(named.group(1)))
if sys.version_info[:2] == floor:
self.skipTest("this run is on the floor")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches the floor interpreter; see README.md's Test line")
suite = ["python", "-m", "unittest", "discover", "-s", "bin", "-p", "test_*.py"]
ran = subprocess.run(["uv", "run", "--no-project", "--python", "%d.%d" % floor, *suite], capture_output=True, cwd=ROOT, text=True)
self.assertEqual(ran.returncode, 0, ran.stderr)
+45 -5
View File
@@ -16,26 +16,66 @@
2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. Valid while no flag skips the dialog.
## loop-claude: every worktree of the checkout is trusted before an interrupt
2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path.
## loop-claude: a wrong-shape trust file gets one message, naming the shape
2026-09-26, larv-review, declining a product-owner nit. Serves goal 4. `trust` says `not an object whose "projects" maps paths to objects` for every wrong shape; naming the failing path would add a branch to `trust`, and the interrupt still lands in Claude Code's own dialog, which shows the path. The 2026-09-25 panel's `trust` as the unit least wanted to modify was the first reason; the 2026-09-26 panel named `typed`, so the entry rests on the dialog. Valid while the interrupt lands in that dialog.
## bin/: the Python floor is README's Install prerequisite
2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python.
## bin/: host python, no container
2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run the same way. Valid while claude runs on the host.
## comprehension floor: the 2026-09-25 four-seat score is the ratchet, and 0.1.0 waits on what caps it
## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
2026-09-25, larv-review, carrying lilleman's 2026-09-24 target of every dimension at 7.0 or above. Serves goal 4. Junior A, Mid A, the maintainability senior and the inherited architect, depth 1 over every non-test file, blind to `todo.md` and this log: Navigation 8.0, Locality 6.0, Shape 7.0, Self-sufficiency 6.5, overall 7.0; on 2026-09-24 they were 8.0, 5.75, 7.5, 6.0, 6.75. Every seat scored Locality 6 and every overall sits on that cap; three of four named `trust` as the unit they would least want to modify. Shape fell 0.5 on the flat 36-name namespace in `bin/loop-claude`, the 18-item bar in `agents/systems-architect.md` and `trigger` meaning three things. The places named sit in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats.
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats.
## loop-claude: the five section headers stay
2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its four siblings indexing the script by the Claude Code internal each group touches. Valid until a scoring run scores Navigation without them.
## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, as skills already cite `CLAUDE.md` headings, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run.
2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run.
## larv-review: a re-entered loop takes a fresh round cap
2026-09-24, larv-review. Serves goal 4. The cap stops a loop that does not converge on one set of findings; a re-entry is a new set. A cap shared across the whole flow would skip §6.5's closing round exactly when §5 ran long. Valid while the protocol caps rounds per loop.
2026-09-24, larv-review. Serves goal 4. The cap stops a loop that does not converge on one set of findings; a re-entry is a new set. A cap shared across the whole flow would skip §6.5's closing round exactly when §5 ran long. Valid until the rebuild merges; superseded then by "review: the round cap counts a pass's runs per chunk".
## loop-claude: a reload into an older file is unsupported
2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` on disk is rolled back to a version with an older handover dies with a traceback in that older file, which this version cannot change; the human who rolled it back reruns `loop-claude <task>`. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this.
2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded <state>` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude <task>`. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this.
## loop-claude: a CR-only README.md is reported at line 1
2026-09-26, larv-review. Serves goal 4. The line of a non-UTF-8 byte counts `\n`, so a file with classic-Mac `\r` endings reports line 1 whatever line an editor shows; no machine the audience runs writes such a file. Valid while the audience is the author's own machines.
## loop-claude: each project's model lives in loop-claude's own file
2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. Valid while Claude Code keeps rewriting the settings' model from inside a session.
## rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole
2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. Valid until the rebuild merges.
## review: the round cap counts a pass's runs per chunk
2026-09-28, lilleman, for the rebuild. Serves goal 4. A pass runs at most three times per chunk, re-entries included, and a fourth run asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask.
## loop-claude: the judge is retried alone, on its own counter
2026-09-28, lilleman, for the rebuild. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run.
## loop-claude: the judge loads `CLAUDE.md`
2026-09-28, lilleman, for the rebuild. Serves goal 4. The judge rules on chunks, releases and premises, which `CLAUDE.md` → "Vocabulary" and "Working loop" define; `--bare` would leave it the prompt's words alone. Valid while those definitions live in `CLAUDE.md`.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp collapses two states. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
-8
View File
@@ -1,8 +0,0 @@
# Principles
The technical principles the reviewer agents in `../agents/` hold every project to.
Each applies them through its own lens:
- `../agents/stability-reviewer.md` — enforces them at code level, per PR.
- `../agents/systems-architect.md` — treats them as baseline constraints on every design.
- `../agents/product-owner-reviewer.md` — checks the externally-visible ones (`rest-apis.md`, `frontend.md`, and what surfaces from `technical-principles.md`) from the customer's perspective.
-4
View File
@@ -1,9 +1,5 @@
# Frontend principles
Follow all of them. The two groups below are for orientation, not permission to skip the
second one: **foundational stances** are structural bets that are expensive to reverse;
**quality attributes** are the -ilities and UX outcomes you uphold continuously.
General principles (KISS, DRY, …) live in `technical-principles.md` and apply here too.
## Foundational stances
+1 -1
View File
@@ -4,7 +4,7 @@
Log levels have a standard, RFC5424: { emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 }.
We follow a simplified variant (sadly with non-matching numbers atm):
We follow a simplified variant:
* **0: Error** - Crash or equivalent catastrophe that needs fairly immediate action.
* **1: Warning** - The app works, for now, but something is wrong and needs to be fixed.
@@ -24,11 +24,12 @@ A review's first line, derived mechanically from the findings:
- Surface everything in one round.
- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each previous 🔴 and 🟡 is resolved — re-run the scenario, don't trust the claim — then pass over what changed. A fix spawns a new finding only where the fix itself introduced a real problem.
- The loop exits on no 🔴 and no 🟡. The 🟢 and ❓ left then are addressed in that same round — fixed, answered, declined or filed in `todo.md` — and trigger no further round. A nit whose fix changes behaviour is a fresh finding and takes a round.
- Round cap: 3; when it stops the loop, list what is open. Systems-architect gets one scoped re-check; still `BLOCK` → `needs input`.
- Round cap: 3; when it stops the loop, list what is open and ask the human.
- Systems-architect gets one scoped re-check; still `BLOCK` → ask the human.
## Declining
Anything below 🔴 the caller may decline where the reason is sound, sits consistently with the repo's goals, and confidence is very high; the decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason that contradicts a goal, or that no goal speaks to and you are not confident in, is a gap in the goals: propose the goal or rule that settles the whole class, show what falls out of it for this instance, and take the human's answer — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix.
Anything below 🔴 the caller may decline where the reason is sound, sits consistently with the repo's goals, and confidence is very high; the decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason that contradicts a goal, or that no goal speaks to and you are not confident in, is a gap in the goals, taken per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess" — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix.
A reviewer honours an accepted risk in `docs/decisions.md` and a finding declined this way: it stays declined and is not raised again.
+1
View File
@@ -9,6 +9,7 @@
"~/code"
]
},
"model": "opus[1m]",
"disableClaudeAiConnectors": true,
"statusLine": {
"type": "command",
+2 -3
View File
@@ -64,7 +64,7 @@ handful of units with the files around them.
**3. Full sweep, on request.** Every line, tests included, in as many passes as it takes. Slow and
expensive, and the only depth that can say a place is clear because somebody read it. Reserve it
for a deliberate in-depth audit — a number about to be published, a handover being priced, a
sampled score under dispute. A review gate never runs it: gates run depth 1 or 2.
sampled score under dispute.
## The seats
@@ -240,5 +240,4 @@ it apart; it does not by itself prove a ceiling worthless against future drift.
Panelists also surface real defects in passing — dead values, unstated invariants, doc gaps.
Verify each in the code yourself before reporting it; a panelist's incidental claim is a lead, not
a finding. Everything that survives lands where the project's own working loop puts findings — a
plan item under a release, a decision entry — never in chat alone.
a finding. Everything that survives lands per `~/.claude/CLAUDE.md` → "Working loop".
+23 -32
View File
@@ -5,19 +5,19 @@ description: Ship a work chunk through review to a merged PR; decisions land in
# larv-review — ship the chunk, review until clean, gate green, merge
You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §12. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work.
You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §11. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A fix made in any pass is a change the passes before it in this order never saw; a pass it re-enters says so, and a re-entry is a new loop with its own round cap.
**Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary.
Words: `~/.claude/CLAUDE.md` → "Vocabulary". Verdicts, severities, round caps, declining a finding and where decisions are recorded: ~/.claude/agents/review-protocol.md. Its Declining section also binds `/security-review` and the external reviewer in §10.
Words: `~/.claude/CLAUDE.md` → "Vocabulary". Verdicts, severities, round caps, declining a finding and where decisions are recorded: ~/.claude/principles/review-protocol.md. Its Declining section also binds `/security-review` and the external reviewer in §9.
## 0. Preconditions
- Not a git repo → say so and stop.
- Someone else's PR, or the user asked for opinions only → single stability pass, report findings, done (skip shipping, fixing, the loops and the merge).
- Prose only — markdown, docs, comments, no code — → the reviewer loops add nothing: ship the branch (§1), the prose pass (§8), green gate (§9), merge (§11). Say so in the summary. Prose an outside reader lands on — public API docs, README, CHANGELOG, error or deprecation text — still takes §6's product-owner pass.
- Prose only — markdown, docs, comments, no code — → the reviewer loops add nothing: ship the branch (§1), the prose pass (§7), green gate (§8), merge (§10). Say so in the summary. Prose an outside reader lands on — public API docs, README, CHANGELOG, error or deprecation text — still takes §6's product-owner pass.
- Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status.
- **Nothing merges and nothing is reported done without premises**, which `~/.claude/CLAUDE.md` → "Working loop" holds all planned work on. Premises missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. The same content in `AGENTS.md`, in `docs/` or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. Only what that section lets through without them reaches review.
- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. Only what that section lets through without them reaches review.
## 1. Ship the branch (idempotent — skip whatever already exists)
@@ -43,29 +43,29 @@ Otherwise, any one of these is grounds for the pass:
- diff > ~400 non-generated lines, or touching > ~5 modules
- a previous stability round escalated to systems-architect
No signal fires → skip it, say so in the summary, don't ask. A signal fires with no record behind it → ask the user (AskUserQuestion) with the evidence and your recommendation. No user reachable → run the pass.
No signal fires → skip it, say so in the summary, don't ask. A signal fires with no record behind it → ask the user (AskUserQuestion) with the evidence and your recommendation. No user reachable → run the pass. A fix made in any pass after §3 takes this trigger again on what it changed.
## 3. Architecture pass (when warranted)
Launch **systems-architect**: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts.
- **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary.
- **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect once, scoped to verifying its own findings. Still BLOCK → stop and report: `needs input`.
- **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect once, scoped to verifying its own findings. Still BLOCK → stop and ask the human.
- **ALIGN** → apply what is cheap now; ask the user about the rest — each item becomes a fix, a ticket, or a documented decision, never a silent drop.
- **APPROVE** / **APPROVE WITH NITS** → proceed; nits per the protocol's rounds.
### Comprehension floor (with every architecture pass)
Invoke the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff, and at depth 1 or 2. Below 7.0 the chunk does not merge: fix what the capping dimension names, or take the user's explicit decision to ship under it and record that in `docs/decisions.md` with the score and the dimension. At or above 7.0 the score is still a ratchet — a later chunk may not lower it — and the four dimension scores go in the summary so the next run can see the direction of travel.
Invoke the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel.
## 4. Security pass (whenever the chunk changed anything but test code)
Run the built-in **`/security-review`** skill over the branch diff. It is the pass of record here: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse.
Run the built-in **`/security-review`** skill over the branch diff. It is the pass of record here: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. A fix made in any pass after it re-enters it only where it opens a new untrusted-input boundary or touches authn/authz, secrets or crypto.
- **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. Verification showing it is not real is no decline but a disproof — record what disproved it, since a finding that is factually wrong needs no goal to reject.
- **MEDIUM** → fix in this chunk, under the protocol's Declining section.
- **LOW** → treat as a 🟢.
- A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item at the top under `## Security`, naming the exposure and the path it reaches, per `~/.claude/CLAUDE.md` → "Todo items". Say whether it is in this chunk's blast radius; filing it is not fixing it.
- A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item per `~/.claude/CLAUDE.md` → "Todo items"; filing it is not fixing it.
**Escalate to a full scan** — the `claude-security` plugin (`/claude-security` → "Scan changes"), first-party and agent-verified — when the change touches authn/authz, secrets or crypto, a new untrusted-input boundary, or a new external surface. Same shape of judgment as §2's trigger: a signal with no record behind it, and a user reachable, is an ask. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass.
@@ -73,14 +73,16 @@ Run the built-in **`/security-review`** skill over the branch diff. It is the pa
## 5. Stability loop
A fix sent back here opens its loop with a round prompted with the fix's scope and why it changed.
1. Launch **stability-reviewer**, prompted per the protocol's rounds.
2. Fix every 🔴 **and every 🟡** along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. §9's gate verifies what the final round's nits changed.
2. Fix every 🔴 **and every 🟡** along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. §8's gate verifies what the final round's nits changed.
3. Commit and push each round's fixes so CI feedback accumulates while the loop runs.
4. Carry any 🔀 product-owner escalation into §6.
## 6. Product-owner loop (when a reviewer escalates to it)
## 6. Product-owner loop (when escalated to, or an external surface changed)
A 🔀 product-owner-reviewer escalation from any pass above runs it. Nothing escalated and no external surface changed → skip it, say so in the summary.
A 🔀 product-owner-reviewer escalation from any pass runs it, and so does a change to an external surface, a fix from any pass after it included. Neither → skip it, say so in the summary.
1. Launch **product-owner-reviewer** with the change and the external surface it touches — API, CLI, UI, error and deprecation text a consumer reads, README and docs an outside reader lands on — prompted per the protocol's rounds.
2. Apply what it asks for, under the protocol's Declining section. Its findings are about the consumer's experience (wording, discoverability, upgrade path, the edge case a persona hits), so the fix is as often a message or a doc as it is code.
@@ -88,18 +90,7 @@ A 🔀 product-owner-reviewer escalation from any pass above runs it. Nothing es
4. Approved having changed nothing → you are done here; there is nothing to re-verify.
5. Otherwise re-enter §5 over what this loop changed.
## 7. Re-entry
A fix made in any pass is a change the passes before it never saw. It re-enters:
- §3 only where it fires a §2 signal of its own.
- §4 only where it opens a new untrusted-input boundary or touches authn/authz, secrets or crypto.
- §5 where §6.5 or §9 sends it there, prompted with the fix's scope and why it changed.
- §6 where it changed an external surface or a reviewer escalated 🔀 to it, as at first entry.
A re-entry is a new loop with its own round cap.
## 8. Prose pass (every chunk)
## 7. Prose pass (every chunk)
Two scopes:
@@ -115,29 +106,29 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph
When §2's trigger says the architecture pass is warranted, this pass widens with it: the fresh-context agent reads every prose file the repo owns rather than only the cited sections. That is the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk.
## 9. Green gate, PR ready
## 8. Green gate, PR ready
- Run the project's test suite locally unless the final stability round already left it verified green; fix, commit, push.
- Watch the forge's checks until every one passes. A red check is a finding: fix → commit → push → watch again. A CI fix that changes behavior (not config or a flake) re-enters §5.
- No CI configured → the gate is local tests only; note it in the summary (a missing merge gate on a production-horizon project is architect-finding material).
- Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix.
## 10. External auto-reviewer (when the repo has one)
## 9. External auto-reviewer (when the repo has one)
Marking the PR ready is what summons CodeRabbit and its kind, so this follows §9.
Marking the PR ready is what summons CodeRabbit and its kind, so this follows §8.
- Detect one from the repo — a reviewer's config file (`.coderabbit.yaml` and the like), or its comments on the repo's earlier PRs. None found → skip, say so.
- Wait up to **10 minutes** for its first review, checking about once a minute. Nothing by then → note it in the summary and carry on; a reviewer that arrives later is read the next time anyone visits the PR, never waited on twice.
- Its findings follow the protocol like every reviewer above — no more authority, and no less; anything it marks blocking is a 🔴. Fix → commit → push, then wait up to **5 minutes** for its re-review of the new commit.
- Its findings follow the protocol like every reviewer above — no more authority, and no less; anything it marks blocking is a 🔴. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit.
## 11. Goal alignment, then merge
## 10. Goal alignment, then merge
1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; state the conflict and ask: `needs input`.
2. The item ships into a release later than one that is finished and uncut → leave the PR ready and unmerged; say that release is ready to cut: `needs input`.
1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict.
2. The item ships into a release later than one that is finished and uncut → leave the PR ready and unmerged; tell the human that release is ready to cut.
3. Aligned, every loop exited and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
4. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". Ticking it off emptied its release → the summary says the release is ready to cut.
5. Stop. The next chunk gets a fresh session. A release is the human's — prepare it, never cut it.
## 12. Wrap up
## 11. Wrap up
Summarize: PR URL and final state, every reviewer's verdict, rounds used per loop, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
-2
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env bash
# Claude Code status line. Input: statusline JSON on stdin.
set -uo pipefail
input=$(cat)
@@ -40,7 +39,6 @@ humanize_tokens() {
fi
}
# " 2h15m left (01:23)" for a reset epoch. Weekday shown when it lands on another day.
reset_suffix() {
local epoch=$1 secs at fmt
epoch=$(printf '%.0f' "$epoch")
+14 -4
View File
@@ -2,8 +2,18 @@
## 0.1.0
Ordered by how many seats of the 2026-09-25 scoring panel (`docs/decisions.md`) named the place; each is one chunk.
**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. What remains of the rebuild is `rebuild`'s `todo.md` (`git show origin/rebuild:todo.md`), where each chunk ticks its item off; this copy stays as planned until the merge. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole.
- Say under `CLAUDE.md` → "One spelling per goal" that one spelling in two places is the same case, and what its rejection names.
- Say `could not read` when `~/.claude.json` parses to anything but an object whose `projects` maps paths to objects, today a traceback before the interrupt.
- State in `docs/decisions.md` the oldest Python `bin/` must parse on, today unstated and 3.11 by the last review.
Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
- **Pin loop-claude's behaviour in black-box tests that pass against main's script.** Run `bin/loop-claude` as a subprocess with a fake `claude` on `PATH` and temporary `HOME` and checkout: premises refusals, exit codes, the worker's and the judge's three strikes, an ungrounded verdict, the interrupt off a terminal, the session resumed while unfinished and fresh after finishing, the models file and `~/.claude.json` rewritten with their modes, the reload at a cycle boundary.
- **Lay out `bin/loop-claude` as a launcher over a `bin/loop_claude/` package, with the loop, checkout and premises moved in.** The launcher resolves its own symlink, injects `Paths` and the environment, and is the only thing that exits; `main` owns the loop state, carries it across a reload on argv, and maps `Stop | Retry | Continue`. The black-box tests pass unchanged.
- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made.
- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2.
- **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds.
- **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.**
- **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`.
- **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over.
- **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale.
- **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log.
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 run, and open its PR into main for the human.** ⚠️ Leave that PR ready and unmerged: only the human merges it, after approving the whole rebuild. A dimension under the floor gets its places filed above this item. Before merging, a loop running main's script reloads into the new one at its next cycle boundary: accept main's `--reloaded` state, or say in the changelog that running loops stop once.