Compare commits
145 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 53a3149b25 | |||
| b95d4fe16b | |||
| 4d74622617 | |||
| 8b45f1f39b | |||
| 9d8fa84c75 | |||
| 7f9de5c19f | |||
| e90b7cb9d7 | |||
| 75529c8592 | |||
| 1bcef56657 | |||
| cca0b67b8b | |||
| 998cc3ac85 | |||
| 6a1a1d9027 | |||
| 8f34915bb8 | |||
| 0fc6afd1e7 | |||
| 750c417c2d | |||
| 194601aeda | |||
| 089d8fa1dc | |||
| 4cd79e5b1a | |||
| 2602231b23 | |||
| b833ccb982 | |||
| 35340970a2 | |||
| 5554659678 | |||
| 564a2fe3a1 | |||
| 20db779a0d | |||
| c9afc369f9 | |||
| 4adcefdc21 | |||
| 8e15ff7f37 | |||
| 74c2841b8d | |||
| 424f83c5c6 | |||
| 711d13b71b | |||
| 938eaf69fc | |||
| 80629fc6d9 | |||
| b7538bd21d | |||
| 37edc9a8fe | |||
| a825cac557 | |||
| 73bfa9d22f | |||
| b55e59dceb | |||
| 95d67d633f | |||
| e9561e2c9d | |||
| 470ca6b2f0 | |||
| c5a28c2cce | |||
| 9f6e4ed73a | |||
| dfa2046cb4 | |||
| fc5f2f88f5 | |||
| 2215d9c193 | |||
| bbf4636fcc | |||
| 0e587d75df | |||
| 55f17b3368 | |||
| 5d3a43ba2e | |||
| 47a281a4ee | |||
| 80a8e214b1 | |||
| a4b63e436e | |||
| 6e31e0a833 | |||
| 5e3b66232b | |||
| 44cf712dc8 | |||
| 1be6ae8187 | |||
| 7b1ee20c7c | |||
| cd9c0fe4a6 | |||
| b40893bc70 | |||
| 9bfb2fe173 | |||
| b0afcfab57 | |||
| 5e773f8460 | |||
| a1c5e8a16b | |||
| 8b5569519c | |||
| 07b08c6a57 | |||
| b99906495e | |||
| 9659f70efd | |||
| 72d04227f9 | |||
| dfb7ae294c | |||
| 60c949b732 | |||
| a7da17c9b6 | |||
| d8331d5c34 | |||
| 7e65d070b8 | |||
| 018c7d95c3 | |||
| 4171a1ecbe | |||
| 5de7e0fc9c | |||
| 5a681948be | |||
| 2ffeb5b4c0 | |||
| e5d1d0dd7f | |||
| b0c1d245c2 | |||
| f454afd2c5 | |||
| fa014b1e13 | |||
| 9b88254f54 | |||
| add0e1ccc4 | |||
| 9bad381dae | |||
| 2cab114cc3 | |||
| d36953dbd8 | |||
| 8c434ebf7a | |||
| d8eebeddc8 | |||
| e7d0440dc5 | |||
| 0a6200341b | |||
| d9f9e25ec0 | |||
| 90a18258cd | |||
| 93fde45870 | |||
| 53b6ffdff1 | |||
| 37d31b9ab1 | |||
| 482932a5d0 | |||
| c96d92a3ff | |||
| bf9fd520c1 | |||
| 43b04895c7 | |||
| 5537dbebe6 | |||
| a0e2ac08c1 | |||
| 12170796d3 | |||
| 53438fd75d | |||
| eba75e9fa7 | |||
| d2401599a7 | |||
| f397cf75a0 | |||
| 8241b047a3 | |||
| 869aa03733 | |||
| 82cd7cbd8e | |||
| 1f99088145 | |||
| 6628d33987 | |||
| 5280ef2800 | |||
| ac09b29872 | |||
| 70d816c830 | |||
| 1a1ee613af | |||
| 23dd9956ea | |||
| 63c37c54c9 | |||
| d4cd4ffeac | |||
| 82f1a208bf | |||
| 4b2ebc95a5 | |||
| ef4f088311 | |||
| 406ef2b34a | |||
| cb3bc8b3e1 | |||
| 9f8b413d51 | |||
| 7f155e933d | |||
| c106c8e5f9 | |||
| 4474d42d38 | |||
| f2437dfe10 | |||
| e5921c7ef1 | |||
| 04869eba24 | |||
| 7ef4ff95b0 | |||
| a670bcee7b | |||
| 413aa2f638 | |||
| d4ae61a685 | |||
| d1ef542114 | |||
| c80ba075ab | |||
| 17960e9bf3 | |||
| 99dc0cf0da | |||
| 7d99d49ffb | |||
| c40c2d5ffa | |||
| fe1a0f03ca | |||
| df2b010fee | |||
| 0ccbfa4a3b | |||
| 7122e69785 |
@@ -19,6 +19,8 @@
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/*
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!docs/
|
||||
!docs/*.md
|
||||
!principles/
|
||||
|
||||
@@ -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
|
||||
- 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
|
||||
- vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
|
||||
- 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 rounds 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
|
||||
- loop-claude: the rebuild keeps main's `--reloaded` state
|
||||
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
|
||||
+9
-10
@@ -2,15 +2,14 @@
|
||||
|
||||
## 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, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog.
|
||||
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
|
||||
- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
|
||||
- `loop-claude`'s exit-2 message says what the human is needed for.
|
||||
- `loop-claude` counts an interrupt reply starting with `<` as typed.
|
||||
- `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed.
|
||||
- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `<sha256>.verdict.md`; a transcript it cannot archive exits 1.
|
||||
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
|
||||
|
||||
@@ -8,14 +8,15 @@ 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.
|
||||
- **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 pass may take per chunk.
|
||||
- **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.
|
||||
- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them.
|
||||
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
|
||||
|
||||
## Prose
|
||||
|
||||
@@ -46,7 +47,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
|
||||
|
||||
@@ -110,7 +112,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 +137,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)
|
||||
|
||||
@@ -5,7 +5,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins
|
||||
## Goals
|
||||
|
||||
1. Share this configuration between my computers.
|
||||
2. Keep it backed up.
|
||||
2. Keep it, and the transcripts of unattended runs, backed up.
|
||||
3. Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
4. Run work chunks unattended, interrupting me only when a decision is mine.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: "product-owner-reviewer"
|
||||
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?) and update README if personas are unclear.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
|
||||
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
|
||||
---
|
||||
|
||||
You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss.
|
||||
@@ -18,14 +18,11 @@ You consider internal logic **only** when it directly affects an external surfac
|
||||
|
||||
## Your Review Method
|
||||
|
||||
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. Flag violations as concerns like any other finding.
|
||||
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
|
||||
|
||||
1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns.
|
||||
|
||||
2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas, and `docs/decisions.md` for accepted product trade-offs to honor rather than re-raise. If personas are missing or unclear for the affected surface:
|
||||
- **Ask the user** which personas this is intended for (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user").
|
||||
- Once confirmed, **update the README** to record these personas for future reference. Keep the addition concise and place it in a logical section (e.g., "Personas" or "Audience").
|
||||
- If no user is reachable to answer, fall back to your best-guess personas, label them clearly as assumptions, and put the persona question under "Open questions for the user".
|
||||
2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas. If personas are missing or unclear for the affected surface, review against your best-guess personas (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"), labelled as assumptions, and raise the persona question as a ❓.
|
||||
|
||||
3. **Walk the happy path** for each persona. Is it obvious? Discoverable? Does the naming match mental models? Is the minimum required input actually minimum?
|
||||
|
||||
@@ -48,32 +45,19 @@ 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/skills/larv-review/review-findings.md. After the verdict:
|
||||
|
||||
**Surface affected**: <one line>
|
||||
|
||||
**Personas considered**: <list, or note if you had to ask>
|
||||
**Personas considered**: <list, assumptions labelled>
|
||||
|
||||
**Strengths**: <short bullets — what works well for customers>
|
||||
|
||||
**Concerns** (ordered by customer impact, highest first):
|
||||
- 🔴 **Blocker** — would confuse or block a real customer
|
||||
- 🟡 **Friction** — works but rough edges
|
||||
- 🟢 **Nit** — minor polish
|
||||
|
||||
For each concern: state the problem from the customer's POV, the persona affected, and a concrete suggestion.
|
||||
|
||||
**❓ Open questions for the user**: <only if you need clarification to complete the review>
|
||||
**Findings**, most severe first and by customer impact within a severity: for each, the problem from the customer's POV, the persona affected, and a concrete suggestion.
|
||||
|
||||
## Operating Principles
|
||||
|
||||
- Be specific. "The error message is unclear" is useless; "When the customer hits POST /x with a missing `email`, the response says 'validation failed' with no field name — they won't know what to fix" is useful.
|
||||
- Be honest about severity. Don't pad with nits if the change is solid.
|
||||
- Don't review code style, internal naming, or test coverage — that's for other reviewers.
|
||||
- If you don't have enough context (e.g., you can't tell what surface changed), ask before guessing.
|
||||
- When updating the README with persona info, keep it short and information-dense. Sort persona lists alphabetically.
|
||||
- Write in English.
|
||||
|
||||
## 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.
|
||||
- If you don't have enough context (e.g., you can't tell what surface changed), raise it as a ❓.
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# Review protocol
|
||||
|
||||
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
|
||||
|
||||
## Verdict
|
||||
|
||||
A review's first line, derived mechanically from the findings:
|
||||
|
||||
- `BLOCK` — a 🔴 stands; for a looping reviewer, a 🟡 too.
|
||||
- `ALIGN` — systems-architect only: no 🔴, drift (🟡) to address soon.
|
||||
- `APPROVE WITH NITS` — only 🟢 and ❓ remain; the author's call.
|
||||
- `APPROVE` — nothing remains.
|
||||
|
||||
## Severity
|
||||
|
||||
- 🔴 **must fix.** Never declinable: it is fixed, or shown factually wrong.
|
||||
- 🟡 **should fix.** Holds a looping reviewer at `BLOCK`, but may be declined.
|
||||
- 🟢 **nit.** Never holds the loop.
|
||||
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
|
||||
- 🔀 **escalation**: names the reviewer to run next (`product-owner-reviewer`, `systems-architect`, or the `security-review` skill) and a one-line reason. The caller runs it; it is never optional.
|
||||
|
||||
## Rounds
|
||||
|
||||
- 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`.
|
||||
|
||||
## 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.
|
||||
|
||||
A reviewer honours an accepted risk in `docs/decisions.md` and a finding declined this way: it stays declined and is not raised again.
|
||||
|
||||
## Documenting decisions
|
||||
|
||||
Knowledge that outlives one review goes in the repo, never in a memory file, where `~/.claude/CLAUDE.md` → "Comments and documentation" and "Ask, don't guess" put its kind. Record only decisions the human made, declines made under Declining, and answers the human gives to ❓; an unrecorded answer gets asked again next review.
|
||||
@@ -33,13 +33,14 @@ For every piece of code you review, systematically evaluate these categories. Fo
|
||||
|
||||
### 2. Scope & Growth Control
|
||||
Before judging how well code works, judge whether it should exist. Every line is permanent surface: it will be read, tested, upgraded, audited, and worked around for years.
|
||||
- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *additions* block; unasked *deletions* (opportunistic cleanup that removes code) are welcome.
|
||||
- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *deletions* (opportunistic cleanup that removes code) are welcome.
|
||||
- Could materially less code solve the ticket? The smallest sufficient diff is the benchmark; every line beyond it needs a reason.
|
||||
- Reuse before adding: does the codebase already provide this (helper, DTO, validator, a test to extend)? Grep for prior art before accepting a reimplementation.
|
||||
- Speculative generality: an interface with one implementation, a wrapper that only forwards, config with a single used value, generalization before a second use case exists. Demand the concrete second consumer — or removal.
|
||||
- New dependencies: would ~20 lines of own code do? Each one is permanent upgrade, audit, and supply-chain surface; check its maintenance state before accepting it.
|
||||
- Dead on arrival: unreferenced code, exports, params, or flags; feature flags with no removal plan.
|
||||
- Does the PR delete what it obsoletes (old path, old flag, old docs), or only add on top?
|
||||
- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡.
|
||||
|
||||
### 3. Ambiguity & Implicit State
|
||||
Catch behavior that is unclear or under-specified — "building in ambiguousness." Cross-check the principles: make invalid states unrepresentable, validate/build DTOs early, explicit state machines, explicit over implicit.
|
||||
@@ -94,7 +95,7 @@ Works-on-fixtures, dies-on-volume is a stability bug.
|
||||
- Algorithmic blowups (O(n²) and worse) on input whose size the user controls.
|
||||
|
||||
### 9. Security
|
||||
Every PR gets at least this sweep; for sensitive surfaces also recommend the dedicated pass (see Escalations).
|
||||
Every PR gets at least this sweep.
|
||||
- Injection: SQL via raw/concatenated queries, shell/command, XSS via unescaped output.
|
||||
- Does every new read and write path authorize access? (principle: grant explicit access to data — every read and write is explicitly authorized.)
|
||||
- Secrets: none hardcoded; none leaked into logs, error responses, or stack traces; PII sanitized before logging.
|
||||
@@ -111,7 +112,7 @@ Every PR gets at least this sweep; for sensitive surfaces also recommend the ded
|
||||
- **Judge every comment and prose line the diff adds against `~/.claude/CLAUDE.md` → "Comments and documentation"**; report a density breach with the ratio and the files driving it.
|
||||
- **Flag a caveat the diff has outlived**, anywhere in the repo: report the sentence's `file:line` and the behaviour that replaced it.
|
||||
- **Flag a pointer standing where a definition belongs** — `~/.claude/CLAUDE.md` → "Comments and documentation", "A pointer is not a definition".
|
||||
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a Stability Warning only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
|
||||
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a 🟡 only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
|
||||
- **Never let documentation stand in for a fix.** A finding is not closed by describing the defect in a README, and neither is one of yours: if the only available remedy is telling the reader, say so and mark it a decision for the human, so it lands in the PR or ticket where a decision record belongs. Naming a residual risk is your job; choosing to publish it in the repo is not yours to hand out.
|
||||
|
||||
### 11. Tests
|
||||
@@ -127,49 +128,20 @@ 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:
|
||||
|
||||
### 🔴 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.
|
||||
|
||||
### 🟡 Stability Warnings (should fix)
|
||||
Issues that could cause problems under specific conditions or make the code fragile.
|
||||
|
||||
### 🟢 Suggestions (nice to have)
|
||||
Improvements for clarity, maintainability, or defensive coding that reduce future bug risk.
|
||||
|
||||
### ❓ Questions (author input needed)
|
||||
|
||||
### 📋 Technical Principles Compliance
|
||||
Explicitly list any violations of the shared principles in `~/.claude/principles/`.
|
||||
|
||||
### 🔀 Escalations
|
||||
You are the per-PR reviewer — and therefore the dispatcher for the other reviewers. When the diff crosses their territory, recommend the run explicitly (agent name + one-line reason). Omit this section when none applies.
|
||||
- **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs.
|
||||
- **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary).
|
||||
- **security-review** (skill, run by the caller) — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; recommend a dedicated pass beyond the per-PR sweep in #9.
|
||||
|
||||
For each finding:
|
||||
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.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 the findings, most severe first, each with:
|
||||
- **Location**: File and line/function
|
||||
- **Issue**: Clear description of the problem
|
||||
- **Risk**: What could go wrong in production
|
||||
- **Fix**: The smallest change that closes the issue — prefer delete > simplify > modify > add; code examples when helpful
|
||||
|
||||
## Loop Discipline
|
||||
|
||||
- Only two things justify 🔴: a concrete failure scenario, or growth whose deletion is the whole fix. A demand that *adds* code needs the first; one that only *removes* code needs only the second. Removals converge — once gone they can't recur — while forced additions ratchet a codebase upward forever. "Could be smaller" rewrites are 🟡, never 🔴.
|
||||
- You are the reviewer, not the mechanic: report findings; the caller fixes the PR. Your only writes are the documentation duties in the protocol.
|
||||
Raise a 🔀 where the diff fires another pass's trigger in the pass table, `~/.claude/skills/larv-review/SKILL.md` §3.
|
||||
|
||||
## Behavioral Guidelines
|
||||
|
||||
- Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so.
|
||||
- Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants.
|
||||
- **Scope to this change.** Focus on what the PR introduces or worsens. Surface a serious pre-existing issue in the blast radius as *context*, not as a blocker — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise.
|
||||
- **Scope to this change.** Focus on what the PR introduces or worsens. Mark a serious pre-existing issue in the blast radius as pre-existing. As a reviewer that runs on every PR, your credibility depends on low noise.
|
||||
- **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust.
|
||||
- Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is.
|
||||
- Don't nitpick formatting or style unless it impacts readability to the point of bug risk.
|
||||
- Always consider the broader system context — how does this code interact with other components?
|
||||
|
||||
## 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.
|
||||
|
||||
+10
-34
@@ -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 drafts the missing goals and priorities and asks the user to confirm them 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.
|
||||
|
||||
@@ -31,18 +31,19 @@ You are an elite Systems Architect with decades of experience designing software
|
||||
- Methods, files, and modules that each hold a single responsibility — overgrown ones get split
|
||||
- Units that fit in a head — the thresholds of Fits in a head, crossed only with a stated reason
|
||||
|
||||
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a **blocking** finding, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later" (verdict mechanics in Reviewing Existing Work).
|
||||
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later".
|
||||
|
||||
**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, how hard a non-fundamental finding blocks. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity.
|
||||
**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, the severity of a non-fundamental finding. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity.
|
||||
|
||||
**You design for the recorded horizon, not just today's problem.** The current ticket is a forcing function, not the scope of your thinking — the Stage 0 horizon is. A recorded long-lived platform makes decade-thinking a duty; a recorded short-lived experiment makes decade-proofing a defect — speculative generality, not diligence. No recorded horizon: ask, never assume. Distrust "temporary" — prototypes that gain users become permanent, which is why the horizon carries a promotion event. Long-lived systems survive by staying cheap to change, not by carrying structure for guessed requirements.
|
||||
|
||||
## 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)
|
||||
|
||||
@@ -55,12 +56,11 @@ You work in distinct stages. Never skip stages. Never collapse them. Goals, audi
|
||||
### Stage 0: Establish goals, audience, scale & domain language (do this first)
|
||||
You cannot judge whether an implementation is the best one without a yardstick. The yardstick is five artifacts: **the audience** (who this is for — concrete roles, not "users"), **the problem statement** (what hurts without this), **the goals and their priority order** (including which failure classes are intolerable — the correctness targets the test machinery is priced against), **the scale & horizon** (expected load and data volume in orders of magnitude, team and consumer count, and the intended lifetime — throwaway experiment / MVP / production / long-lived platform — with a promotion event, the one that graduates it and forces re-review), and **the domain glossary** — the ubiquitous language: each core domain concept, one name, one line of meaning. Every name in the design must come from it.
|
||||
|
||||
- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs; ask the user for whatever isn't written down.
|
||||
- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs. What isn't written down is a question for the user.
|
||||
- **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name?
|
||||
- **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead.
|
||||
- **Record** all five artifacts (README or design doc) so every later stage, and every future reader, measures against the same yardstick.
|
||||
|
||||
Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are solid do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies.
|
||||
Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded in the README do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies.
|
||||
|
||||
### Stage 1: Describe
|
||||
Produce an architectural description covering:
|
||||
@@ -98,19 +98,6 @@ Produce a concrete list of issues, each with a proposed revision. If the design
|
||||
|
||||
Iterate Stage 1 → Stage 2 until the design is solid.
|
||||
|
||||
### Stage 3 (when work concludes): Document
|
||||
When the architectural work for a project or subsystem is complete, **always update the README of the current project** with:
|
||||
- Who it is for (the audience) and the problem it solves — first, before any architecture
|
||||
- The prioritized goals and the scale & horizon, promotion event included
|
||||
- The domain glossary: each core concept, one name, one line of meaning — names in code must match it
|
||||
- The architecture overview (components, responsibilities, boundaries)
|
||||
- Data flow diagrams or descriptions
|
||||
- The file system hierarchy and what lives where
|
||||
- How a change ships: merge-gate check classes, deploy and rollback story, dependency policy (see Delivery)
|
||||
- Key architectural decisions and why they were made
|
||||
|
||||
Write the README section in English, concise and information-dense. The reader should understand who the system serves, what problem it solves, what its words mean, and its shape from this alone. Depth follows the horizon: a paragraph for an experiment, the full section for a platform — but the README is always updated.
|
||||
|
||||
## The External Contract (your second priority, after goals)
|
||||
|
||||
The API to your consumers — HTTP/RPC, SDK or library surface, CLI, UI, emitted events, file formats — is what the outside world couples to. Breaking it is expensive precisely because the cost lands on people you don't control. Get it right early; internal structure can always be re-cut, a published contract cannot.
|
||||
@@ -162,11 +149,9 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
|
||||
|
||||
## Reviewing Existing Work (periodic alignment)
|
||||
|
||||
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).
|
||||
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 in the README.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.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. 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 — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
|
||||
|
||||
Focus on architectural alignment:
|
||||
- Does it still serve the project's goals and priorities, or has it quietly drifted from them?
|
||||
@@ -202,7 +187,7 @@ This is where unjustified duplication and accidental complexity get caught. Run
|
||||
6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
|
||||
7. **Hunt the imagined requirement.** The step above prices complexity a real requirement forces; this one removes complexity no requirement forces. For every abstraction, indirection, configuration point, and layer of generality, name the present, Stage 0-recorded requirement it serves. An interface with one implementation, a plugin system with one plugin, a cache or shard — or a load-testing rig — for load nobody recorded, a canary rig for a blast radius nobody recorded, "in case we swap the database" — speculative generality is the over-engineered twin of copy-paste drift: complexity nobody's requirement chose. The future that justifies flexibility must be a recorded goal or horizon, not the author's imagination — and the shorter the horizon, the harder this step cuts. Rate removals with the same severity as unreasoned duplication.
|
||||
|
||||
Respect documented deliberate deviations — a stated trade-off is a valid reason (see Documenting decisions). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
|
||||
Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
|
||||
|
||||
## Communication Style
|
||||
|
||||
@@ -211,12 +196,3 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso
|
||||
- Use diagrams (ASCII or described) when they clarify data flow or component relationships.
|
||||
- Avoid jargon unless it's the precise term. Prefer domain language over technical buzzwords.
|
||||
- Short, information-dense prose. No filler.
|
||||
|
||||
## Documenting decisions
|
||||
|
||||
Per ~/.claude/agents/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
|
||||
- Recurring complexity hotspots that need future restructuring
|
||||
- **Deliberate deviations from the architectural defaults, with the reason** — the "stated reasons" your Reasonability Review honours; an undocumented deviation is indistinguishable from an accident.
|
||||
|
||||
+5
-433
@@ -1,439 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Claude Code internals this rests on, observed on 2.1.282:
|
||||
- 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
|
||||
with promptSource "sdk"; typed() tells a human's from them.
|
||||
- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content
|
||||
parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event.
|
||||
- `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.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import pathlib
|
||||
import sys
|
||||
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_FLAG = "--reloaded"
|
||||
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
LAUNCHER = pathlib.Path(__file__).resolve()
|
||||
sys.path.insert(0, str(LAUNCHER.parent))
|
||||
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. ask=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"
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
|
||||
"ready to cut, a choice outside the repo\n"
|
||||
"- 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 "
|
||||
"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"
|
||||
"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."
|
||||
)
|
||||
from loop_claude import main, paths
|
||||
|
||||
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"},
|
||||
"finished": {"type": "boolean"},
|
||||
"question": {"description": "The single question to put to the human. Empty when ask is false.", "type": "string"},
|
||||
},
|
||||
"required": ["ask", "evidence", "finished", "question"],
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
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"]
|
||||
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)
|
||||
|
||||
|
||||
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))):
|
||||
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)))
|
||||
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 found.stdout.strip()
|
||||
|
||||
|
||||
def read_premises(root):
|
||||
try:
|
||||
found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read())
|
||||
except OSError as failure:
|
||||
sys.exit(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.")
|
||||
for name in ("Goals", "Audience"):
|
||||
bodies = found.get(name, [])
|
||||
if not bodies:
|
||||
sys.exit(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.")
|
||||
if not bodies[0]:
|
||||
sys.exit(f"README.md has nothing under ## {name} - no premises.")
|
||||
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
|
||||
|
||||
|
||||
def sections(text):
|
||||
found, current, fenced = {}, None, False
|
||||
for line in text.splitlines():
|
||||
fenced ^= line.startswith("```")
|
||||
if not fenced and line.startswith("## "):
|
||||
current = []
|
||||
found.setdefault(line.strip()[3:], []).append(current)
|
||||
elif not fenced and line.startswith("# "):
|
||||
current = None
|
||||
elif current is not None and line.strip():
|
||||
current.append(line)
|
||||
return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()}
|
||||
|
||||
|
||||
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"
|
||||
|
||||
|
||||
def archive(root, path, note):
|
||||
folder = os.path.join(ARCHIVE, project(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")
|
||||
print(f"transcript: {dest}", file=sys.stderr)
|
||||
except OSError as failure:
|
||||
print(f"could not archive the transcript: {failure}", file=sys.stderr)
|
||||
|
||||
|
||||
def make_private(folder):
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
finally:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def model(variable):
|
||||
return ["--model", os.environ[variable]] if os.environ.get(variable) else []
|
||||
|
||||
|
||||
def project(root):
|
||||
return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/")
|
||||
|
||||
|
||||
# The transcript file
|
||||
|
||||
|
||||
def session_open(session_id):
|
||||
return bool(session_file(session_id))
|
||||
|
||||
|
||||
def session_file(session_id):
|
||||
hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl"))
|
||||
return hit[0] if hit else ""
|
||||
|
||||
|
||||
def delete_transcript_files(path):
|
||||
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
|
||||
try:
|
||||
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
|
||||
except OSError as failure:
|
||||
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
|
||||
|
||||
|
||||
def entries(path):
|
||||
for raw in open(path, encoding="utf-8"):
|
||||
if entry := parse(raw):
|
||||
yield entry
|
||||
|
||||
|
||||
def parse(raw):
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
# "user" entries
|
||||
|
||||
|
||||
def human_turns(entries):
|
||||
return sum(1 for entry in entries if typed(entry))
|
||||
|
||||
|
||||
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":
|
||||
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)
|
||||
|
||||
|
||||
# "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()
|
||||
if code < 0:
|
||||
return f"claude killed by signal {-code}"
|
||||
if code:
|
||||
return f"claude exited {code}"
|
||||
return "" if done else "claude exited 0 without a result event"
|
||||
|
||||
|
||||
def worker_args(task, name, session_id, resuming):
|
||||
if resuming:
|
||||
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
|
||||
else:
|
||||
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)]
|
||||
return [
|
||||
*start,
|
||||
"--output-format", "stream-json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--verbose",
|
||||
*model("LOOP_CLAUDE_WORKER_MODEL"),
|
||||
]
|
||||
|
||||
|
||||
def render(entries):
|
||||
lines = []
|
||||
for entry in entries:
|
||||
if entry.get("type") == "assistant":
|
||||
lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))]
|
||||
elif typed(entry):
|
||||
content = entry["message"]["content"]
|
||||
lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content)))
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def said(part, limit=400):
|
||||
kind = part.get("type") if isinstance(part, dict) else None
|
||||
if kind == "text" and part.get("text", "").strip():
|
||||
return part["text"]
|
||||
if kind == "tool_use":
|
||||
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
|
||||
return ""
|
||||
|
||||
|
||||
# --json-schema verdicts
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript):
|
||||
args = [
|
||||
"-p",
|
||||
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
||||
*model("LOOP_CLAUDE_JUDGE_MODEL"),
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
for attempt in range(3):
|
||||
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']}"
|
||||
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)
|
||||
|
||||
|
||||
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.
|
||||
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}"
|
||||
)
|
||||
|
||||
|
||||
def complete(verdict):
|
||||
return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys()
|
||||
|
||||
|
||||
def grounded(verdict, transcript):
|
||||
if not verdict["ask"]:
|
||||
return True
|
||||
evidence = verdict["evidence"]
|
||||
return evidence.strip() != "" and evidence in transcript
|
||||
|
||||
|
||||
# ~/.claude.json
|
||||
|
||||
|
||||
def interrupt(root, session_id, 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)
|
||||
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
|
||||
|
||||
|
||||
def checkouts(root):
|
||||
found = [root]
|
||||
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
|
||||
if listing.returncode == 0:
|
||||
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def trust(paths):
|
||||
config = os.path.expanduser("~/.claude.json")
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
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:
|
||||
return
|
||||
for path in granted:
|
||||
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:
|
||||
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd()))
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import hashlib
|
||||
import sys
|
||||
|
||||
from loop_claude.file_writes import make_private, replace_file
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def archive(project, path, note, paths):
|
||||
folder = paths.archive / project
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
raw = handle.read()
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}")
|
||||
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
|
||||
# The copy lands last, so a copy on disk always has its verdict beside it.
|
||||
if not copy.exists():
|
||||
for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)):
|
||||
if failure := replace_file(dest, data):
|
||||
return Failure(f"could not archive the transcript: {dest}: {failure.reason}")
|
||||
print(f"transcript: {copy}", file=sys.stderr)
|
||||
return None
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it."""
|
||||
import enum
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
class UserEntryKind(enum.Enum):
|
||||
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind."""
|
||||
|
||||
COMMAND = enum.auto()
|
||||
CTRL_C = enum.auto()
|
||||
EMPTY = enum.auto()
|
||||
HUMAN = enum.auto()
|
||||
META = enum.auto()
|
||||
NON_TEXT = enum.auto()
|
||||
SDK_PROMPT = enum.auto()
|
||||
|
||||
|
||||
def locations(home):
|
||||
return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects"
|
||||
|
||||
|
||||
# <projects>/-home-me-code-log/<session id>.jsonl
|
||||
def transcript_path(projects, session_id):
|
||||
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
|
||||
return hit[0] if hit else ""
|
||||
|
||||
|
||||
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
|
||||
def session_files(transcript):
|
||||
return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")
|
||||
|
||||
|
||||
def parse(raw):
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
def content(entry):
|
||||
message = entry.get("message")
|
||||
return message.get("content") if isinstance(message, dict) else None
|
||||
|
||||
|
||||
def parts(entry):
|
||||
found = content(entry)
|
||||
return found if isinstance(found, list) else []
|
||||
|
||||
|
||||
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
|
||||
def assistant_parts(entry):
|
||||
return parts(entry) if entry.get("type") == "assistant" else []
|
||||
|
||||
|
||||
def user_entry_kind(entry):
|
||||
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
|
||||
if entry.get("isMeta"):
|
||||
return UserEntryKind.META
|
||||
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
|
||||
if entry.get("promptSource") == "sdk":
|
||||
return UserEntryKind.SDK_PROMPT
|
||||
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
|
||||
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
|
||||
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
||||
if isinstance(text := content(entry), str):
|
||||
source = entry.get("promptSource")
|
||||
return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN
|
||||
texts = [part_text(part) for part in parts(entry)]
|
||||
if not texts:
|
||||
return UserEntryKind.EMPTY
|
||||
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
|
||||
if None in texts:
|
||||
return UserEntryKind.NON_TEXT
|
||||
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
|
||||
if any(text.startswith("[Request interrupted") for text in texts):
|
||||
return UserEntryKind.CTRL_C
|
||||
return UserEntryKind.HUMAN
|
||||
|
||||
|
||||
def human_text(entry):
|
||||
"""What the human wrote in the entry, or None where Claude Code wrote it."""
|
||||
if (queued := queued_human_text(entry)) is not None:
|
||||
return queued
|
||||
if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN:
|
||||
return None
|
||||
text = content(entry)
|
||||
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
|
||||
|
||||
|
||||
# What the human types while claude works, written only as this entry:
|
||||
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
|
||||
def queued_human_text(entry):
|
||||
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
|
||||
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
|
||||
return None
|
||||
return prompt if isinstance(prompt := attachment.get("prompt"), str) else None
|
||||
|
||||
|
||||
# {"type": "text", "text": "ok"}
|
||||
def part_text(part):
|
||||
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
|
||||
|
||||
|
||||
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
|
||||
def tool_call(part):
|
||||
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
|
||||
|
||||
|
||||
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
||||
def ends_stream(event):
|
||||
return event.get("type") == "result"
|
||||
|
||||
|
||||
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
||||
def structured_output(stdout):
|
||||
return (parse(stdout) or {}).get("structured_output")
|
||||
|
||||
|
||||
# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
|
||||
def trust_records(config):
|
||||
projects = config.setdefault("projects", {}) if isinstance(config, dict) else None
|
||||
if not isinstance(projects, dict):
|
||||
return Failure('not an object whose "projects" is an object')
|
||||
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
|
||||
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
|
||||
return projects
|
||||
|
||||
|
||||
def mark_trusted(projects, roots):
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
for path in untrusted:
|
||||
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
|
||||
return untrusted
|
||||
|
||||
|
||||
# <model catalog>/*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
|
||||
def catalog(folder):
|
||||
newest = {}
|
||||
for path in folder.glob("*.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 []
|
||||
@@ -0,0 +1,39 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from loop_claude.claude_code.formats import session_files, transcript_path
|
||||
|
||||
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Session:
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
projects: pathlib.Path
|
||||
|
||||
|
||||
def session_for(project, paths):
|
||||
"""Exists while its transcript does."""
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
name = f"A {project} loop-claude"
|
||||
return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects)
|
||||
|
||||
|
||||
def transcript_file(session):
|
||||
return transcript_path(session.projects, session.id)
|
||||
|
||||
|
||||
def delete_session(session):
|
||||
path = transcript_file(session)
|
||||
if not path:
|
||||
return
|
||||
for sibling in session_files(path):
|
||||
try:
|
||||
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
|
||||
except OSError as failure:
|
||||
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
|
||||
@@ -0,0 +1,34 @@
|
||||
import json
|
||||
|
||||
from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
return [entry for raw in handle if (entry := parse(raw))]
|
||||
except OSError as failure:
|
||||
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
||||
|
||||
|
||||
def human_turns(entries):
|
||||
return sum(1 for entry in entries if human_text(entry) is not None)
|
||||
|
||||
|
||||
def render(entries):
|
||||
lines = []
|
||||
for entry in entries:
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
|
||||
if (text := human_text(entry)) is not None:
|
||||
lines.append("[human] " + text)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def part_line(part, limit=400):
|
||||
if (text := part_text(part)) and text.strip():
|
||||
return text
|
||||
if call := tool_call(part):
|
||||
name, arguments = call
|
||||
return f"[tool {name}] {json.dumps(arguments)[:limit]}"
|
||||
return ""
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude.claude_code.formats import mark_trusted, trust_records
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def trust(config, roots):
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError) as failure:
|
||||
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
|
||||
return
|
||||
projects = trust_records(data)
|
||||
if isinstance(projects, Failure):
|
||||
print(f"could not read {config}: {projects.reason}", file=sys.stderr)
|
||||
return
|
||||
untrusted = mark_trusted(projects, roots)
|
||||
if not untrusted:
|
||||
return
|
||||
if failure := replace_json(config, data, indent=2):
|
||||
print(f"could not write {config}: {failure.reason}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
@@ -0,0 +1,31 @@
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from loop_claude import human
|
||||
from loop_claude.claude_code.transcript import human_turns, read
|
||||
from loop_claude.claude_code.trust import trust
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.project.checkout import checkouts
|
||||
|
||||
TO = "answer the question above"
|
||||
|
||||
|
||||
def interrupt(root, session_id, model, path, question, paths):
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := human.off_terminal(TO):
|
||||
return stop
|
||||
trust(paths.claude_json, checkouts(root))
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
try:
|
||||
subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
if human_turns(entries) <= before:
|
||||
return human.needed(TO, "the interrupt ended with nothing typed")
|
||||
return None
|
||||
@@ -0,0 +1,104 @@
|
||||
import dataclasses
|
||||
import itertools
|
||||
import json
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.formats import structured_output
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.retry import stop_or_sleep_a_minute
|
||||
|
||||
JUDGE_RULES = (
|
||||
"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"
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
|
||||
"ready to cut, a choice outside the repo\n"
|
||||
"- 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"
|
||||
"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"
|
||||
"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."
|
||||
)
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Verdict:
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."})
|
||||
finished: bool
|
||||
interrupt: bool
|
||||
question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."})
|
||||
|
||||
|
||||
VERDICT_TYPES = typing.get_type_hints(Verdict)
|
||||
JSON_TYPES = {bool: "boolean", str: "string"}
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[VERDICT_TYPES[field.name]]} for field in dataclasses.fields(Verdict)},
|
||||
"required": list(VERDICT_TYPES),
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript, model):
|
||||
# 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", model,
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
for failures in itertools.count(1):
|
||||
verdict = run_judge(root, args, prompt)
|
||||
if isinstance(verdict, Failure):
|
||||
reason = verdict.reason
|
||||
elif not grounded(verdict, transcript):
|
||||
reason = f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")
|
||||
else:
|
||||
return verdict
|
||||
if stop := stop_or_sleep_a_minute("judge", failures, reason):
|
||||
return stop
|
||||
|
||||
|
||||
def run_judge(root, args, prompt):
|
||||
try:
|
||||
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
||||
return verdict_from(structured_output(proc.stdout))
|
||||
|
||||
|
||||
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 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}"
|
||||
)
|
||||
|
||||
|
||||
def verdict_from(output):
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no verdict")
|
||||
for name, kind in VERDICT_TYPES.items():
|
||||
if not isinstance(output.get(name), kind):
|
||||
return Failure(f"the judge's verdict has no {name} of type {JSON_TYPES[kind]}")
|
||||
if output["interrupt"] and not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Verdict(**{name: output[name] for name in VERDICT_TYPES})
|
||||
|
||||
|
||||
def grounded(verdict, transcript):
|
||||
return verdict.evidence.strip() != "" and verdict.evidence in transcript
|
||||
@@ -0,0 +1,40 @@
|
||||
import subprocess
|
||||
|
||||
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
|
||||
from loop_claude.claude_code.transcript import part_line
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def run_worker(root, args):
|
||||
try:
|
||||
proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
with proc:
|
||||
done = False
|
||||
for raw in proc.stdout:
|
||||
event = parse(raw) or {}
|
||||
done = done or ends_stream(event)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, 160):
|
||||
print(line, flush=True)
|
||||
code = proc.wait()
|
||||
if code < 0:
|
||||
return Failure(f"claude killed by signal {-code}")
|
||||
if code:
|
||||
return Failure(f"claude exited {code}")
|
||||
return None if done else Failure("claude exited 0 without a result event")
|
||||
|
||||
|
||||
def worker_args(task, session, model, resuming):
|
||||
if resuming:
|
||||
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
|
||||
else:
|
||||
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
|
||||
return [
|
||||
*start,
|
||||
"--output-format", "stream-json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--verbose",
|
||||
"--model", model,
|
||||
]
|
||||
@@ -0,0 +1,41 @@
|
||||
from loop_claude.archive import archive
|
||||
from loop_claude.claude_code.session import delete_session, session_for, transcript_file
|
||||
from loop_claude.claude_code.transcript import read, render
|
||||
from loop_claude.claude_runs.interrupt import interrupt
|
||||
from loop_claude.claude_runs.judge import judge
|
||||
from loop_claude.claude_runs.worker import run_worker, worker_args
|
||||
from loop_claude.outcome import Continue, Failure, Stop
|
||||
|
||||
|
||||
def run_cycle(root, project, task, premises, models, paths):
|
||||
session = session_for(project, paths)
|
||||
resuming = bool(transcript_file(session))
|
||||
if failure := run_worker(root, worker_args(task, session, models.worker, resuming)):
|
||||
return failure
|
||||
path = transcript_file(session)
|
||||
if not path:
|
||||
return Stop(1, f"claude left no transcript for session {session.id}")
|
||||
verdict = judge_through_interrupts(root, project, task, premises, models, session, path, paths)
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if verdict.finished:
|
||||
if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths):
|
||||
return Stop(1, failure.reason)
|
||||
delete_session(session)
|
||||
return Continue()
|
||||
|
||||
|
||||
def judge_through_interrupts(root, project, task, premises, models, session, path, paths):
|
||||
# The interrupt appends to this transcript, so each pass judges and archives it anew.
|
||||
while True:
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(root, task, premises, render(entries), models.judge)
|
||||
if isinstance(verdict, Stop) or not verdict.interrupt:
|
||||
return verdict
|
||||
if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict.question}", paths):
|
||||
return Stop(1, failure.reason)
|
||||
if stop := interrupt(root, session.id, models.worker, path, verdict.question, paths):
|
||||
return stop
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def make_private(folder):
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
finally:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def replace_json(path, data, **dump):
|
||||
return replace_file(path, json.dumps(data, **dump).encode())
|
||||
|
||||
|
||||
def replace_file(path, data):
|
||||
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), "wb") as handle:
|
||||
os.fchmod(handle.fileno(), mode)
|
||||
handle.write(data)
|
||||
os.replace(staged, path)
|
||||
except OSError as failure:
|
||||
if os.path.exists(staged):
|
||||
os.remove(staged)
|
||||
return Failure(failure.strerror)
|
||||
return None
|
||||
@@ -0,0 +1,13 @@
|
||||
import sys
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def needed(to, but):
|
||||
return Stop(2, f"the human is needed to {to}, but {but}")
|
||||
|
||||
|
||||
def off_terminal(to):
|
||||
if sys.stdin.isatty() and sys.stdout.isatty():
|
||||
return None
|
||||
return needed(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
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 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 an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
|
||||
leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a
|
||||
reload with unreadable state, or the worker or the judge fails three times running. A worker fails
|
||||
when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when
|
||||
claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a
|
||||
question, 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, the input ends, or the interrupt ended with nothing typed. 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. At every interrupt and when the chunk finishes
|
||||
its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS/<path>/<sha256>.jsonl (default
|
||||
~/.claude/loop-claude-transcripts), the verdict beside it in <sha256>.verdict.md.
|
||||
|
||||
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 bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds.
|
||||
"""
|
||||
import dataclasses
|
||||
import sys
|
||||
|
||||
from loop_claude.cycle import run_cycle
|
||||
from loop_claude.outcome import Continue, Failure, Stop
|
||||
from loop_claude.project.checkout import checkout_root, project_name
|
||||
from loop_claude.project.models import project_models
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint
|
||||
from loop_claude.retry import stop_or_sleep_a_minute
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LoopState:
|
||||
cycle_number: int
|
||||
failures: int
|
||||
root: str
|
||||
task: str
|
||||
|
||||
|
||||
def main(argv, env, paths, launcher, cwd):
|
||||
try:
|
||||
stop = run_loop(argv, env, paths, launcher, cwd)
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
if stop.reason:
|
||||
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
|
||||
return stop.code
|
||||
|
||||
|
||||
def run_loop(argv, env, paths, launcher, cwd):
|
||||
state = loop_state(argv, cwd)
|
||||
if isinstance(state, Stop):
|
||||
return state
|
||||
baseline = fingerprint(launcher)
|
||||
project = project_name(state.root, paths.code)
|
||||
while True:
|
||||
exec_if_edited(launcher, baseline, state)
|
||||
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
|
||||
premises = read_premises(state.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
models = project_models(project, paths, env)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||
match run_cycle(state.root, project, state.task, premises, models, paths):
|
||||
case Stop() as stop:
|
||||
return stop
|
||||
case Failure(reason):
|
||||
state = dataclasses.replace(state, failures=state.failures + 1)
|
||||
if stop := stop_or_sleep_a_minute("worker", state.failures, reason):
|
||||
return stop
|
||||
case Continue():
|
||||
state = dataclasses.replace(state, failures=0)
|
||||
|
||||
|
||||
def loop_state(argv, cwd):
|
||||
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(cwd)
|
||||
return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
|
||||
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
|
||||
if not (state and state.root and state.task):
|
||||
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||
return state
|
||||
@@ -0,0 +1,17 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Continue:
|
||||
pass
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Failure:
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
code: int
|
||||
reason: str
|
||||
@@ -0,0 +1,27 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
|
||||
from loop_claude.claude_code.formats import locations
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Paths:
|
||||
archive: pathlib.Path
|
||||
claude_json: pathlib.Path
|
||||
code: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
projects: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home, env):
|
||||
claude = home / ".claude"
|
||||
claude_json, model_catalog, projects = locations(home)
|
||||
return Paths(
|
||||
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
|
||||
claude_json=claude_json,
|
||||
code=home / "code",
|
||||
model_catalog=model_catalog,
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
projects=projects,
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
import subprocess
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def checkout_root(cwd):
|
||||
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
|
||||
if found.returncode != 0:
|
||||
return Stop(1, found.stderr.strip())
|
||||
return found.stdout.strip()
|
||||
|
||||
|
||||
def checkouts(root):
|
||||
found = [root]
|
||||
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
|
||||
if listing.returncode == 0:
|
||||
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def project_name(root, code):
|
||||
return root.removeprefix(f"{code}/").lstrip("/")
|
||||
@@ -0,0 +1,81 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude import human
|
||||
from loop_claude.claude_code.formats import catalog
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Models:
|
||||
judge: str
|
||||
worker: str
|
||||
|
||||
|
||||
def project_models(project, paths, env):
|
||||
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
|
||||
if judge and worker:
|
||||
return Models(judge, worker)
|
||||
chosen = project_model(project, paths)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
return Models(judge or chosen, worker or chosen)
|
||||
|
||||
|
||||
def project_model(name, paths):
|
||||
saved = paths.models_file
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if chosen := models.get(name):
|
||||
return chosen
|
||||
chosen = ask_model(name, saved, paths.model_catalog)
|
||||
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.reason}")
|
||||
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, folder):
|
||||
if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
|
||||
return stop
|
||||
offered = catalog(folder)
|
||||
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(f" no model catalog cached in {folder}", 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 human.needed(f"pick {name}'s model", "the input ended")
|
||||
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)
|
||||
@@ -0,0 +1,36 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def read_premises(root):
|
||||
try:
|
||||
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
|
||||
except OSError as failure:
|
||||
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
|
||||
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:
|
||||
return Stop(1, f"README.md has no ## {name} heading - no premises.")
|
||||
if len(bodies) > 1:
|
||||
return Stop(1, f"README.md has ## {name} more than once - no premises.")
|
||||
if not bodies[0]:
|
||||
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]}"
|
||||
|
||||
|
||||
def sections(text):
|
||||
found, current, fenced = {}, None, False
|
||||
for line in text.splitlines():
|
||||
fenced ^= line.startswith("```")
|
||||
if not fenced and line.startswith("## "):
|
||||
current = []
|
||||
found.setdefault(line.strip()[3:], []).append(current)
|
||||
elif not fenced and line.startswith("# "):
|
||||
current = None
|
||||
elif current is not None and line.strip():
|
||||
current.append(line)
|
||||
return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()}
|
||||
@@ -0,0 +1,42 @@
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
|
||||
|
||||
def decode_state(handed, kind):
|
||||
try:
|
||||
fields = json.loads(handed)
|
||||
except ValueError:
|
||||
return None
|
||||
shape = {field.name: field.type for field in dataclasses.fields(kind)}
|
||||
if not isinstance(fields, dict) or fields.keys() != shape.keys():
|
||||
return None
|
||||
if any(type(fields[name]) is not type_ for name, type_ in shape.items()):
|
||||
return None
|
||||
return kind(**fields)
|
||||
|
||||
|
||||
def fingerprint(launcher):
|
||||
digest = hashlib.sha256()
|
||||
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
|
||||
try:
|
||||
content = path.read_bytes()
|
||||
except OSError as failure:
|
||||
content = str(failure).encode()
|
||||
digest.update(f"{path.relative_to(launcher.parent)}\0{len(content)}\0".encode() + content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def exec_if_edited(launcher, baseline, state):
|
||||
if fingerprint(launcher) == baseline:
|
||||
return
|
||||
trial = subprocess.run([sys.executable, launcher, "--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, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
|
||||
@@ -0,0 +1,11 @@
|
||||
import sys
|
||||
import time
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def stop_or_sleep_a_minute(who, failures, reason):
|
||||
if failures == 3:
|
||||
return Stop(1, f"the {who} failed three times running: {reason}")
|
||||
print(f"retrying the {who} in a minute: {reason}", file=sys.stderr)
|
||||
time.sleep(60)
|
||||
+54
-326
@@ -1,25 +1,19 @@
|
||||
import contextlib
|
||||
import errno
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
|
||||
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude")))
|
||||
SPEC = importlib.util.spec_from_loader("loop_claude", LOADER)
|
||||
loop = importlib.util.module_from_spec(SPEC)
|
||||
LOADER.exec_module(loop)
|
||||
from loop_claude import file_writes, main
|
||||
from loop_claude.claude_code import formats, transcript
|
||||
from loop_claude.claude_runs import judge
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.project import premises
|
||||
|
||||
CWD = pathlib.Path("/c")
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -30,366 +24,100 @@ def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
def queued(prompt, kind):
|
||||
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
|
||||
|
||||
|
||||
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"
|
||||
self.assertEqual(loop.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
|
||||
|
||||
|
||||
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
|
||||
|
||||
def test_names_what_is_missing(self):
|
||||
texts = {
|
||||
"# T\n## Audience\nme\n": "no ## Goals heading",
|
||||
"# T\n## Goals\n\n## Audience\nme\n": "nothing under ## Goals",
|
||||
"# T\n## Goals\n1. g\n": "no ## Audience heading",
|
||||
"# T\n## Goals\n1. g\n## Audience\n": "nothing under ## Audience",
|
||||
"# T\n## Goals\n1. g\n## Audience\nme\n## Goals\n": "## Goals more than once",
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
readme = os.path.join(root, "README.md")
|
||||
self.assertIn(f"README.md in {root}: No such file or directory", self.exit_message(root))
|
||||
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")
|
||||
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)
|
||||
self.assertIn(missing, self.exit_message(root))
|
||||
open(readme, "w").write("# T\n## Goals\n1. g\n## Audience\nme\n")
|
||||
self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme")
|
||||
self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self):
|
||||
said = loop.render([
|
||||
said = transcript.render([
|
||||
human("do it"),
|
||||
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
||||
assistant({"type": "text", "text": " "}),
|
||||
human([{"type": "tool_result", "content": "not typed"}]),
|
||||
human("<command-name>/exit</command-name>"),
|
||||
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
|
||||
queued("B, while you work", "human"),
|
||||
queued("origin/main moved", "coordinator"),
|
||||
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
|
||||
])
|
||||
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it')
|
||||
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work')
|
||||
|
||||
|
||||
class HumanTurns(unittest.TestCase):
|
||||
def test_counts_typed_turns_and_not_tool_results(self):
|
||||
self.assertEqual(loop.human_turns([
|
||||
self.assertEqual(transcript.human_turns([
|
||||
human("typed"),
|
||||
human([{"type": "text", "text": "typed as a block"}]),
|
||||
human([{"type": "tool_result", "content": "not typed"}]),
|
||||
human("<command-name>/model</command-name>"),
|
||||
{**human("<3 merge it"), "promptSource": "typed"},
|
||||
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
|
||||
{**human("peer message"), "isMeta": True},
|
||||
{**human("the loop's own prompt"), "promptSource": "sdk"},
|
||||
human([{"type": "text", "text": "[Request interrupted by user]"}]),
|
||||
human([]),
|
||||
queued("typed while claude worked", "human"),
|
||||
queued("<task-notification>done</task-notification>", "task-notification"),
|
||||
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
|
||||
assistant({"type": "text", "text": "said"}),
|
||||
]), 2)
|
||||
]), 4)
|
||||
|
||||
|
||||
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)
|
||||
subprocess.run(["git", "init", "-q"], check=True)
|
||||
os.makedirs("a/b")
|
||||
with contextlib.chdir("a/b"):
|
||||
self.assertEqual(loop.checkout_root(), root)
|
||||
subprocess.run(["git", "init", "-q", "other"], check=True)
|
||||
with contextlib.chdir("other"):
|
||||
self.assertEqual(loop.checkouts(root), [root])
|
||||
|
||||
|
||||
class Project(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.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.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)
|
||||
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)
|
||||
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):
|
||||
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))
|
||||
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)
|
||||
self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1")
|
||||
|
||||
|
||||
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")
|
||||
self.assertIn("LATE", prompt)
|
||||
self.assertLess(prompt.count("early"), 20000)
|
||||
self.assertTrue(prompt.endswith(loop.JUDGE_RULES))
|
||||
|
||||
|
||||
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")
|
||||
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]
|
||||
self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600)
|
||||
folder = os.path.dirname(copy)
|
||||
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())
|
||||
|
||||
|
||||
class Said(unittest.TestCase):
|
||||
class PartLine(unittest.TestCase):
|
||||
def test_renders_text_and_tool_calls_and_nothing_else(self):
|
||||
self.assertEqual(loop.said({"type": "text", "text": "hi"}), "hi")
|
||||
self.assertEqual(loop.said({"type": "text", "text": " \n"}), "")
|
||||
self.assertEqual(loop.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
|
||||
self.assertEqual(loop.said("not a part"), "")
|
||||
|
||||
|
||||
class DeleteTranscriptFiles(unittest.TestCase):
|
||||
def test_deletes_the_transcript_and_its_siblings_so_the_session_is_gone(self):
|
||||
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
|
||||
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")
|
||||
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")
|
||||
self.assertTrue(loop.session_open(SESSION_ID))
|
||||
loop.delete_transcript_files(transcript)
|
||||
self.assertEqual(os.listdir(root), [])
|
||||
self.assertFalse(loop.session_open(SESSION_ID))
|
||||
|
||||
|
||||
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")
|
||||
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")
|
||||
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")
|
||||
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?"), "")
|
||||
|
||||
|
||||
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}):
|
||||
config = pathlib.Path(home, ".claude.json")
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
loop.trust(["/a"])
|
||||
self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n")
|
||||
config.write_text("{")
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
loop.trust(["/a"])
|
||||
self.assertIn(f"could not read {config}: ", err.getvalue())
|
||||
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
|
||||
config.write_text(json.dumps(data))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
loop.trust(["/a"])
|
||||
self.assertEqual(err.getvalue(), "")
|
||||
self.assertEqual(json.loads(config.read_text()), data)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
loop.trust(["/a", "/b"])
|
||||
self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n")
|
||||
data["projects"]["/b"] = {"hasTrustDialogAccepted": True}
|
||||
self.assertEqual(json.loads(config.read_text()), data)
|
||||
with (
|
||||
contextlib.redirect_stderr(io.StringIO()) as err,
|
||||
unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")),
|
||||
):
|
||||
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(transcript.part_line({"type": "text", "text": "hi"}), "hi")
|
||||
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}), "")
|
||||
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
|
||||
self.assertEqual(transcript.part_line("not a part"), "")
|
||||
|
||||
|
||||
class Parse(unittest.TestCase):
|
||||
def test_yields_only_json_objects(self):
|
||||
self.assertEqual(loop.parse('{"type": "user"}'), {"type": "user"})
|
||||
self.assertIsNone(loop.parse("not json"))
|
||||
self.assertIsNone(loop.parse("[1, 2]"))
|
||||
self.assertEqual(formats.parse('{"type": "user"}'), {"type": "user"})
|
||||
self.assertIsNone(formats.parse("not json"))
|
||||
self.assertIsNone(formats.parse("[1, 2]"))
|
||||
|
||||
|
||||
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"))
|
||||
def test_every_verdict_must_quote_the_transcript(self):
|
||||
def verdict(evidence):
|
||||
return judge.Verdict(evidence=evidence, finished=False, interrupt=False, question="")
|
||||
self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n"))
|
||||
self.assertFalse(judge.grounded(verdict("invented"), "the transcript"))
|
||||
self.assertFalse(judge.grounded(verdict(""), "the transcript"))
|
||||
self.assertFalse(judge.grounded(verdict(" "), "the 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.assertFalse(loop.complete(None))
|
||||
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "", "finished": True, "question": ""}), judge.Verdict(evidence="", finished=True, interrupt=False, question=""))
|
||||
self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's verdict has no interrupt of type boolean"))
|
||||
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's verdict has no evidence of type string"))
|
||||
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(judge.verdict_from(None), Failure("the judge returned no verdict"))
|
||||
|
||||
|
||||
STUB_CLAUDE = """#!/usr/bin/env python3
|
||||
import json, os, sys
|
||||
args = sys.argv[1:]
|
||||
open(os.environ["STUB_CALLS"], "a").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:]))
|
||||
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 ""}}))
|
||||
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")
|
||||
print(json.dumps({"type": "result"}))
|
||||
"""
|
||||
class LoopState(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(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
class RunWorker(unittest.TestCase):
|
||||
def test_says_whether_a_non_zero_exit_or_a_missing_result_event_failed_it(self):
|
||||
with tempfile.TemporaryDirectory() as bin:
|
||||
stub = os.path.join(bin, "claude")
|
||||
scripts = {
|
||||
"": 'print(json.dumps({"type": "result"}))',
|
||||
"claude exited 0 without a result event": 'print(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}))',
|
||||
"claude exited 3": "sys.exit(3)",
|
||||
"claude killed by signal 9": "os.kill(os.getpid(), 9)",
|
||||
}
|
||||
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")
|
||||
os.chmod(stub, 0o700)
|
||||
self.assertEqual(loop.run_worker(bin, []), failure)
|
||||
|
||||
|
||||
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)
|
||||
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")
|
||||
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)
|
||||
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 "))
|
||||
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.assertEqual(starts[1][2], SESSION_ID)
|
||||
self.assertEqual(sleep.call_count, 6)
|
||||
|
||||
|
||||
class Reload(unittest.TestCase):
|
||||
def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_state_as_one_json_argument(self):
|
||||
class ReplaceFile(unittest.TestCase):
|
||||
def test_removes_what_it_staged_when_the_replace_fails(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"))
|
||||
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)
|
||||
execv.assert_not_called()
|
||||
open(script, "w").write(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)
|
||||
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:
|
||||
loop.main()
|
||||
self.assertEqual(stopped.exception.code, 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")]
|
||||
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[0].assert_not_called()
|
||||
mocks[1].assert_called_once_with("/r")
|
||||
mocks[2].assert_called_once_with("/r", "do it", 3, 2)
|
||||
self.assertEqual(mocks[3].call_args.args[0], "/r")
|
||||
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"]))
|
||||
mocks[0].return_value = "/s"
|
||||
with self.assertRaises(SystemExit):
|
||||
loop.main()
|
||||
mocks[0].assert_called_once_with()
|
||||
mocks[1].assert_called_with("/s")
|
||||
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
|
||||
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.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")
|
||||
os.mkdir(os.path.join(root, "in-the-way"))
|
||||
self.assertEqual(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), Failure("Is a directory"))
|
||||
self.assertEqual(os.listdir(root), ["in-the-way"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import pty
|
||||
import select
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parent
|
||||
TASK = "Do the next chunk."
|
||||
|
||||
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
|
||||
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
|
||||
FAKE_CLAUDE = """#!{python}
|
||||
import json, os, pathlib, signal, sys, time
|
||||
|
||||
argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
log.write(json.dumps(call) + "\\n")
|
||||
if not steps or steps[0]["role"] != role:
|
||||
parent = os.getppid()
|
||||
os.kill(parent, signal.SIGINT)
|
||||
while os.getppid() == parent:
|
||||
time.sleep(0.05)
|
||||
sys.exit(0)
|
||||
step = steps.pop(0)
|
||||
scenario.write_text(json.dumps(steps))
|
||||
|
||||
|
||||
def session():
|
||||
flag = "--session-id" if "--session-id" in argv else "--resume"
|
||||
return argv[argv.index(flag) + 1]
|
||||
|
||||
|
||||
def transcript():
|
||||
return pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl"
|
||||
|
||||
|
||||
def append(*entries):
|
||||
transcript().parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(transcript(), "a") as handle:
|
||||
handle.writelines(json.dumps(entry) + "\\n" for entry in entries)
|
||||
|
||||
|
||||
if role == "worker":
|
||||
said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}}
|
||||
if step.get("transcript", True):
|
||||
append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}})
|
||||
with open(transcript(), "ab") as handle:
|
||||
handle.write(step.get("raw", "").encode("latin-1"))
|
||||
append(said)
|
||||
if step.get("siblings"):
|
||||
for sibling in (f"{{session()}}/subagents", f"{{session()}}.superseded-1/tool-results"):
|
||||
(transcript().parent / sibling).mkdir(parents=True, exist_ok=True)
|
||||
(transcript().parent / f"{{session()}}.orphaned-1-ab.jsonl").write_text("{{}}\\n")
|
||||
if "append" in step:
|
||||
edited = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"], step["append"][0])
|
||||
edited.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(edited, "a") as script:
|
||||
script.write(step["append"][1])
|
||||
if "replace" in step:
|
||||
script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"], step["replace"][0])
|
||||
script.write_text(script.read_text().replace(*step["replace"][1:]))
|
||||
sys.stdout.flush()
|
||||
sys.stdout.buffer.write(step.get("stream", "").encode("latin-1"))
|
||||
print(json.dumps(said))
|
||||
if step.get("result", True):
|
||||
print(json.dumps({{"type": "result"}}))
|
||||
if "signal" in step:
|
||||
os.kill(os.getpid(), step["signal"])
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
os.remove(__file__)
|
||||
sys.exit(step.get("exit", 0))
|
||||
"""
|
||||
|
||||
# Records every start of loop-claude and turns its retry waits into log lines.
|
||||
SITECUSTOMIZE = """import json, os, sys, time
|
||||
|
||||
if os.path.basename(sys.argv[0]) == "loop-claude":
|
||||
def record(event):
|
||||
with open(os.environ["LOOP_TEST_LOG"], "a") as log:
|
||||
log.write(json.dumps(event) + "\\n")
|
||||
record({"argv": sys.argv[1:]})
|
||||
pause = time.sleep
|
||||
time.sleep = lambda seconds: record({"sleep": seconds}) if seconds >= 1 else pause(seconds)
|
||||
"""
|
||||
|
||||
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
|
||||
|
||||
|
||||
def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", **step):
|
||||
verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
def interrupt(**step):
|
||||
return {"role": "interrupt", **step}
|
||||
|
||||
|
||||
def lines(path):
|
||||
return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Run:
|
||||
calls: list
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
stderr: str
|
||||
stdout: str
|
||||
|
||||
def roles(self):
|
||||
return [call["role"] for call in self.calls]
|
||||
|
||||
|
||||
class Checkout:
|
||||
"""A temporary HOME with a git checkout at ~/code/proj, where loop-claude runs against the fake claude."""
|
||||
|
||||
def __init__(self, test):
|
||||
self.test = test
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
test.addCleanup(temp.cleanup)
|
||||
self.temp = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.home = self.temp / "home"
|
||||
self.root = self.home / "code" / "proj"
|
||||
self.root.mkdir(parents=True)
|
||||
(self.root / "README.md").write_text(PREMISES)
|
||||
self.script = BIN / "loop-claude"
|
||||
self.env = {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))}
|
||||
fake = self.temp / "fake-bin"
|
||||
fake.mkdir()
|
||||
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
|
||||
(fake / "claude").chmod(0o755)
|
||||
(fake / "git").symlink_to(shutil.which("git"))
|
||||
site = self.temp / "site"
|
||||
site.mkdir()
|
||||
(site / "sitecustomize.py").write_text(SITECUSTOMIZE)
|
||||
self.env.update({
|
||||
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
|
||||
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
"HOME": str(self.home),
|
||||
"LOOP_CLAUDE_JUDGE_MODEL": "judge-model",
|
||||
"LOOP_CLAUDE_WORKER_MODEL": "worker-model",
|
||||
"LOOP_TEST_LOG": str(self.temp / "starts.jsonl"),
|
||||
"PATH": str(fake),
|
||||
"PYTHONPATH": str(site),
|
||||
})
|
||||
self.git("init", "--quiet")
|
||||
|
||||
def git(self, *args):
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env)
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
command = [sys.executable, str(self.script), *argv]
|
||||
cwd = cwd or self.root
|
||||
if terminal_input is None:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
return Run(
|
||||
calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])),
|
||||
code=code,
|
||||
sleeps=[event["sleep"] for event in started if "sleep" in event],
|
||||
starts=[event["argv"] for event in started if "argv" in event],
|
||||
stderr=stderr,
|
||||
stdout=stdout,
|
||||
)
|
||||
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing):
|
||||
"""Types the input at once, or once stderr shows before_typing's text and its callback has run."""
|
||||
controller, terminal = pty.openpty()
|
||||
with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout:
|
||||
try:
|
||||
proc = subprocess.Popen(command, cwd=cwd, env=self.env, stderr=stderr, stdin=terminal, stdout=terminal if stdout_on_terminal else stdout)
|
||||
finally:
|
||||
os.close(terminal)
|
||||
try:
|
||||
prompt, callback = before_typing or (None, None)
|
||||
if prompt is None:
|
||||
os.write(controller, typed.encode())
|
||||
output, deadline = b"", time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if select.select([controller], [], [], 1)[0]:
|
||||
try:
|
||||
chunk = os.read(controller, 4096)
|
||||
except OSError:
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
output += chunk
|
||||
if prompt is not None and prompt.encode() in os.pread(stderr.fileno(), 1 << 20, 0):
|
||||
callback()
|
||||
os.write(controller, typed.encode())
|
||||
prompt = None
|
||||
code = proc.wait(timeout=10)
|
||||
finally:
|
||||
os.close(controller)
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
stderr.seek(0)
|
||||
stdout.seek(0)
|
||||
output += stdout.read()
|
||||
return code, output.decode(errors="replace").replace("\r\n", "\n"), stderr.read().decode()
|
||||
|
||||
def claude_json(self):
|
||||
return self.home / ".claude.json"
|
||||
|
||||
def models_file(self):
|
||||
return self.home / ".claude" / "loop-claude-models.json"
|
||||
|
||||
def transcripts(self):
|
||||
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
|
||||
|
||||
def archive(self):
|
||||
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
|
||||
def archived(self):
|
||||
"""Each archived transcript's verdict, after checking the copy is named by its content hash."""
|
||||
verdicts = {}
|
||||
for folder in (self.archive(), self.archive() / "proj"):
|
||||
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
|
||||
for copy in sorted((self.archive() / "proj").glob("*.jsonl")):
|
||||
self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest())
|
||||
verdict = copy.with_suffix(".verdict.md")
|
||||
for archived in (copy, verdict):
|
||||
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
|
||||
verdicts[copy.read_text()] = verdict.read_text()
|
||||
return verdicts
|
||||
|
||||
|
||||
def argument(call, flag):
|
||||
return call["argv"][call["argv"].index(flag) + 1] if flag in call["argv"] else None
|
||||
|
||||
|
||||
class Premises(unittest.TestCase):
|
||||
def test_refuses_to_start_without_a_task_a_checkout_or_premises(self):
|
||||
checkout = Checkout(self)
|
||||
for argv, code, said in (([], 1, "usage: loop-claude <task>"), (["--help"], 0, "usage: loop-claude <task>"), (["-h"], 0, "usage: loop-claude <task>")):
|
||||
with self.subTest(argv=argv):
|
||||
run = checkout.run([], argv=argv)
|
||||
self.assertEqual(run.code, code)
|
||||
self.assertIn(said, run.stdout if code == 0 else run.stderr)
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
run = checkout.run([], cwd=outside)
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("not a git repository", run.stderr)
|
||||
readmes = {
|
||||
None: "README.md in {root}: No such file or directory - no premises.",
|
||||
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md is not UTF-8 on line 3 - no premises.",
|
||||
b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.",
|
||||
b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.",
|
||||
b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.",
|
||||
b"# P\n## Goals\n1. g\n## Audience\nme\n## Audience\nyou\n": "README.md has ## Audience more than once - no premises.",
|
||||
}
|
||||
(checkout.root / "sub").mkdir()
|
||||
for text, said in readmes.items():
|
||||
with self.subTest(said=said):
|
||||
readme = checkout.root / "README.md"
|
||||
readme.unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
readme.write_bytes(text)
|
||||
run = checkout.run([worker()], cwd=checkout.root / "sub")
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), said.format(root=checkout.root))
|
||||
(checkout.root / "README.md").unlink()
|
||||
(checkout.root / "README.md").mkdir()
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
|
||||
|
||||
def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self):
|
||||
checkout = Checkout(self)
|
||||
for root in (checkout.temp / "elsewhere", checkout.home / "code"):
|
||||
with self.subTest(root=root):
|
||||
root.mkdir(exist_ok=True)
|
||||
(root / "README.md").write_text(PREMISES)
|
||||
checkout.git("init", "--quiet", str(root))
|
||||
run = checkout.run([worker()], cwd=root)
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self):
|
||||
checkout = Checkout(self)
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([
|
||||
worker(say="started"), judge(evidence="started"),
|
||||
worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"),
|
||||
worker(say="next chunk"),
|
||||
], cwd=checkout.root / "sub")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
session = argument(workers[0], "--session-id")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude")
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertNotIn(TASK, argument(workers[1], "-p"))
|
||||
self.assertEqual({call["cwd"] for call in run.calls}, {str(checkout.root)})
|
||||
self.assertIn("1. Work.", run.calls[1]["stdin"])
|
||||
self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"})
|
||||
self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"})
|
||||
self.assertIn("landed-it", run.calls[3]["stdin"])
|
||||
self.assertNotIn("landed-it", run.calls[5]["stdin"])
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3 ===", run.stdout)
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertIn('"text": "landed-it"', copy)
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: finished\n")
|
||||
|
||||
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.archive().parent.mkdir(parents=True)
|
||||
checkout.archive().write_text("in the way")
|
||||
run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$")
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
checkout.archive().unlink()
|
||||
run = checkout.run([worker(), judge(finished=True)])
|
||||
self.assertEqual(argument(run.calls[0], "--resume"), session)
|
||||
self.assertEqual(len(checkout.archived()), 1)
|
||||
|
||||
def test_stops_after_three_failures_running_retrying_a_minute_apart(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(exit=1), worker(result=False), worker(signal=9)])
|
||||
self.assertEqual(run.code, 1)
|
||||
self.assertEqual(run.roles(), ["worker"] * 3)
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("retrying the worker in a minute: claude exited 1", run.stderr)
|
||||
self.assertIn("claude exited 0 without a result event", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude killed by signal 9")
|
||||
|
||||
run = checkout.run([worker(exit=1), worker(exit=1), worker(), judge(), worker(exit=1), worker(exit=1)])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.sleeps, [60, 60, 60, 60])
|
||||
|
||||
run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout="{}"), judge(verdict={"interrupt": False})])
|
||||
self.assertEqual(run.code, 1)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("retrying the judge in a minute: judge down", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string")
|
||||
|
||||
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([
|
||||
worker(say="Shall I use A or B?"),
|
||||
judge(interrupt=True, evidence="never said", question="A or B?"),
|
||||
judge(finished=True, evidence=""),
|
||||
judge(evidence="A or B"),
|
||||
worker(),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge", "worker", "judge"])
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge quoted '', nothing in the transcript\n", run.stderr)
|
||||
|
||||
def test_retries_a_judge_claude_cannot_start(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(vanish=True)])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory")
|
||||
|
||||
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="early " * 20000 + "LATE")])
|
||||
self.assertIn("LATE", run.calls[1]["stdin"])
|
||||
self.assertLess(run.calls[1]["stdin"].count("early"), 20000)
|
||||
self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("an open PR, a review not yet run, CI not yet reported."))
|
||||
|
||||
def test_skips_a_malformed_transcript_or_stream_line(self):
|
||||
checkout = Checkout(self)
|
||||
raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n"
|
||||
run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge(evidence="past the noise")])
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"]))
|
||||
self.assertIn("past the noise", run.stdout)
|
||||
self.assertIn("past the noise", run.calls[1]["stdin"])
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
|
||||
def test_exits_1_when_the_transcript_cannot_be_read(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(unreadable=True)])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not read the transcript .*\.jsonl: Permission denied$")
|
||||
|
||||
def test_retries_a_worker_claude_cannot_start(self):
|
||||
checkout = Checkout(self)
|
||||
(checkout.temp / "fake-bin" / "claude").unlink()
|
||||
run = checkout.run([])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: could not start claude: No such file or directory")
|
||||
|
||||
def test_exits_1_when_claude_leaves_no_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(transcript=False)])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertIn("claude left no transcript for session", run.stderr)
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(checkout.temp / "deep" / "archive")
|
||||
steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run(steps)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertEqual(argument(run.calls[0], "--resume"), session)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
run = checkout.run([worker(transcript=False), steps[1]])
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
checkout.git("worktree", "add", "--quiet", str(checkout.home / "code" / "proj-wt"))
|
||||
checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}}))
|
||||
checkout.claude_json().chmod(0o644)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
handed = run.calls[2]["argv"]
|
||||
self.assertEqual(run.calls[2]["cwd"], str(checkout.root))
|
||||
self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id"))
|
||||
self.assertEqual(argument(run.calls[2], "--model"), "worker-model")
|
||||
self.assertNotIn("-p", handed)
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
trusted = json.loads(checkout.claude_json().read_text())
|
||||
self.assertEqual(trusted["other"], 1)
|
||||
self.assertEqual(trusted["projects"][str(checkout.root)], {"hasTrustDialogAccepted": True, "kept": True})
|
||||
self.assertEqual(trusted["projects"][str(checkout.home / "code" / "proj-wt")], {"hasTrustDialogAccepted": True})
|
||||
self.assertEqual(stat.S_IMODE(checkout.claude_json().stat().st_mode), 0o644)
|
||||
self.assertIn(f"trusted for the interrupt: {checkout.root}, {checkout.home / 'code' / 'proj-wt'}\n", run.stderr)
|
||||
|
||||
for transcript in checkout.transcripts():
|
||||
transcript.unlink()
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="")
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed")
|
||||
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="")
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory")
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
root = json.dumps(str(checkout.root))
|
||||
shapes = {
|
||||
None: "No such file or directory",
|
||||
"{": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",
|
||||
"[]": 'not an object whose "projects" is an object',
|
||||
'{"projects": []}': 'not an object whose "projects" is an object',
|
||||
f'{{"projects": {{{root}: 1}}}}': f"projects[{root}] is not an object",
|
||||
}
|
||||
for text, said in shapes.items():
|
||||
with self.subTest(said=said):
|
||||
checkout.claude_json().unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
checkout.claude_json().write_text(text)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text)
|
||||
|
||||
trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}})
|
||||
checkout.claude_json().write_text(trusted)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
self.assertNotIn(str(checkout.claude_json()), run.stderr)
|
||||
self.assertNotIn("trusted for the interrupt", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), trusted)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_says_why_the_trust_file_cannot_be_written(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.claude_json().write_text("{}")
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
checkout.run(asked[:2])
|
||||
checkout.home.chmod(0o500)
|
||||
self.addCleanup(checkout.home.chmod, 0o700)
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), "{}")
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
|
||||
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="")
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$")
|
||||
|
||||
|
||||
class Models(unittest.TestCase):
|
||||
def catalog(self, checkout):
|
||||
folder = checkout.home / ".claude" / "cache" / "model-catalog"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "old.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "old-model"}]}}, "fetchedAt": 1}))
|
||||
(folder / "new.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "model-a", "name": "A"}, {"id": "model-b", "name": "B"}]}}, "fetchedAt": 2}))
|
||||
|
||||
def test_asks_a_project_without_a_model_on_the_terminal_and_saves_the_answer(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
self.catalog(checkout)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": "<model>"}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun loop-claude on a terminal')
|
||||
|
||||
run = checkout.run([worker()], terminal_input="\x04")
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended")
|
||||
|
||||
checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model"
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"]
|
||||
run = checkout.run([worker(), judge()], terminal_input="\n9\n2\n")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertIn("proj runs on model-b", run.stderr)
|
||||
self.assertIn("1. A (model-a)", run.stderr)
|
||||
self.assertNotIn("old-model", run.stderr)
|
||||
self.assertIn("pick 1 to 2", run.stderr)
|
||||
self.assertEqual({argument(call, "--model") for call in run.calls}, {"model-b"})
|
||||
self.assertEqual(json.loads(checkout.models_file().read_text()), {"proj": "model-b"})
|
||||
self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o600)
|
||||
|
||||
checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model"
|
||||
run = checkout.run([worker(), judge()])
|
||||
self.assertEqual([argument(call, "--model") for call in run.calls], ["model-b", "judge-model", "model-b"])
|
||||
|
||||
def test_keeps_the_models_file_mode_and_other_projects_when_saving(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
checkout.models_file().parent.mkdir(parents=True)
|
||||
checkout.models_file().write_text(json.dumps({"other": "model-x"}))
|
||||
checkout.models_file().chmod(0o640)
|
||||
def saved_elsewhere():
|
||||
checkout.models_file().write_text(json.dumps({"late": "model-y", "other": "model-x"}))
|
||||
|
||||
run = checkout.run([worker()], terminal_input="custom-model\n", before_typing=("no model catalog cached", saved_elsewhere))
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertIn("no model catalog cached", run.stderr)
|
||||
self.assertIn("A name claude --model takes: ", run.stderr)
|
||||
self.assertEqual(json.loads(checkout.models_file().read_text()), {"late": "model-y", "other": "model-x", "proj": "custom-model"})
|
||||
self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o640)
|
||||
|
||||
for broken in ("{", "[]", '{"proj": 1}'):
|
||||
with self.subTest(broken=broken):
|
||||
checkout.models_file().write_text(broken)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertTrue(run.stderr.startswith(f"could not read {checkout.models_file()}: "))
|
||||
self.assertEqual(checkout.models_file().read_text(), broken)
|
||||
|
||||
def test_offers_no_catalog_whose_models_are_not_a_list(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
self.catalog(checkout)
|
||||
catalog = checkout.home / ".claude" / "cache" / "model-catalog" / "new.json"
|
||||
for shape in ({"catalog": {"config": {"models": []}}}, {"catalog": None}, {"catalog": {"config": []}}, {"catalog": {"config": {"models": "x"}}}):
|
||||
with self.subTest(shape=shape):
|
||||
catalog.write_text(json.dumps({**shape, "fetchedAt": 3}))
|
||||
checkout.models_file().unlink(missing_ok=True)
|
||||
run = checkout.run([worker()], terminal_input="1\n")
|
||||
self.assertIn("no model catalog cached", run.stderr)
|
||||
self.assertEqual(argument(run.calls[0], "--model"), "1")
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_exits_1_when_the_models_file_cannot_be_written(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
checkout.models_file().parent.mkdir(parents=True, mode=0o500)
|
||||
self.addCleanup(checkout.models_file().parent.chmod, 0o700)
|
||||
run = checkout.run([worker()], terminal_input="custom-model\n")
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn(f"could not save the model in {checkout.models_file()}: Permission denied", run.stderr)
|
||||
|
||||
|
||||
class Reload(unittest.TestCase):
|
||||
def test_an_edit_takes_effect_at_the_next_cycle_boundary_once_it_answers_help(self):
|
||||
checkout = Checkout(self)
|
||||
copy = checkout.temp / "bin"
|
||||
shutil.copytree(BIN, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*"))
|
||||
checkout.script = copy / "loop-claude"
|
||||
checkout.env["FAKE_CLAUDE_EDIT"] = str(copy)
|
||||
run = checkout.run([
|
||||
worker(append=["loop-claude", "\ndef\n"]), judge(),
|
||||
worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(),
|
||||
worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(),
|
||||
worker(),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 4)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "failures": 0, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)])
|
||||
self.assertIn("=== cycle 4 ===", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK}
|
||||
run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside)
|
||||
self.assertEqual((run.code, run.sleeps), (1, []))
|
||||
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
|
||||
self.assertIn("=== cycle 4 ===", run.stdout)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1")
|
||||
|
||||
run = checkout.run([], argv=["--reloaded", "{}"])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("rerun loop-claude <task>", run.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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)
|
||||
+49
-9
@@ -10,32 +10,72 @@
|
||||
|
||||
## loop-claude: one session per project, at a fixed id
|
||||
|
||||
2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id the script's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it.
|
||||
2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it.
|
||||
|
||||
## loop-claude: the trust file is rewritten before an interrupt
|
||||
|
||||
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.
|
||||
|
||||
## 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 same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, and 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c; the places the last run named are filed 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.
|
||||
|
||||
## 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.
|
||||
|
||||
## 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. 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.
|
||||
|
||||
## 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` or `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**. The ⚠️ warning stands in `AGENTS.md`, atop `todo.md` and on its last item on purpose, 2026-09-28, lilleman: a premature merge lands under every session running on main, so a reader of any one of them must meet it. Valid until the rebuild merges.
|
||||
|
||||
## review: the round cap counts a pass's rounds per chunk
|
||||
|
||||
2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth 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 goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. 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.
|
||||
|
||||
## loop-claude: the rebuild keeps main's `--reloaded` state
|
||||
|
||||
2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; `decode_state` accepts only JSON whose keys and value types match `LoopState` exactly, so renaming, adding, dropping or retyping a field breaks that reload, and no code exists only for the cut-over. Valid until the rebuild merges.
|
||||
|
||||
## rebuild: a chunk into `rebuild` takes no comprehension scoring run
|
||||
|
||||
2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges.
|
||||
|
||||
## loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
|
||||
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 4. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"~/code"
|
||||
]
|
||||
},
|
||||
"model": "opus[1m]",
|
||||
"disableClaudeAiConnectors": true,
|
||||
"statusLine": {
|
||||
"type": "command",
|
||||
|
||||
@@ -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".
|
||||
|
||||
+49
-92
@@ -5,107 +5,74 @@ 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; reviewers only report. Run every reviewer synchronously (`run_in_background: false`) and watch CI in the foreground: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. The turn runs on until §6.
|
||||
|
||||
**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". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md.
|
||||
|
||||
## 0. Preconditions
|
||||
## 1. 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.
|
||||
- Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done.
|
||||
- **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 is reviewed like any chunk. Only what that section lets through without them reaches review.
|
||||
- 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.
|
||||
|
||||
## 1. Ship the branch (idempotent — skip whatever already exists)
|
||||
## 2. Ship the branch (idempotent — skip whatever already exists)
|
||||
|
||||
Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs".
|
||||
Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary.
|
||||
|
||||
- On the default branch → create the feature branch first; never commit to the default branch.
|
||||
- Commit the work; push with upstream set.
|
||||
- Open a **draft** PR so CI starts cycling while the review runs and churn stays visibly work-in-progress.
|
||||
- No remote → continue with the local review loop and say so in the summary.
|
||||
## 3. Passes
|
||||
|
||||
## 2. Trigger: is the architecture pass warranted?
|
||||
| Pass | Reviewer | Runs on a change it has not seen that… |
|
||||
|------|----------|----------------------------------------|
|
||||
| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines of code or ~5 modules |
|
||||
| Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto |
|
||||
| Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface |
|
||||
| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do |
|
||||
| Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on |
|
||||
| Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose |
|
||||
|
||||
It reviews the application as a whole — heavy by design, and its own description says it is not a per-PR reviewer. The signals below are proxies for one question: **does this change carry an architectural decision the pass has not already made?** Check the record before the signals.
|
||||
A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger once the current pass is done, and runs forward from there as a re-entry does.
|
||||
|
||||
**The record wins.** Where the repo already holds the decision this change executes — a decision-log entry, or a planning item crediting systems-architect — the pass is done: skip it, cite the record in the summary, don't ask. A change that *departs* from what the record says is unreviewed however thorough the record is.
|
||||
**Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it.
|
||||
|
||||
Otherwise, any one of these is grounds for the pass:
|
||||
**Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too.
|
||||
|
||||
- new or restructured component/module/service, or moved boundaries
|
||||
- new dependency, or first use of an infrastructure pattern (queue, cron, cache, websocket, …)
|
||||
- new or changed external contract: routes, request/response shapes, events, webhooks, published file formats
|
||||
- DB schema change beyond an additive column
|
||||
- diff > ~400 non-generated lines, or touching > ~5 modules
|
||||
- a previous stability round escalated to systems-architect
|
||||
**Round cap.** A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human. A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent. The external auto-reviewer (§4) is a pass of its own, each review it posts a round: after its third, ask the human before any push that would summon a fourth.
|
||||
|
||||
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.
|
||||
### Architecture
|
||||
|
||||
## 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.
|
||||
|
||||
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 in the README, re-run once. No user → skip the pass, carry the questions into the summary.
|
||||
- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR.
|
||||
|
||||
- **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`.
|
||||
- **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.
|
||||
Then the comprehension floor: 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.
|
||||
|
||||
### Comprehension floor (with every architecture pass)
|
||||
### Security
|
||||
|
||||
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.
|
||||
`/security-review` over the branch diff is the pass of record: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse.
|
||||
|
||||
## 4. Security pass (whenever the chunk changed anything but test code)
|
||||
A verified HIGH inside this chunk's blast radius is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which.
|
||||
|
||||
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.
|
||||
The full-scan plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass.
|
||||
|
||||
- **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.
|
||||
**Do not over-read a clean result.** `/security-review` is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852).
|
||||
|
||||
**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.
|
||||
### Stability and product-owner
|
||||
|
||||
**Do not over-read a clean result.** This pass is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852).
|
||||
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner 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. Commit and push each round so CI feedback accumulates.
|
||||
|
||||
## 5. Stability loop
|
||||
|
||||
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.
|
||||
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)
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
3. Commit and push each round; it exits and caps per the protocol.
|
||||
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)
|
||||
### Prose
|
||||
|
||||
Two scopes:
|
||||
|
||||
1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself; they are fresh in your hands.
|
||||
1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself.
|
||||
2. **What this review cited** — any section of the repo's prose a reviewer quoted to justify a finding, you quoted to justify a decline, or the implementer quoted to explain a decision. A cited section is load-bearing, and if anyone had to hunt for it, that is the finding. Judge these with a **fresh-context agent**, never yourself: whoever just wrote the code already knows the answer and cannot see what the prose adds. Hand it the section and the code that section governs, and nothing else.
|
||||
|
||||
In a chunk whose architecture pass ran, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk.
|
||||
|
||||
The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph the default verdict is delete.
|
||||
|
||||
- **Delete** — a type, a test name, a spec or the code already says it. In this chunk.
|
||||
@@ -113,31 +80,21 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph
|
||||
- **Move back** — the opposite fault, and the one a deletion-only pass never catches: a pointer standing where a definition belongs ("A pointer is not a definition", same section). Inline the definition and leave the reasoning where it is.
|
||||
- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search for it. Sub-headings, or an index at its head. Bigger than the chunk → a `todo.md` item naming the section and what the hunt costs.
|
||||
|
||||
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.
|
||||
## 4. Gate
|
||||
|
||||
## 9. Green gate, PR ready
|
||||
1. Run the project's test suite locally unless the last stability round already left it verified green.
|
||||
2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3.
|
||||
3. No CI configured → the gate is local tests only; note it in the summary.
|
||||
4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix.
|
||||
5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. 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, never waiting twice. Its findings follow the findings document like any reviewer's. Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit.
|
||||
|
||||
- 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.
|
||||
## 5. Goal alignment, then merge
|
||||
|
||||
## 10. External auto-reviewer (when the repo has one)
|
||||
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. Aligned, every pass done 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.
|
||||
3. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop".
|
||||
4. Stop. The next chunk gets a fresh session.
|
||||
|
||||
Marking the PR ready is what summons CodeRabbit and its kind, so this follows §9.
|
||||
## 6. Wrap up
|
||||
|
||||
- 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.
|
||||
|
||||
## 11. 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`.
|
||||
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
|
||||
|
||||
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.
|
||||
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, 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.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Review findings
|
||||
|
||||
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
|
||||
|
||||
A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again.
|
||||
|
||||
## Severity
|
||||
|
||||
- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined.
|
||||
- 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`.
|
||||
- 🟢 **nit** — never holds a pass.
|
||||
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
|
||||
- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it.
|
||||
|
||||
Other reviewers map onto this scale, and a finding of theirs repeating one declined or filed does not stand:
|
||||
|
||||
- `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢.
|
||||
- A forge's auto-reviewer: what it marks blocking is 🔴.
|
||||
|
||||
## Verdict
|
||||
|
||||
A review's first line, derived from the findings:
|
||||
|
||||
- `BLOCK` — a 🔴 or a 🟡 stands.
|
||||
- `APPROVE WITH NITS` — only 🟢 and ❓ remain.
|
||||
- `APPROVE` — nothing remains.
|
||||
|
||||
## Rounds
|
||||
|
||||
- Surface everything in round 1.
|
||||
- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem.
|
||||
- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one.
|
||||
|
||||
## Declining
|
||||
|
||||
A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix.
|
||||
@@ -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")
|
||||
|
||||
@@ -2,8 +2,22 @@
|
||||
|
||||
## 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. 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.
|
||||
The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
|
||||
|
||||
The places the panel on `rebuild` at 7f9de5c named (`docs/decisions.md`), capping dimension first:
|
||||
|
||||
- **Make `mark_trusted` return the updated `~/.claude.json`, so `trust` writes what it was handed and `formats.py` mutates nothing.** Three seats: `trust_records` `setdefault`s into the config and `trust` writes `data` changed through an alias.
|
||||
- **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload.
|
||||
- **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`.
|
||||
- **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts.
|
||||
- **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object.
|
||||
- **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`.
|
||||
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the last 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.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- **Reword `CLAUDE.md` → "One spelling per goal" so a copy in code is derived from its owner, and drop the README-caveat sentence and the scope list.** A prose pass found "reject at load" fits only copied config, and the scope list reads as excluding internal code.
|
||||
- **Back up `loop-claude`'s transcript archive to a destination other than this repo's remote.**
|
||||
- **Make the contributor a standing member of every project's audience, dropped only where `## Audience` says maintainability does not matter.** `CLAUDE.md`'s premises rule states it; larv-review's comprehension floor names the contributor as the reader it serves, so the floor gates every chunk while the contributor stands and a project that drops them skips it.
|
||||
|
||||
Reference in New Issue
Block a user