diff --git a/AGENTS.md b/AGENTS.md index 2b829f35..8c449c13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ 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 each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing +- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md` and `docs/decisions.md`; the worker's own account of which goal settles a choice decides nothing - loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it - loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json` - bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor diff --git a/CHANGELOG.md b/CHANGELOG.md index f4602db7..d8173855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ## Unreleased - Unless another Exempt reason fits, larv-review marks a `todo.md` item filed from a 🟡 finding against `~/.claude/principles/` with `principle`, an Exempt reason that keeps it whatever its score. +- `loop-claude`'s judge reads the project's `AGENTS.md` and `docs/decisions.md` beside the README's goals and audience, and does not interrupt for a choice they settle. When the worker asks a question that the README or those files answer, the worker resumes with the judge's quote of the answer, which `loop-claude` prints. A quote they do not hold word for word is dropped, and the question goes to you. So does a question asked again after its answer. The fourth question they answer in one cycle goes to you too, with the quote. The judge reads as much of the transcript's end as fits a 400,000-character prompt, up from the last 40,000 characters. `loop-claude` exits 1 when `AGENTS.md` or `docs/decisions.md` cannot be read or is not UTF-8. +- A project's decision log is `docs/decisions.md` alone, the one file the judge, `rank_todo.py` and the reviewers read. - `loop-claude` waits out a usage limit and retries: 2 minutes past the reset, or every 10 minutes when the reset time is unknown. A limit is not a failure, and restarts the count of three failures in a row. It prints what claude said about the limit and when the next try is due. - Add the official plugin marketplace and install every plugin `settings.json` enables (README → Install): `claude-security`, `code-review` and `rust-analyzer-lsp`, which needs `rust-analyzer` on `PATH` for Rust projects. With `claude-security`, larv-review's full security scan runs once you confirm its cost; an unattended larv-review reports the scan as not run. `settings.json` silences the plugin's scan tip after `git push`. - systems-architect and product-owner-reviewer can no longer edit what they review; stability-reviewer keeps its shell to run tests, and loses Claude Code's file-editing tools. diff --git a/CLAUDE.md b/CLAUDE.md index 36b8a3c4..47a333e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -87,7 +87,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ### Decisions: one home, each linked to a goal or a technical principle -**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A choice found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to the log, leaving its title in `AGENTS.md`'s list. A goal stays a goal in the README; the log records only what the goal leaves open. +**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. **The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A choice found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to the log, leaving its title in `AGENTS.md`'s list. A goal stays a goal in the README; the log records only what the goal leaves open. **Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. @@ -151,7 +151,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl ## Vocabulary - **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. -- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. +- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md` or `docs/decisions.md`. - **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. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. diff --git a/bin/loop_claude/claude_code/entries.py b/bin/loop_claude/claude_code/entries.py index f226a57c..1bd0b534 100644 --- a/bin/loop_claude/claude_code/entries.py +++ b/bin/loop_claude/claude_code/entries.py @@ -65,6 +65,13 @@ def human_text(entry: dict) -> str | None: return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry)) +# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; the previous run stopped before it was finished."}} +def loop_text(entry: dict) -> str | None: + """What a -p prompt of loop-claude's told the agent.""" + text = content(entry) + return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None + + # 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: dict) -> str | None: diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index 64599c11..bf2ae8f6 100644 --- a/bin/loop_claude/claude_code/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -1,6 +1,6 @@ import json -from loop_claude.claude_code.entries import assistant_parts, human_text, parse_entry, part_text, tool_call +from loop_claude.claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call from loop_claude.failure import Failure JUDGED_TOOL_INPUT = 400 @@ -30,6 +30,8 @@ def render(entries: list[dict]) -> str: lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))] if (text := human_text(entry)) is not None: lines.append("[human] " + text) + elif (text := loop_text(entry)) is not None: + lines.append("[loop] " + text) return "\n\n".join(lines) diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 2c8b481e..b3857aac 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -3,30 +3,38 @@ import json import typing from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output +from loop_claude.cycle.limited import Limited from loop_claude.cycle.retry import retried -from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict +from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict from loop_claude.effects import Effects from loop_claude.failure import Failure -from loop_claude.limited import Limited from loop_claude.stop import Stop -JUDGED_TRANSCRIPT_TAIL = 40000 +# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03. +JUDGE_PROMPT_CHARS = 400000 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" + "- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither " + "README.md nor the project's records settle the matter, or it asks again a question a [loop] line already answered\n" + "- it carried on under an assumption that decides the deliverable, that the human could " + "reasonably reject and that neither README.md nor the project's records settle; 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" + "- it chose between alternatives that neither README.md nor the project's records discriminate " + "between - neither rules 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" + "is still open, never a question they already answered there. A [loop] line is what loop-claude told " + "the agent, such as an answer quoted from README.md or the project's records. A question a [loop] " + "line answered is settled. If the agent asks it again, interrupt with that question.\n" "Where the agent asked or flagged something itself, the question is that one, in the agent's own " "wording; never construct another from facts it stated.\n" + "Where README.md or the project's records answer the agent's own question and no [loop] line has " + "quoted that answer yet, set interrupt=false, put that question in question and quote the passage that answers it in answer, verbatim; the agent is " + "then given that passage in place of the human's reply.\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." @@ -34,10 +42,11 @@ JUDGE_RULES = ( @dataclasses.dataclass(frozen=True) class Reply: - 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."}) + answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the project's records that answers the agent's question, quoted verbatim. Empty otherwise."}) + evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt; for a quoted answer, the agent's question; 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."}) + question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."}) REPLY_TYPES = typing.get_type_hints(Reply) @@ -49,7 +58,7 @@ JUDGE_SCHEMA = { } -def judge(root: str, task: str, premises: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop: +def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop: # 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", @@ -60,11 +69,11 @@ def judge(root: str, task: str, premises: str, rendered_transcript: str, model: "--permission-mode", "bypassPermissions", "--tools", "", ] - prompt = judge_prompt(task, premises, rendered_transcript) - return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects) + prompt = judge_prompt(task, premises, records, rendered_transcript) + return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, f"{premises}\n\n{records}", effects), effects) -def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure | Limited: +def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited: try: proc = effects.claude(args, root, prompt) except OSError as failure: @@ -79,18 +88,23 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, if isinstance(verdict, Failure): return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}") if not grounded(verdict.evidence, rendered_transcript): - return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else "")) + return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else "")) + # Not a Failure: a misquote would otherwise exit an unattended loop. + if isinstance(verdict, QuotedAnswer) and not grounded(verdict.answer, quotable): + return Interrupt(verdict.evidence, verdict.question) return verdict -def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str: - return ( +def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> str: + head = ( f"From README.md:\n{premises}\n\n" + f"The project's records, its working rules and decisions:\n{records or 'none'}\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{rendered_transcript[-JUDGED_TRANSCRIPT_TAIL:]}\n\n" - f"{JUDGE_RULES}" + "What the agent did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n" ) + room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2) + # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. + return f"{head}{rendered_transcript[max(0, len(rendered_transcript) - room):]}\n\n{JUDGE_RULES}" def verdict_from(output: object) -> Verdict | Failure: @@ -99,11 +113,15 @@ def verdict_from(output: object) -> Verdict | Failure: for name, kind in REPLY_TYPES.items(): if not isinstance(output.get(name), kind): return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}") - # An interrupt outranks finished: the human answers before the chunk can close. + # An interrupt outranks a quoted answer and finished: the human answers before the chunk can close. if output["interrupt"]: if not output["question"].strip(): return Failure("the judge interrupted without a question") return Interrupt(output["evidence"], output["question"]) + if output["answer"].strip(): + if not output["question"].strip(): + return Failure("the judge quoted an answer without a question") + return QuotedAnswer(output["evidence"], output["question"], output["answer"]) return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) diff --git a/bin/loop_claude/limited.py b/bin/loop_claude/cycle/limited.py similarity index 100% rename from bin/loop_claude/limited.py rename to bin/loop_claude/cycle/limited.py diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 571df431..f4be7406 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -1,9 +1,9 @@ import sys import typing +from loop_claude.cycle.limited import Limited from loop_claude.effects import Effects from loop_claude.failure import Failure -from loop_claude.limited import Limited from loop_claude.stop import Stop T = typing.TypeVar("T") diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index d889ec1f..413a04c8 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -7,13 +7,14 @@ from loop_claude.cycle.archive import archive from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.cycle.retry import retried -from loop_claude.cycle.states import Active, Answered, Archived, Closing, Ended, Event, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition -from loop_claude.cycle.verdicts import Finished, Unfinished +from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition +from loop_claude.cycle.verdicts import Finished, QuotedAnswer, Unfinished from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.effects import Effects from loop_claude.failure import Failure from loop_claude.paths import Paths from loop_claude.project.model_choice import Models +from loop_claude.project.records import QUOTE_SOURCES from loop_claude.stop import Stop @@ -24,6 +25,7 @@ class Cycle: paths: Paths premises: str project_key: str + records: str root: str session: Session task: str @@ -51,11 +53,11 @@ def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: def step(cycle: Cycle, state: Active) -> Event | Stop: match state: - case Working(): - return work(cycle) - case Judging(transcript_path): + case Working(answered, _): + return work(cycle, answered) + case Judging(transcript_path, _): return rule(cycle, transcript_path) - case Interrupting(transcript_path, question): + case Interrupting(transcript_path, question, _): return ask(cycle, transcript_path, question) case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) @@ -63,9 +65,11 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: typing.assert_never(state) -def work(cycle: Cycle) -> WorkerRan | Stop: +def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop: + if answered is not None: + print(f"\n=== {QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) # session_open runs inside the lambda: a failed attempt may have opened the session. - if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session)), cycle.effects), cycle.effects): + if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session), answered), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") @@ -75,15 +79,15 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) - verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge, cycle.effects) + verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), cycle.models.judge, cycle.effects) return verdict if isinstance(verdict, Stop) else Ruled(verdict) -def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: +def ask(cycle: Cycle, transcript_path: str, question: str) -> HumanAnswered | Stop: # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}", cycle.paths): return Stop(1, failure.reason) - return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() + return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered() def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index ad0f5b11..aa74f42d 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -1,22 +1,31 @@ import dataclasses -from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict +from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict +from loop_claude.project.records import QUOTE_SOURCES + +# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records. +QUOTED_ANSWERS_PER_CYCLE = 3 @dataclasses.dataclass(frozen=True) class Working: - """The worker runs.""" + """The worker runs, resumed with an answer quoted from README.md or the records when there is one.""" + answered: QuotedAnswer | None = None + quoted_answers: int = 0 @dataclasses.dataclass(frozen=True) class Judging: + """The judge rules; quoted_answers counts the questions README.md or the records answered this cycle.""" transcript_path: str + quoted_answers: int = 0 @dataclasses.dataclass(frozen=True) class Interrupting: transcript_path: str question: str + quoted_answers: int = 0 @dataclasses.dataclass(frozen=True) @@ -45,7 +54,7 @@ class Ruled: @dataclasses.dataclass(frozen=True) -class Answered: +class HumanAnswered: pass @@ -54,20 +63,24 @@ class Archived: pass -Event = WorkerRan | Ruled | Answered | Archived +Event = WorkerRan | Ruled | HumanAnswered | Archived def transition(state: State, event: Event) -> State: match state, event: - case Working(), WorkerRan(transcript_path): - return Judging(transcript_path) - case Judging(transcript_path), Ruled(Interrupt(question=question)): - return Interrupting(transcript_path, question) - case Judging(transcript_path), Ruled(Finished() | Unfinished() as verdict): + case Working(_, quoted_answers), WorkerRan(transcript_path): + return Judging(transcript_path, quoted_answers) + case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE: + return Working(answered, quoted_answers + 1) + case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer(question=question, answer=answer)): + return Interrupting(transcript_path, f"{question}\n\n{QUOTE_SOURCES} says:\n{answer}\n\nThose files have answered {quoted_answers} questions this cycle, the most allowed, so this one comes to you.", quoted_answers) + case Judging(transcript_path, quoted_answers), Ruled(Interrupt(question=question)): + return Interrupting(transcript_path, question, quoted_answers) + case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict): return Closing(transcript_path, verdict) # The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves. - case Interrupting(transcript_path), Answered(): - return Judging(transcript_path) + case Interrupting(transcript_path, _, quoted_answers), HumanAnswered(): + return Judging(transcript_path, quoted_answers) case Closing(), Archived(): return Ended() raise ValueError(f"no transition from {state} on {event}") diff --git a/bin/loop_claude/cycle/verdicts.py b/bin/loop_claude/cycle/verdicts.py index 1fa48086..172e8159 100644 --- a/bin/loop_claude/cycle/verdicts.py +++ b/bin/loop_claude/cycle/verdicts.py @@ -7,6 +7,14 @@ class Interrupt: question: str +@dataclasses.dataclass(frozen=True) +class QuotedAnswer: + """The agent asked a question that README.md or the project's records answer. The answer field quotes the passage.""" + evidence: str + question: str + answer: str + + @dataclasses.dataclass(frozen=True) class Finished: evidence: str @@ -17,4 +25,4 @@ class Unfinished: evidence: str -Verdict = Interrupt | Finished | Unfinished +Verdict = Interrupt | QuotedAnswer | Finished | Unfinished diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index dcc642bf..a268e800 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,9 +1,11 @@ from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until from loop_claude.claude_code.session import Session from loop_claude.claude_code.transcript import part_line +from loop_claude.cycle.limited import Limited +from loop_claude.cycle.verdicts import QuotedAnswer from loop_claude.effects import Effects from loop_claude.failure import Failure -from loop_claude.limited import Limited +from loop_claude.project.records import QUOTE_SOURCES PRINTED_TOOL_INPUT = 160 @@ -37,8 +39,10 @@ def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure return None if result is not None else Failure("claude exited 0 without a result event") -def worker_args(task: str, session: Session, model: str, resuming: bool) -> list[str]: - if resuming: +def worker_args(task: str, session: Session, model: str, resuming: bool, answered: QuotedAnswer | None = None) -> list[str]: + if answered is not None: + start = ["-p", f"Your question: {answered.question}\n\n{QUOTE_SOURCES} answers it:\n\n{answered.answer}\n\nContinue the task.", "--resume", str(session.id)] + elif 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 chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)] diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index a9b593d2..9b3d74dd 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -3,8 +3,14 @@ usage: loop-claude 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 the premises and rules whether the chunk, the work of one PR, is finished. +premises; the task runs at the checkout root. Each cycle a worker runs the task. A judge then reads +the transcript's end, the premises, and the project's records: AGENTS.md and docs/decisions.md, +where they exist. It rules whether the chunk, the work of one PR, is finished. A choice the worker +made that the premises or the records settle is not asked about. When the worker asks a question +they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A +quote they do not hold word for word is dropped, and the question goes to the human. So does a +question asked again after its answer. The fourth question they answer in one cycle goes to the +human too, with the quote. 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. @@ -33,6 +39,7 @@ loop-claude --help succeeds: the loop reloads into the edited script. Exit 1, saying why, when: - no task is given - git cannot start or finds no checkout +- README.md, or AGENTS.md or docs/decisions.md where they exist, cannot be read or is not UTF-8 - README.md holds no premises - the models file cannot be read or written - claude leaves no transcript @@ -45,11 +52,11 @@ Exit 1, saying why, when: - the worker or the judge fails three times running, retried a minute apart within the cycle. 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 reply misses or mistypes a field, - interrupts without a question, or quotes a line the transcript does not hold. A usage limit is - not a failure, and restarts the count of three: the worker or the judge is retried 2 minutes - after the limit resets, or every 10 minutes when the reset time is unknown or more than 2 - minutes past. The judge's reply gives its reset time only as text, so the judge is always - retried every 10 minutes. stderr says when the next try is due. + interrupts or quotes an answer without a question, or quotes a line the transcript does not hold. + A usage limit is not a failure, and restarts the count of three: the worker or the judge is + retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or + more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is + always retried every 10 minutes. stderr says when the next try is due. Exit 2, when the human is needed and cannot answer: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered @@ -71,6 +78,7 @@ from loop_claude.paths import Paths from loop_claude.project.checkout import checkout_root, project_key from loop_claude.project.model_choice import get_or_ask_models from loop_claude.project.premises import read_premises +from loop_claude.project.records import read_records from loop_claude.stop import Stop @@ -98,11 +106,14 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc premises = read_premises(loop_run.root) if isinstance(premises, Stop): return premises + records = read_records(loop_run.root) + if isinstance(records, Stop): + return records models = get_or_ask_models(key, paths, env, effects) if isinstance(models, Stop): return models print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True) - if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, root=loop_run.root, session=session, task=loop_run.task)): + if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, records=records, root=loop_run.root, session=session, task=loop_run.task)): return stop diff --git a/bin/loop_claude/markdown_sections.py b/bin/loop_claude/markdown_sections.py new file mode 100644 index 00000000..593d6655 --- /dev/null +++ b/bin/loop_claude/markdown_sections.py @@ -0,0 +1,27 @@ +import re + +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M) + + +def sections(text: str) -> dict[str, list[str]]: + blocks: list[tuple[str | None, list[str]]] = [] + opener = "" + for line in text.splitlines(): + if fence := FENCE.match(line): + marker = fence.group(1) + if not opener: + opener = marker + elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip(): + opener = "" + fenced = bool(opener or fence) + if not fenced and line.startswith("## "): + blocks.append((line.strip()[3:], [])) + elif not fenced and line.startswith("# "): + blocks.append((None, [])) + elif blocks and line.strip(): + blocks[-1][1].append(line) + found: dict[str, list[str]] = {} + for name, body in blocks: + if name is not None: + found.setdefault(name, []).append("\n".join(body)) + return found diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index 4fc70c25..de5f057d 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -27,3 +27,13 @@ def worktrees(root: str, effects: Effects) -> list[str]: def project_key(root: str, code: pathlib.Path) -> str: return root.removeprefix(f"{code}/").lstrip("/") + + +def read_checkout_file(root: str, name: str, consequence: str) -> str | Stop: + try: + return pathlib.Path(root, name).read_text(encoding="utf-8") + except OSError as failure: + return Stop(1, f"{name} in {root}: {failure.strerror} - {consequence}.") + except UnicodeDecodeError as failure: + line = failure.object.count(b"\n", 0, failure.start) + 1 + return Stop(1, f"{name} in {root} is not UTF-8 on line {line} - {consequence}.") diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index ba152799..45b080f4 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,19 +1,13 @@ -import pathlib -import re - +from loop_claude.markdown_sections import sections +from loop_claude.project.checkout import read_checkout_file from loop_claude.stop import Stop -FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M) - def read_premises(root: str) -> str | Stop: - 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.") + text = read_checkout_file(root, "README.md", "no premises") + if isinstance(text, Stop): + return text + found = sections(text) for name in ("Goals", "Audience"): bodies = found.get(name, []) if not bodies: @@ -23,27 +17,3 @@ def read_premises(root: str) -> str | Stop: 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: str) -> dict[str, list[str]]: - blocks: list[tuple[str | None, list[str]]] = [] - opener = "" - for line in text.splitlines(): - if fence := FENCE.match(line): - marker = fence.group(1) - if not opener: - opener = marker - elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip(): - opener = "" - fenced = bool(opener or fence) - if not fenced and line.startswith("## "): - blocks.append((line.strip()[3:], [])) - elif not fenced and line.startswith("# "): - blocks.append((None, [])) - elif blocks and line.strip(): - blocks[-1][1].append(line) - found: dict[str, list[str]] = {} - for name, body in blocks: - if name is not None: - found.setdefault(name, []).append("\n".join(body)) - return found diff --git a/bin/loop_claude/project/records.py b/bin/loop_claude/project/records.py new file mode 100644 index 00000000..42fe7d33 --- /dev/null +++ b/bin/loop_claude/project/records.py @@ -0,0 +1,21 @@ +import pathlib + +from loop_claude.project.checkout import read_checkout_file +from loop_claude.stop import Stop + +RECORD_FILES = ("AGENTS.md", "docs/decisions.md") +# The files a quoted answer comes from, named as the human and the worker see them; of README.md the judge sees only the premises. +QUOTE_SOURCES = "README.md's Goals and Audience, " + " or ".join(RECORD_FILES) + + +def read_records(root: str) -> str | Stop: + """The record files, each headed by its path; a file the project lacks is left out.""" + records = [] + for name in RECORD_FILES: + if not pathlib.Path(root, name).exists(): + continue + text = read_checkout_file(root, name, "the judge cannot read the project's records") + if isinstance(text, Stop): + return text + records.append(f"From {name}:\n{text.strip()}") + return "\n\n".join(records) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index edff2d7e..f6dfdb92 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -60,7 +60,7 @@ import sys # Kept inside loop_claude/ so reload's fingerprint covers them. from loop_claude.failure import Failure from loop_claude.file_writes import replace_file -from loop_claude.project.premises import FENCE, sections +from loop_claude.markdown_sections import FENCE, sections EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 84e6440f..c78b3a6d 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -16,15 +16,15 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import file_writes, paths +from loop_claude import file_writes, markdown_sections, paths from loop_claude.claude_code import entries, session, transcript, trust from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker -from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished +from loop_claude.cycle.limited import Limited +from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from loop_claude.effects import Effects from loop_claude.failure import Failure -from loop_claude.limited import Limited from loop_claude.loop import main, reload -from loop_claude.project import checkout, model_choice, premises +from loop_claude.project import checkout, model_choice, records from loop_claude.stop import Stop CWD = pathlib.Path("/c") @@ -91,8 +91,8 @@ def ran(stdout="", code=0, stderr=""): return subprocess.CompletedProcess([], code, stdout, stderr) -def judged(verdict, evidence="working"): - reply = {"evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict == "interrupt" else ""} +def judged(verdict, evidence="working", answer=""): + reply = {"answer": answer, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""} return ran(json.dumps({"structured_output": reply})) @@ -127,19 +127,28 @@ class Streamed: class Transitions(unittest.TestCase): def test_each_state_moves_on_its_events_and_only_on_them(self): + answered = states.Ruled(QuotedAnswer("e", "Which one?", "A.")) legal = ( (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), + (states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)), (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), + (states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?", 3)), + (states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)), + (states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)), + (states.Judging("/t", 3), answered, states.Interrupting("/t", "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md or docs/decisions.md says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.", 3)), (states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), + (states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), - (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), + (states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), + (states.Interrupting("/t", "q"), states.HumanAnswered(), states.Judging("/t")), + (states.Interrupting("/t", "q", 3), states.HumanAnswered(), states.Judging("/t", 3)), (states.Closing("/t", Finished("e")), states.Archived(), states.Ended()), ) for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Closing("/t", Finished("e")), states.Ended()) - every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived()) + every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", "q"), states.Interrupting("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended()) + every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanAnswered(), states.Archived()) for state in every_state: for event in every_event: if (state, event) not in [(state, event) for state, event, _ in legal]: @@ -155,8 +164,8 @@ class Cycles(unittest.TestCase): self.paths = paths.paths_from(self.home, {}) self.session = session.session_for("proj", self.paths) - def cycle(self, fake): - return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", root=str(self.home), session=self.session, task="Do it.") + def cycle(self, fake, records=""): + return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", records=records, root=str(self.home), session=self.session, task="Do it.") def archived_verdicts(self): return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.verdict.md")) @@ -235,6 +244,25 @@ class Cycles(unittest.TestCase): self.assertNotIn("the second", prompts[0]) self.assertIn("[human] the second", prompts[1]) + def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self): + answered = judged("quoted", answer="Use *A*.") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, on_terminal_claude=[0], git=[ran()]) + with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed: + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + resumed = fake.made("stream_claude")[1] + self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md or docs/decisions.md answers it:\n\nUse *A*.\n\nContinue the task.") + self.assertEqual(len(fake.made("stream_claude")), 4) + self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md or docs/decisions.md answered: Which one? ===\nUse *A*."), 3) + self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md or docs/decisions.md says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue()) + + def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use B.")], on_terminal_claude=[0], git=[ran()]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(len(fake.made("stream_claude")), 1) + self.assertIn("\nWhich one?\n", said.getvalue()) + self.assertNotIn("Use B.", said.getvalue()) + @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") def test_stops_keeping_the_transcript_when_the_finished_chunks_session_cannot_be_deleted(self): folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) @@ -295,7 +323,7 @@ class Limits(unittest.TestCase): def test_the_judge_reports_a_limit_whatever_its_exit_code(self): reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"}) fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")]) - self.assertEqual(judge.run_judge("/r", [], "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)")) + self.assertEqual(judge.run_judge("/r", [], "", "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)")) def test_reads_only_a_rejecting_events_whole_seconds(self): for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]: @@ -348,19 +376,37 @@ class WorkerArgs(unittest.TestCase): self.assertNotIn("Do it.", " ".join(resumed)) +class Records(unittest.TestCase): + def test_heads_each_record_the_project_has_by_its_path(self): + with tempfile.TemporaryDirectory() as root: + self.assertEqual(records.read_records(root), "") + pathlib.Path(root, "docs").mkdir() + pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n") + self.assertEqual(records.read_records(root), "From docs/decisions.md:\n# Decisions") + pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n") + self.assertEqual(records.read_records(root), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions") + + def test_stops_on_a_record_it_cannot_read(self): + with tempfile.TemporaryDirectory() as root: + pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True) + self.assertEqual(records.read_records(root), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the project's records.")) + pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n") + self.assertEqual(records.read_records(root), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the project's records.")) + + 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(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) + self.assertEqual(markdown_sections.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) def test_closes_a_fence_only_on_its_own_marker(self): text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n" - self.assertEqual(list(premises.sections(text)), ["Goals", "Audience"]) - self.assertEqual(list(premises.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"]) + self.assertEqual(list(markdown_sections.sections(text)), ["Goals", "Audience"]) + self.assertEqual(list(markdown_sections.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"]) class Render(unittest.TestCase): - def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): + def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self): said = transcript.render([ human("do it"), assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), @@ -372,7 +418,7 @@ class Render(unittest.TestCase): 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\n\n[human] B, while you work') + 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\n\n[loop] Continue the task; the previous run stopped before it was finished.') class CopyFor(unittest.TestCase): @@ -453,12 +499,15 @@ class Grounded(unittest.TestCase): class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) - self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) - self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) - self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean")) - self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply 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({"answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) + self.assertEqual(judge.verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) + self.assertEqual(judge.verdict_from({"answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) + self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.")) + self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?")) + self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question")) + self.assertEqual(judge.verdict_from({"answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean")) + self.assertEqual(judge.verdict_from({"answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string")) + self.assertEqual(judge.verdict_from({"answer": "", "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 reply")) @@ -484,10 +533,16 @@ class LoopRuns(unittest.TestCase): self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude ")) +class HelpLimits(unittest.TestCase): + def test_help_states_the_limits_the_code_holds(self): + self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", main.__doc__.replace("\n", " ")) + + class ExitContract(unittest.TestCase): def test_every_exit_1_stop_has_its_clause_in_help(self): read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "README.md holds no premises" models_ = "the models file cannot be read or written" + unreadable = f"README.md, or {' or '.join(records.RECORD_FILES)} where they exist, cannot be read or is not UTF-8" # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. clauses = [ ("cycle/interrupt.py", "interrupt", "1", "entries.reason", read), @@ -505,11 +560,11 @@ class ExitContract(unittest.TestCase): ("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), ("project/checkout.py", "checkout_root", "1", "f'could not start git:", git), ("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git), + ("project/checkout.py", "read_checkout_file", "1", "f'{name} in {root}:", unreadable), + ("project/checkout.py", "read_checkout_file", "1", "f'{name} in {root} is not UTF-8", unreadable), ("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_), ("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_), ("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_), - ("project/premises.py", "read_premises", "1", "f'README.md in {root}:", premises_), - ("project/premises.py", "read_premises", "1", "f'README.md is not UTF-8", premises_), ("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_), ("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_), ("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_), diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 10f69aea..8c9f0209 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -116,7 +116,7 @@ def worker(**step): def judge(interrupt=False, finished=False, evidence="working", question="", **step): - verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} + verdict = {"answer": "", "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} return {"role": "judge", "verdict": verdict, **step} @@ -282,7 +282,7 @@ class Premises(unittest.TestCase): 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## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} 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.", @@ -323,6 +323,8 @@ 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() + (checkout.root / "docs").mkdir() + (checkout.root / "docs" / "decisions.md").write_text("# Decisions\n") run = checkout.run([ worker(say="started"), judge(evidence="started"), worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"), @@ -341,6 +343,7 @@ class Cycles(unittest.TestCase): 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.assertIn("From docs/decisions.md:\n# Decisions", 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"]) @@ -389,7 +392,7 @@ class Cycles(unittest.TestCase): 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 reply; it replied: nothing\n", run.stderr) - self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}') + self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string; it replied: {"structured_output": {"interrupt": false}}') def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self): checkout = Checkout(self) @@ -428,9 +431,10 @@ class Cycles(unittest.TestCase): def test_hands_the_judge_the_tail_of_a_long_transcript(self): checkout = Checkout(self) - run = checkout.run([worker(say="early " * 20000 + "LATE")]) + run = checkout.run([worker(say="early " * 80000 + "LATE")]) self.assertIn("LATE", run.calls[1]["stdin"]) - self.assertLess(run.calls[1]["stdin"].count("early"), 20000) + self.assertEqual(len(run.calls[1]["stdin"]), 400000) + self.assertLess(run.calls[1]["stdin"].count("early"), 80000) 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): diff --git a/docs/decisions.md b/docs/decisions.md index b745e4db..626cd016 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -4,9 +4,11 @@ 2026-09-20, lilleman. Serves goal 4. Across six projects scored with the four seats, Locality or Self-sufficiency capped every seat and Navigation capped none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats. -## loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing +## loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md` and `docs/decisions.md`; the worker's own account of which goal settles a choice decides nothing -2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge is to read `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); `todo.md` item 7 ends the README-only bar. Valid while the worker's self-report stays unreliable. +2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. + +2026-10-01, lilleman: the judge reads `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); its bar becomes whether the README or those files discriminate. 2026-10-03, implemented: when the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended (goal 4.4); the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question those files answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones. ## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it @@ -30,7 +32,9 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -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, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076. Under Self-sufficiency, every seat named larv-review §3 and the agents, which a reader follows only with `CLAUDE.md` open. lilleman decided the same day to ship that PR under the floor; the place filed is `todo.md` item 13. The 2026-10-02 run on PR #198 (a usage limit waited out) scored 7.63, 6.88, 7.38, 6.75, 7.13 at 8e85033. Under Self-sufficiency, every seat named larv-review §3, which `todo.md` item 13 covers; under Locality, they named `archive`'s invariants spread over `session.py` and `run.py`, `rank_todo.py` reaching into `premises.sections`, and `stopped` comparing reason strings, each under `todo.md`'s bar and not filed. lilleman decided the same day to ship that PR under the floor. 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, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076. Under Self-sufficiency, every seat named larv-review §3 and the agents, which a reader follows only with `CLAUDE.md` open. lilleman decided the same day to ship that PR under the floor; the place filed is `todo.md` item 13. The 2026-10-02 run on PR #198 (a usage limit waited out) scored 7.63, 6.88, 7.38, 6.75, 7.13 at 8e85033. Under Self-sufficiency, every seat named larv-review §3, which `todo.md` item 13 covers; under Locality, they named `archive`'s invariants spread over `session.py` and `run.py`, `rank_todo.py` reaching into `premises.sections`, and `stopped` comparing reason strings, each under `todo.md`'s bar and not filed. lilleman decided the same day to ship that PR under the floor. + +The 2026-10-03 runs on PR #202 (the judge reads the project's records) scored 7.75, 7.13, 7.25, 7.0, 7.25 in the first round and 7.5, 7.0, 7.0, 6.75, 7.0 in the eighth; between them a dimension moved by up to 0.4 on near-identical code. Under Self-sufficiency every seat named larv-review §3 and the agents leaning on `CLAUDE.md`, the Claude Code flags left unexplained, and the judge's contract spread over its prompt, schema, parser and `--help`; under Shape, that "record", "verdict" and "judge" each name two things, and that `loop_claude/` holds modules `rank_todo.py` also uses. lilleman decided the same day to ship that PR under the floor and to fix those places next: `todo.md` items 13, 17, 42, 43 and 44, ranked after item 41. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes diff --git a/todo.md b/todo.md index 1ff55532..9bd2526e 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 9` -`Next ID = 40` +`Next ID = 46` | Goal | W | |---|---| @@ -25,19 +25,23 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| | 39 | 0.1.0 | defect | **Run larv-review's security pass so it hands back to the run, and the run goes on to the next pass without the user prompting it.** | 2 | 2 | 10 | 10 | 4, 4.2 | 30.9 | +| 41 | 0.1.0 | defect | **Accept a judge's quote that elides with an ellipsis when its fragments appear in the transcript in order, and tell the judge to quote one passage.** | 2 | 2 | 10 | 10 | 4, 4.2 | 30.9 | +| 17 | 0.1.0 | decision | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 10 | 9 | 4, 4.1 | 30.6 | +| 13 | 0.1.0 | decision | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 10 | 10 | 4, 4.1 | 29.1 | | 1 | 0.1.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | -| 7 | 0.1.0 | decision | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | -| 8 | 0.1.0 | | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 | -| 13 | 0.1.0 | decision | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | +| 42 | 0.1.0 | decision | **Give the judge's contract one home, so its prompt, reply schema, parser and `--help` cannot drift apart.** | 3 | 4 | 9 | 9 | 4, 4.1 | 26.1 | +| 44 | 0.1.0 | decision | **Move the modules `rank_todo.py` shares out from under `loop_claude/`, keeping them inside reload's fingerprint.** | 2 | 2 | 8 | 8 | 4, 4.1 | 24.2 | +| 43 | 0.1.0 | decision | **Give "record", "verdict" and "judge" one meaning each across loop-claude, larv-review and workflow-bench.** | 2 | 3 | 8 | 8 | 4, 4.1 | 24.0 | | 23 | 0.1.0 | | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | +| 40 | 0.1.0 | | **Render tool input in the judged transcript with its non-ASCII characters as written, so the judge's quotes of it match the transcript.** | 2 | 1 | 5 | 6 | 4.2 | 13.0 | | 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | | 36 | 0.1.0 | | **Ask the user once before a full security scan, folding larv-review's ask into the plugin's cost prompt.** | 2 | 2 | 5 | 5 | 4.2 | 11.9 | | 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | | 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | | 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | | 29 | 0.1.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | -| 17 | 0.1.0 | decision | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | | 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 | +| 45 | 0.1.0 | principle | **Sort each Python file's imports by the first name each binds.** | 2 | 3 | 3 | 3 | 4.1 | 6.6 | ## Details @@ -45,28 +49,44 @@ larv-review §3 runs `/security-review` through the Skill tool, in the run's own context. That skill's prompt ends "Your final reply must contain the markdown report and nothing else", so the run's turn ends on the report: stability, product-owner, prose, the gate and the merge never run, and the user has to prompt the run to go on. Seen on 2026-10-03 in fejkdata PR #145. One fix: launch the security pass as a subagent given that skill's prompt, so its final reply is the subagent's, and larv-review's turn continues. +### 41. Accept a judge's quote that elides with an ellipsis when its fragments appear in the transcript in order, and tell the judge to quote one passage. + +On 2026-10-03 the log project's loop exited 1: "the judge failed three times running: the judge quoted \"**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …\", which is not in the transcript". Each fragment the judge joined with " ... " is in the rendered transcript; `grounded` matches the evidence as one contiguous string, so a correct interrupt was rejected three times and the human was never asked. The archive is `~/.claude/loop-claude-transcripts/log/dbac9d7096282d2bc6c38fc8c03cd74b50d29b75080b1f647c0f305a088db894/5d8c9152cdcd91e90dfd2773cd81c9e64bcd412ff148c5cf19e2a728ceee5028.verdict.md`. Fix both ends: `grounded` splits on `...` and `…` and finds the fragments in order, and the `evidence` description asks for one contiguous passage. + +### 17. Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open. + +The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. + +### 13. Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded. + +Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. + ### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. 2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest. -### 7. Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice. +### 42. Give the judge's contract one home, so its prompt, reply schema, parser and `--help` cannot drift apart. -Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match. +The 2026-10-03 scoring runs on PR #202 named it under Self-sufficiency and Locality: what a reply means is stated in `JUDGE_RULES`, the `Reply` field descriptions, `verdict_from`'s precedence, `transition`'s cap and the `--help` docstring, and the repeated-question rule lives only in the prompt. Derive each from one definition, or tie it to that definition with a test; the interrupt wording moves out of `transition` into `run.ask`. -### 8. Judge a cycle on more than the transcript's last 40,000 characters. +### 44. Move the modules `rank_todo.py` shares out from under `loop_claude/`, keeping them inside reload's fingerprint. -`judge_prompt` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. +Named under Shape by the same runs: `failure.py`, `file_writes.py` and `markdown_sections.py` sit in loop-claude's package because `reload.fingerprint` hashes only `loop_claude/**/*.py`, and nothing at the package says a second tool depends on them. Widen the fingerprint to a named shared package. -### 13. Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded. +### 43. Give "record", "verdict" and "judge" one meaning each across loop-claude, larv-review and workflow-bench. -Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. +Named under Shape by the same runs: loop-claude's records are `AGENTS.md` and `docs/decisions.md`, larv-review's "record" is a decision-log entry or plan item older than the chunk; `Verdict` is the judge's ruling and `.verdict.md` also holds stop reasons; `cycle/judge.py` and `workflow-bench/judge.py` are different judges. ### 23. Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers. On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads. +### 40. Render tool input in the judged transcript with its non-ASCII characters as written, so the judge's quotes of it match the transcript. + +`part_line` renders a tool call with `json.dumps(arguments)`, which escapes non-ASCII as `\uXXXX`. A judge that quotes such a line with its characters as written, such as Swedish text, fails `grounded` three times on one transcript, and the loop exits 1. Raised, unverified, by the 2026-10-03 scoring run on PR #202. + ### 21. Give `settings.json`'s model one writer, and sort its keys. Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. @@ -93,10 +113,10 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. -### 17. Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open. - -The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. - ### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. + +### 45. Sort each Python file's imports by the first name each binds. + +The principle "Deterministic order wherever order carries no meaning" sorts imports on their first binding; `bin/loop_claude/` and `bin/rank_todo.py` sort `from loop_claude…` imports by module path, as in `loop/main.py` and `cycle/run.py`, so moving a module reorders imports in every file that uses it. Filed by the 2026-10-03 principles audit on PR #202.