Compare commits

...

20 Commits

Author SHA1 Message Date
lilleman b03bfab121 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 2m36s
2026-11-12 11:35:10 +01:00
lilleman 2294916343 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); fixed in the stability answer: the changelog bullet, the decision's title and count, the rule's sentences, the re-entry pointer and Done's clause 2026-11-12 11:33:53 +01:00
lilleman c010b12c5a Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); fixed in the stability answer: a run that fails is fixed again, a round needs a 🔴, the findings ask only for a kill or a pass, and the answer commit records the clean run 2026-11-12 11:33:53 +01:00
lilleman 6ff139f67c Answer stability round 1: 1 🔴, 2 🟡 (0 misread); require every 🔴 and 🟡 to be mechanical, keep the named test as found, recount the archive, and say which passes still rerun 2026-11-12 11:33:53 +01:00
lilleman 7b0e428eec Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-12 11:28:34 +01:00
lilleman dd7e9b9929 Skip a stability round 2 whose every 🔴 named a surviving mutant or a failing test
CI / tests (pull_request) Successful in 2m12s
2026-11-12 11:27:46 +01:00
lilleman 02bde923e5 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); fixed in the stability answer: the decision's margin figures, title and actors, the help's bar clause, and item 321's detail
CI / tests (pull_request) Successful in 2m37s
2026-11-12 11:21:27 +01:00
lilleman 87ffd81d21 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); fixed in the stability answer: whole counts in the report, and the help says a replay fails 2026-11-12 11:21:27 +01:00
lilleman 2770de2744 Answer stability round 1: 0 🔴, 7 🟡 (0 misread); hold a rung to a whole count of findings, tell a 🔴 by its opening mark, test the second reference replay failing alone, and share the candidate rungs 2026-11-12 11:21:19 +01:00
lilleman 058f4ca7aa Test the reference replays apart, a round one of them failed on and a reference that found nothing; drop share's dead guard 2026-11-12 11:01:49 +01:00
lilleman d55b1e4ad5 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-12 10:54:38 +01:00
lilleman 4fc822c346 Record the prose replay under the new bar, which qualified no rung, and finish item 318
CI / tests (pull_request) Failing after 2m39s
2026-11-12 10:54:01 +01:00
lilleman cbe99537e2 Qualify a review-replay rung by the project's rung's own recall, trying the project's model at lower efforts first 2026-11-12 10:39:40 +01:00
lilleman fa54ed46b1 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); rename Record to Annotation, and reword the decision, the help and the changelog
CI / tests (pull_request) Successful in 2m37s
2026-11-12 10:25:30 +01:00
lilleman 72d9a9f652 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); print the report before exiting 1 on an unreadable archive, naming the file 2026-11-12 10:25:30 +01:00
lilleman d449c552c6 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); keep the whole typed answer that holds the judge's quote of a reversal, and test a failing rev-parse 2026-11-12 10:25:30 +01:00
lilleman 67e272d5ef Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-12 10:10:29 +01:00
lilleman ec0b17b03f Sort the new modules' imports, and test a reversal count where every chunk holds one 2026-11-12 10:09:19 +01:00
lilleman 1fc7bf0f52 Kill the surviving mutants of the spend, the setup version and the reversal count, and keep a subagent's type on one line 2026-11-12 10:03:47 +01:00
lilleman 3c4cedd389 Record with each archived verdict the setup that ran it, what each model spent by kind, and the human's reversals
CI / tests (pull_request) Failing after 2m12s
2026-11-12 09:57:56 +01:00
31 changed files with 1100 additions and 258 deletions
+3
View File
@@ -2,6 +2,9 @@
## Unreleased
- larv-review skips stability round 2 where round 1 reported a 🔴 and every 🔴 and 🟡 asked only that a named mutant be killed or a named failing test pass, once the tests and the mutation command run clean on the fixes.
- `review-replay` now qualifies a rung whose share of a pass's archived findings is no more than 10 points below the mean of two replays on the project's rung, over at least 8 rounds, where it misses no 🔴 that both found. It used to demand every finding the project's rung found again, which the project's rung itself failed. It tries the project's model at each lower effort first, then the ladder below. Its run on the prose pass of Opus 5.5 projects qualified no rung: Opus 5.5 at low effort found 49% against a bar of 66%.
- loop-claude records beside each verdict, interrupt and quoted answer the claude-config release and commit that ran it, the tokens the worker, each subagent and the judge spent, by model and kind, with the list prices in force, and any typed answer of yours the judge quotes as reversing a choice the worker took on its own recommendation; `score-outcomes` counts those reversals per finished chunk.
- `larv-review prepare-scoring` makes a scoring run's worktree and writes each seat's prompt; `record-scoring` removes both once it has recorded the run.
- `deploy-release` moves a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes, and then says to pick the model again.
- `chunk-pr merge` waits for the pull request's checks itself, allowing a minute for them to report, and no longer takes `--gate-passed`. `wait-for <file> [<pattern>]` waits for a line in a background job's log or report.
+3 -3
View File
@@ -110,11 +110,11 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round twice as archived and once without the instruction files, and prints each finding the last replay missed that both of the others found. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. The rungs tried start with the project's model at a lower effort. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round twice as archived and once without the instruction files, and prints each finding the last replay missed that both of the others found. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
- `run-tests [<pytest args>...]` runs this repo's test suite, as Test says.
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by, and code health's two counter-signals per chunk, misread findings and later fixes; `score-outcomes --help` states the report.
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
@@ -141,7 +141,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `repo_checks/` tests the repo itself.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
- `test_env.py` serves the tests.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
+28
View File
@@ -0,0 +1,28 @@
"""The tokens a message's usage counts, by kind."""
import dataclasses
from claude_code.entries import usage_count
@dataclasses.dataclass(frozen=True)
class Tokens:
"""Raw token counts by kind. Claude Code's usage doesn't count thinking apart from output, so output holds both."""
input: int = 0
write_5m: int = 0
write_1h: int = 0
read: int = 0
output: int = 0
def plus(self, other: "Tokens") -> "Tokens":
return Tokens(*(mine + theirs for mine, theirs in zip(dataclasses.astuple(self), dataclasses.astuple(other))))
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
def tokens_of(usage: object) -> Tokens:
"""The tokens of one message's usage, or of a json reply's; none where it is no object."""
if not isinstance(usage, dict):
return Tokens()
written = usage.get("cache_creation")
# A write without the split by lifetime counts as a five-minute one.
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
return Tokens(usage_count(usage, "input_tokens"), five, hour, usage_count(usage, "cache_read_input_tokens"), usage_count(usage, "output_tokens"))
+11
View File
@@ -60,6 +60,17 @@ def render(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | No
return "\n\n".join(lines)
def human_answers(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> list[str]:
"""Each answer the human typed, whole, as render shows it on a [human] line, latest last."""
found = []
for entry in entries:
if isinstance(entry, HumanTurn):
found.append(entry.text)
elif isinstance(entry, LoopPrompt) and (typed := typed_answer(entry.text)):
found.append(typed.answer)
return found
def assistant_lines(turn: AssistantTurn) -> list[str]:
"""The turn's text and tool calls as the judge reads them."""
return [line for part in turn.parts if (line := part_line(part, JUDGED_TOOL_INPUT))]
+1 -1
View File
@@ -132,7 +132,7 @@ class Main(unittest.TestCase):
@staticmethod
def verdict(interrupt, evidence):
output = {"answer": "", "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "release_ready": False}
output = {"answer": "", "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
return {"type": "result", "structured_output": output}
def test_replays_the_models_projects_on_the_reference_then_on_each_rung_the_judge_climbs_to_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
+18 -4
View File
@@ -9,11 +9,12 @@ from loop_effects.effects import Effects
from claude_code.entries import Entry, structured_output
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from claude_code.transcript import plain, verbatim
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from claude_code.transcript import human_answers, plain, verbatim
from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung
from loop_claude.stop import Stop
from claude_code.tokens import tokens_of
# 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
@@ -77,6 +78,8 @@ class Reply:
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
# Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by.
reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."})
REPLY_TYPES = typing.get_type_hints(Reply)
@@ -103,6 +106,8 @@ class Grounds(typing.NamedTuple):
after_mark: str
# README.md's premises and the records.
quotable: str
# Each answer the human typed, whole, latest last (transcript.human_answers).
typed: tuple[str, ...] = ()
class Brief(typing.NamedTuple):
@@ -164,7 +169,8 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
if isinstance(reply, Failure | Limited):
return reply
verdict = verdict_from(structured_output(reply))
output = structured_output(reply)
verdict = verdict_from(output)
replied = json.dumps(reply, ensure_ascii=False)
cost = cost_of(reply)
if isinstance(verdict, Failure):
@@ -172,7 +178,13 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
checked = quotes_checked(verdict, grounds)
if isinstance(checked, Failure):
return Rejected(checked.reason, replied, cost)
return dataclasses.replace(checked, judge_cost=cost)
return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed)))
def reversal_of(output: object, typed: tuple[str, ...]) -> str:
"""The latest answer the human typed that holds the reply's reversed quote, whole, so the same answer archives the same way however the judge quotes it; empty where none does. verdict_from has checked the field is a str."""
quote = output.get("reversed") if isinstance(output, dict) else None
return next((answer for answer in reversed(typed) if isinstance(quote, str) and verbatim(quote, answer)), "")
def cost_of(reply: dict) -> float:
@@ -191,6 +203,7 @@ def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
| its left_open | answered_before and the question | the interrupt becomes an Unfinished that quotes answered_before back to the worker | re_ask_checked |
| a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried | answer_checked |
| the escalation | grounds.shown and grounds.after_mark | the escalation is dropped, so the worker's rung holds | escalation_mark.checked |
| the reversal | one of grounds.typed | the reversal is dropped; run_judge, after this check | reversal_of |
Only a misquoted evidence fails. A Failure for any other would exit an unattended loop, so each changes the verdict instead.
"""
@@ -252,5 +265,6 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
shown=shown,
after_mark=escalation_mark.after_mark(brief.entries, brief.escalated_at),
quotable=f"{brief.premises}\n\n{brief.records}",
typed=tuple(human_answers(brief.entries, typed_answer)),
)
return f"{head}{shown}\n\n{JUDGE_RULES}", grounds
+30 -6
View File
@@ -9,16 +9,19 @@ from loop_claude.cycle.judge import Brief, judge, Rejected
from loop_claude.cycle import chunk_items
from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_effects.effects import Effects, say
from claude_code.entries import Entry
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
from loop_claude.routing import judge_rung, next_route, step_up, StepUp
from transcript_archive.read import last_spent
from transcript_archive import outcomes
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from model_routing.ladder import Rung
from loop_claude.cycle import spend
from loop_claude.stop import Stop
from model_routing import worker_rungs
@@ -29,6 +32,8 @@ class Cycle:
Each step reads the few fields it needs by name, so the fields stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows more than seven where a reader finds them by name.
"""
# The claude-config release and commit the cycle runs under, such as `v0.8.0 (<sha>)`, or why they are unknown: loop/main.py's setup_version.
config: str
effects: Effects
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
facts: str
@@ -158,17 +163,32 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
if not isinstance(verdict, Interrupt | QuotedAnswer):
return Ruled(verdict)
annotation = annotation_of(cycle, transcript_path, entries, verdict.judged)
if isinstance(annotation, Failure):
return Stop(1, annotation.reason)
stepped = ruling_step_up(cycle, verdict)
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers), stepped):
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped):
return Stop(1, failure.reason)
return Ruled(verdict, stepped.after if stepped else None)
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> str:
def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: Judged) -> outcomes.Annotation | Failure:
"""What a verdict, an interrupt or a quoted answer records beside its judge lines: the setup, the stretch's spend as spend.py counts it, and the reversal the judge found."""
since = last_spent(cycle.project_archive, transcript_path)
if isinstance(since, Failure):
return since
subagents = spend.subagents(transcript_path)
if isinstance(subagents, Failure):
return subagents
spent = spend.spent(since, entries, subagents, judge_of(cycle).model, judged.tokens)
return outcomes.Annotation(cycle.config, spend.spent_block(since, spent), judged.reversed)
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> str:
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from README.md or the records."""
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judge_cost)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judge_cost)
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, annotation)
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
@@ -212,7 +232,11 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judge_cost) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judge_cost)
entries = read_transcript(transcript_path)
annotation = entries if isinstance(entries, Failure) else annotation_of(cycle, transcript_path, entries, verdict.judged)
if isinstance(annotation, Failure):
return Stop(1, annotation.reason)
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, annotation) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, annotation)
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
+96
View File
@@ -0,0 +1,96 @@
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`.
A stretch runs from the previous outcome that recorded a spend, or from the chunk's start, to the ruling. It counts the worker's main thread, each subagent and the judge run that ruled, each message once. Dollars are left to be derived from the model and the tokens, at the prices recorded beside them.
"""
import datetime
import json
import pathlib
import typing
from claude_code.entries import AssistantTurn, Entry
from failure import Failure
from routing_figures.prices import PRICES
from claude_code.transcript import read_transcript
from transcript_archive.outcomes import SPENT
from claude_code.tokens import Tokens, tokens_of
KINDS = "input, cache write 5m, cache write 1h, cache read, output"
# Who spent, such as `worker`, `judge` or `Explore "Search the hooks"`, and the model they ran on.
Spender = tuple[str, str]
WORKER = "worker"
JUDGE = "judge"
class Subagent(typing.NamedTuple):
"""A subagent's transcript, named by the agent type and the description its .meta.json gives: {"agentType": "Explore", "description": "Search the hooks", ...}."""
name: str
entries: list[Entry]
def spent(since: str, worker: list[Entry], subagents: list[Subagent], judge_model: str, judge: Tokens) -> dict[Spender, Tokens]:
"""The tokens each spender spent after since, a UTC stamp, or in the whole transcript where since is empty."""
found: dict[Spender, Tokens] = {}
for name, entries in ((WORKER, worker), *subagents):
for model, tokens in thread_spend(entries, since).items():
found[name, model] = found.get((name, model), Tokens()).plus(tokens)
found[JUDGE, judge_model] = judge
return {spender: tokens for spender, tokens in found.items() if tokens != Tokens()}
def thread_spend(entries: list[Entry], since: str) -> dict[str, Tokens]:
"""Each model's tokens in one transcript's messages written after since. A message's usage repeats in each entry of it, so each message counts once, by its id."""
start = moment(since) if since else None
counted: dict[str, AssistantTurn] = {}
for entry in entries:
if isinstance(entry, AssistantTurn) and entry.model and (start is None or later(entry.timestamp, start)):
counted.setdefault(entry.message_id or entry.uuid, entry)
found: dict[str, Tokens] = {}
for turn in counted.values():
found[turn.model] = found.get(turn.model, Tokens()).plus(tokens_of(turn.usage))
return found
def moment(stamp: str) -> datetime.datetime:
return datetime.datetime.fromisoformat(stamp)
# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. In practice none is, since the judge runs for seconds after the worker's last message.
def later(timestamp: str, start: datetime.datetime) -> bool:
"""Whether timestamp is after start; False where it is no time, or names no time zone to compare by."""
try:
return moment(timestamp) > start
except (TypeError, ValueError):
return False
def subagents(transcript_path: str) -> list[Subagent] | Failure:
"""The subagents' transcripts Claude Code keeps beside the worker's: <session>/subagents/agent-<id>.jsonl, each with its .meta.json."""
found = []
for path in sorted(pathlib.Path(transcript_path.removesuffix(".jsonl"), "subagents").glob("*.jsonl")):
entries = read_transcript(str(path))
if isinstance(entries, Failure):
return entries
found.append(Subagent(subagent_name(path), entries))
return found
def subagent_name(transcript: pathlib.Path) -> str:
"""The agent type and the quoted description; `subagent` where the meta is missing or names neither."""
try:
meta = json.loads(transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json").read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, ValueError):
meta = {}
meta = meta if isinstance(meta, dict) else {}
# One line for the type, since a line break could forge an archive line such as `Config: `; json.dumps escapes the description's.
kind, description = " ".join(str(meta.get("agentType") or "subagent").split()), str(meta.get("description") or "")
return f"{kind} {json.dumps(description, ensure_ascii=False)}" if description else kind
def spent_block(since: str, found: dict[Spender, Tokens]) -> str:
"""The archive's block for what the stretch spent, then the list prices in force for each model in it; empty where nothing was spent."""
if not found:
return ""
spenders = [f"- {name}, {model}: {', '.join(map(str, (tokens.input, tokens.write_5m, tokens.write_1h, tokens.read, tokens.output)))}" for (name, model), tokens in found.items()]
priced = [f"- {model}: {price.input:g}, {price.write_5m:g}, {price.write_1h:g}, {price.read:g}, {price.output:g}" for model in dict.fromkeys(model for _, model in found) if (price := PRICES.get(model))]
prices = ["", f"List prices in dollars per million tokens of {KINDS}:", *priced] if priced else []
return "\n".join([f"{SPENT}{since or 'the chunk began'}, in tokens of {KINDS}:", *spenders, *prices])
+18 -1
View File
@@ -12,6 +12,7 @@ from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint,
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.project.model_choice import get_or_ask_models
from git_cli.git_repo import Git
from loop_claude.loop.usage import HELP
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
@@ -90,7 +91,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
todo = fetched_todo(loop)
show_taken_in = shown_items(loop, todo, route.item)
show_taken_in(loop_run.items_taken_in)
return Cycle(effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
@@ -104,3 +105,19 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
return loop_run
def setup_version(claude_dir: pathlib.Path, git: Git) -> str:
"""The release and commit of this setup that the worker's claude reads, as `v0.8.0 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. Where git can't tell, `unknown` and why."""
described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir))
commit = git("rev-parse", "HEAD", cwd=str(claude_dir))
if isinstance(described, Failure):
return unknown_version(described)
if isinstance(commit, Failure):
return unknown_version(commit)
return f"{described.strip()} ({commit.strip()})"
def unknown_version(failure: Failure) -> str:
# One line, since the archive reads the line after it as the judge's.
return f"unknown: {' '.join(failure.reason.split())}"
+12 -11
View File
@@ -151,7 +151,7 @@ def worker(**step):
def judge(interrupt=False, finished=False, evidence="working", question="", escalation="", release_ready=False, **step):
verdict = {"answer": "", "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready}
verdict = {"answer": "", "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": ""}
return {"role": "judge", "verdict": verdict, **step}
@@ -299,7 +299,7 @@ class Checkout:
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
def archived(self):
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC>, after checking the copy is named by its content hash."""
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC> and every setup version by <config>, after checking the copy is named by its content hash."""
outcomes = {}
for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()):
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
@@ -308,7 +308,8 @@ class Checkout:
kept = copy.with_suffix(".outcomes.md")
for archived in (copy, kept):
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
outcomes[copy.read_text()] = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
outcomes[copy.read_text()] = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE)
return outcomes
@@ -422,8 +423,8 @@ class Cycles(unittest.TestCase):
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "next chunk"', copies[f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n"])
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
@@ -451,8 +452,8 @@ class Cycles(unittest.TestCase):
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p"))
self.assertIn("on one line, as in `Chunk items: ", argument(workers[0], "-p"))
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
checkout = Checkout(self)
@@ -507,8 +508,8 @@ class Cycles(unittest.TestCase):
("claude-fable-5-2", "low"),
])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
checkout = Checkout(self)
@@ -526,7 +527,7 @@ class Cycles(unittest.TestCase):
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertNotIn("at max effort", "".join(outcomes))
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_on_it_and_its_judge_on_the_models_highest(self):
checkout = Checkout(self)
@@ -724,7 +725,7 @@ class Interrupt(unittest.TestCase):
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\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ")
+191 -33
View File
@@ -28,9 +28,10 @@ from release_plan.release_standing import DefaultPlan, LastCut
from loop_effects.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT
from claude_code import entries, reply, session
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
from git_cli.git_repo import git
from loop_state import hand_over, paths, running_loops, session_lock
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
from model_routing.ladder import LADDER, Rung
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
@@ -42,12 +43,15 @@ from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from loop_claude.stop import Stop
from loop_state.running_loops import Taken
from claude_code.tokens import Tokens, tokens_of
from records.utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
from loop_state.waiting.listing import waiting
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
# The claude-config release and commit each cycle the tests run is under.
CONFIG = "v0.8.0 (abc123)"
# How it records routes by item 179's L of 2 and E + I of 5, on Routing's rungs.
SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "likelihood": 2, "escape_and_impact": 5}'
OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}'
@@ -171,19 +175,21 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None):
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready}
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""):
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed}
return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})}))
class Worker:
"""A worker claude: writes a line to the session's transcript, then streams a result."""
def __init__(self, home, prompted=False, text="working"):
def __init__(self, home, prompted=False, text="working", usage=None):
self.home = home
# Whether it records its -p prompt in the transcript first, as claude does.
self.prompted = prompted
self.text = text
# The usage its message records, twice as Claude Code writes a message of two blocks; none where None.
self.usage = usage
def __call__(self, args):
flag = "--session-id" if "--session-id" in args else "--resume"
@@ -194,7 +200,10 @@ class Worker:
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n")
if self.prompted:
handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n")
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
said = assistant({"type": "text", "text": self.text})
if self.usage is not None:
said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage}
handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2))
return Streamed(0)
@@ -278,7 +287,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -286,14 +295,38 @@ class Cycles(unittest.TestCase):
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_archives_the_cost_the_judges_reply_records_beside_its_verdict(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished", cost=0.25)])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judge_cost=0.25))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judged=Judged(cost=0.25)))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_archives_what_the_worker_and_the_judge_spent_beside_the_verdict(self):
worker = Worker(self.paths.claude_code_transcripts.parent, usage={"input_tokens": 1, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5})
answer = json.loads(judged("finished").stdout)
fake = FakeEffects(streams=[worker], claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 6, "output_tokens": 7}}))])
run.run_cycle(self.cycle(fake))
self.assertEqual(self.archived_outcomes(), [f"""Task: Do it.
2026-09-21T14:13:20Z Verdict: finished
Evidence:
> working
Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:
- worker, claude-opus-5-5: 1, 2, 3, 4, 5
- judge, judge-model: 6, 0, 0, 0, 7
List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output:
- claude-opus-5-5: 4, 5, 8, 0.2, 20
Config: {CONFIG}
Judge: judge-model
Worker: {OFF_LADDER}
"""])
def test_shows_the_items_each_ruling_finds_the_worker_names_on_its_chunk_items_line(self):
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 14 (L 2, E + I 3), 3 (L 1, E + I 2)")
fake = FakeEffects(streams=[worker], claude=[judged("unfinished")])
@@ -344,7 +377,7 @@ class Cycles(unittest.TestCase):
self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1])
self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
@@ -363,12 +396,13 @@ class Cycles(unittest.TestCase):
"Task: Do it.\n\n"
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self):
for first, then, inputs in (
(judged("interrupt", cost=0.25), judged("finished"), ["Use B."]),
(judged("quoted", answer="Use A.", cost=0.25), judged("finished"), []),
(judged("unfinished", cost=0.25), judged("finished"), []),
(judged("finished", evidence="never said", cost=0.25), judged("finished"), []),
):
with self.subTest(first=first.stdout), tempfile.TemporaryDirectory() as archive:
@@ -378,6 +412,36 @@ class Cycles(unittest.TestCase):
kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md"))
self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept)
def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self):
for verdict in ("interrupt", "finished"):
with self.subTest(verdict=verdict), tempfile.TemporaryDirectory() as archive:
unreadable = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" / "agent-x.jsonl"
unreadable.mkdir(parents=True)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged(verdict)], inputs=["Use B."])
with contextlib.redirect_stderr(io.StringIO()):
stop = run.run_cycle(dataclasses.replace(self.cycle(fake), project_archive=pathlib.Path(archive)))
self.assertEqual((stop.code, stop.reason), (1, f"could not read the transcript {unreadable}: Is a directory"))
shutil.rmtree(unreadable.parent.parent)
(self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl").unlink()
def test_counts_the_spend_since_the_last_outcome_that_recorded_one_and_archives_the_reversal(self):
transcript = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl"
transcript.parent.mkdir(parents=True)
old = {"type": "assistant", "timestamp": "2026-09-21T14:13:19Z", "message": {"id": "old", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 100}}}
new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}}
transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW))
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")])
run.run_cycle(self.cycle(fake))
latest = max(self.archived_outcomes(), key=len)
self.assertIn(f"""Reversed:
> No, keep the old name.
Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache write 1h, cache read, output:
- worker, claude-opus-5-5: 0, 0, 0, 0, 5
""", latest)
def test_stops_with_exit_1_asking_nothing_where_an_interrupt_cannot_be_archived(self):
self.archive.parent.mkdir(parents=True)
self.archive.write_text("")
@@ -450,7 +514,7 @@ class Cycles(unittest.TestCase):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer])
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
judge_prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(judge_prompts), 2)
@@ -469,8 +533,8 @@ class Cycles(unittest.TestCase):
self.assertEqual(len(fake.made("stream_claude")), 4)
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
@@ -482,7 +546,7 @@ class Cycles(unittest.TestCase):
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
self.assertNotIn("went through", first[first.index("-p") + 1])
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n"
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n"
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
kept = "".join(self.archived_outcomes())
self.assertIn(f"Z {answered}\n20", kept)
@@ -495,7 +559,7 @@ class Cycles(unittest.TestCase):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
kept = "".join(self.archived_outcomes())
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n", kept)
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n", kept)
self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept)
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self):
@@ -612,7 +676,7 @@ class Cycles(unittest.TestCase):
stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
self.assertTrue(session.session_open(self.session))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)])
@@ -1577,6 +1641,98 @@ class JudgePrompt(unittest.TestCase):
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
def turn(message_id, model, at, **usage):
return entries.AssistantTurn(message_id=message_id, model=model, timestamp=at, usage=usage)
class Spend(unittest.TestCase):
def test_reads_the_cache_writes_by_lifetime_and_counts_one_without_the_split_as_five_minutes(self):
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}), Tokens(1, 2, 3, 4, 5))
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0))
self.assertEqual(tokens_of(None), Tokens())
def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self):
thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)]
self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)})
def test_sums_two_subagents_of_one_name_on_one_model(self):
helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])]
self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)})
def test_counts_each_message_once_by_its_id_and_only_after_since(self):
thread = [
turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7),
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
turn("m3", "b", "2026-11-01T10:00:03Z", cache_read_input_tokens=5),
]
self.assertEqual(spend.thread_spend(thread, "2026-11-01T10:00:01Z"), {"a": Tokens(1, 0, 0, 0, 2), "b": Tokens(0, 0, 0, 5, 0)})
self.assertEqual(spend.thread_spend(thread, ""), {"a": Tokens(1, 0, 0, 0, 9), "b": Tokens(0, 0, 0, 5, 0)})
def test_names_each_spender_and_leaves_out_one_that_spent_nothing(self):
worker = [turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7)]
helper = spend.Subagent('Explore "Search"', [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)])
self.assertEqual(spend.spent("", worker, [helper], "j", Tokens()), {("worker", "a"): Tokens(output=7), ('Explore "Search"', "b"): Tokens(input=3)})
self.assertEqual(spend.spent("", [], [], "j", Tokens(input=1)), {("judge", "j"): Tokens(input=1)})
def test_names_a_subagent_by_its_agent_type_and_description(self):
with tempfile.TemporaryDirectory() as root:
folder = pathlib.Path(root, "s", "subagents")
folder.mkdir(parents=True)
for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]:
(folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n")
if meta:
(folder / f"{name}.meta.json").write_text(json.dumps(meta))
found = spend.subagents(str(pathlib.Path(root, "s.jsonl")))
self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"])
self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)})
self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), [])
def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self):
found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)}
self.assertEqual(spend.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output:
- worker, claude-opus-5-5: 1, 2, 3, 4, 5
- judge, unpriced: 6, 0, 0, 0, 0
List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output:
- claude-opus-5-5: 4, 5, 8, 0.2, 20""")
self.assertEqual(spend.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0")
self.assertEqual(spend.spent_block("", {}), "")
def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self):
shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name"
typed = ("Use A.", "No, keep the old name. Use X.")
for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]:
with self.subTest(quoted=quoted):
answer = json.loads(judged("unfinished", reversed=quoted).stdout)
fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))])
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept)))
class SetupVersion(unittest.TestCase):
def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self):
with tempfile.TemporaryDirectory() as root:
isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root}
with unittest.mock.patch.dict(os.environ, isolated):
gone = main.setup_version(pathlib.Path(root), git)
self.assertRegex(gone, r"^unknown: [^\n]*not a git repository")
for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]):
self.assertIsInstance(git(*step, cwd=root), str)
head = git("rev-parse", "HEAD", cwd=root).strip()
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})")
git("tag", "v0.1.0", cwd=root)
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})")
git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root)
head = git("rev-parse", "HEAD", cwd=root).strip()
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})")
def test_names_why_git_cannot_name_the_commit_on_one_line(self):
def fake_git(*args, cwd=None):
return Failure("fatal: bad HEAD\nhint: repair it") if args[0] == "rev-parse" else "v0.1.0\n"
self.assertEqual(main.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it")
class Grounded(unittest.TestCase):
def test_every_verdict_must_quote_the_transcript(self):
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
@@ -1639,32 +1795,32 @@ class ChunkItems(unittest.TestCase):
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "reversed": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
def test_carries_the_earlier_answer_an_interrupt_names(self):
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?"}
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?", "reversed": ""}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more"))
self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e"))
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
def test_takes_an_escalation_quote_on_an_interrupt(self):
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
@@ -1690,7 +1846,7 @@ class Verdict(unittest.TestCase):
self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed)
def test_takes_an_escalation_quote_on_a_quoted_answer(self):
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
@@ -1883,8 +2039,10 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("cycle/run.py", "rule", "1", "entries.reason", read),
("cycle/run.py", "rule", "1", "annotation.reason", read),
("cycle/run.py", "rule", "1", "failure.reason", read),
("cycle/run.py", "keep_rejection", "1", "unkept.reason", read),
("cycle/run.py", "close", "1", "annotation.reason", read),
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
+17 -8
View File
@@ -1,6 +1,8 @@
"""The verdicts cycle.judge.verdict_from builds from the judge's reply; cycle.run.rule then stamps every verdict but Finished with the items the chunk takes. They sit outside cycle/, since routing reads them and cycle imports routing."""
import dataclasses
from claude_code.tokens import Tokens
@dataclasses.dataclass(frozen=True)
class TakenIn:
@@ -13,6 +15,17 @@ class TakenIn:
highest_escape_and_impact: int = 0
@dataclasses.dataclass(frozen=True)
class Judged:
"""What the judge run that gave a verdict found beside it, which the cycle archives with the verdict."""
# In dollars, as its reply records; 0 where it records none.
cost: float = 0.0
# Its reply's usage, on the judge's model.
tokens: Tokens = Tokens()
# The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote.
reversed: str = ""
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
@@ -23,8 +36,7 @@ class Interrupt:
release_ready: bool = False
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read: int | None = None
# What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
judge_cost: float = 0.0
judged: Judged = Judged()
# The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them.
answered_before: str = ""
left_open: str = ""
@@ -40,15 +52,13 @@ class QuotedAnswer:
escalation: str = ""
taken_in: TakenIn = TakenIn()
entries_read: int | None = None
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
judge_cost: float = 0.0
judged: Judged = Judged()
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
judge_cost: float = 0.0
judged: Judged = Judged()
@dataclasses.dataclass(frozen=True)
@@ -58,8 +68,7 @@ class Unfinished:
escalation: str = ""
taken_in: TakenIn = TakenIn()
entries_read: int | None = None
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
judge_cost: float = 0.0
judged: Judged = Judged()
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
+1 -1
View File
@@ -96,7 +96,7 @@ def stepped_up(rung: Rung) -> Rung:
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay …`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
+64 -40
View File
@@ -1,4 +1,4 @@
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.
usage: review-replay <pass> <model> [--omit-claude-md]
@@ -13,17 +13,22 @@ shows the chunk's change. The prompt names the clone in place of the worktree it
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
names it and why. The prompt also names a copy of the chunk's review folder in place of that
folder, holding only the reports written after the chunk began and before the round did. A replay
finds nothing where its prompt still names the review folder, or names a file there, other than a
round's report, that the folder did not hold from the chunk's start until the round's.
fails where its prompt still names the review folder, or names a file there, other than a round's
report, that the folder did not hold from the chunk's start until the round's.
It first replays every round on the project's rung, the reference reviewer. Archived findings
that the reference reviewer does not raise again may rest on code or rules that have changed
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
one. For each replay, claude on the project's rung matches the report to the archived findings,
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
evidence for running the pass's reviewer on it; the decision above records each run.
It replays every round twice on the project's rung. Even that rung finds only part of its own
archived findings again, so the bar for a rung below is the mean share of those two replays, less
a margin of 10 percentage points. Rounds that either replay failed on are left out, and where
fewer than 8 remain, or the bar is zero or below, no rung is tried. It
then replays the rounds on each rung below, highest first: the project's model at each lower
effort, which the ladder leaves out, then each ladder rung down to the ladder's lowest. It stops at
the first rung that doesn't qualify. A rung qualifies where it finds as many findings as reach the
bar and misses no 🔴 that both replays on the project's rung found; a replay that failed on it
finds nothing. For
each replay, claude on the project's rung matches the report to the archived findings, and counts
a finding only where the report raises it as 🔴 or 🟡. The tool prints each rung's count, each 🔴
it missed, and the lowest rung that, like each rung above it, qualifies. That rung is the evidence
for running the pass's reviewer on it; the decision above records each run.
With --omit-claude-md it tests instead whether the pass's reviewer may start without CLAUDE.md:
docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass
@@ -39,8 +44,9 @@ in its settings and opens the prompt with what the hook hands a reviewer, and cl
header's line on the project principles.
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
review or match finds nothing, or with --omit-claude-md leaves its round out. Exit 1, saying why, on bad arguments, an unreadable archive or
models file, no archived round to replay, or a usage limit.
review or match leaves its round out, except on a rung below the project's, where it finds
nothing. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived
round to replay, or a usage limit.
"""
import dataclasses
import json
@@ -52,17 +58,18 @@ import tempfile
import typing
from transcript_archive.location import archive_root
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
from review_replay.rounds import authored_by, comparison, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
from rung_replay.command import arguments_or_exit, failed, limited_exit, projects_on
from review_replay.rounds import authored_by, comparison, lost_inputs, reviewed_path, Round, round_from, sample, stamp_seconds
from review_replay.recall import candidates, enough, needed, Recall, recall_report, Reference, RungRecall, tried
from transcript_archive.project_key import checkout_of
from claude_code.reply import claude_reply, Limited
from loop_effects.effects import Effects
from failure import Failure
from rung_replay.search import first_reply, replayed, replayed_on
from rung_replay.search import first_reply, replayed_on
from claude_code.transcript import first_timestamped_line, read_transcript
from model_routing.ladder import LADDER, project_rung, Rung
from claude_code.entries import parse_entry, structured_output
from review_rules.reviewer_context import principles_line, reviewer_context
from model_routing.ladder import project_rung, Rung
from review_rules.review_folder import REPORTS, review_folder
from review_rules.review_passes import ReviewedPass, REVIEWERS
@@ -98,19 +105,50 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
chosen = sample(list(codes), LATEST)
if without:
return compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare))
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
candidates = down_from(project, LADDER[0])[1:]
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
return findings_found(found, codes[found], rung, project, home, effects)
def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited:
matched = findings_replayed(found, codes[found], rung, project, home, effects, False)
if isinstance(matched, Failure):
print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True)
return matched
replay = replayed(chosen, project, candidates, found_on, reproduced, f"{reviewed} rounds")
if isinstance(replay, Limited):
return limited_exit(TOOL, replay)
print(report(reviewed, project.model, project, chosen, replay))
recall = recalled(chosen, project, replay_one, f"{reviewed} rounds")
if isinstance(recall, Limited):
return limited_exit(TOOL, recall)
print(recall_report(reviewed, project, recall))
return 0
def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
"""Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify."""
runs: list[list[set[int] | Failure]] = []
for _ in range(2):
found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what)
if isinstance(found, Limited):
return found
runs.append(found)
rounds: list[Round] = []
reference: Reference = ([], [])
for one, first, second in zip(chosen, *runs):
if not isinstance(first, Failure) and not isinstance(second, Failure):
rounds.append(one)
reference[0].append(first)
reference[1].append(second)
recalls: list[RungRecall] = []
lowest = None
for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []:
on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what)
if isinstance(on_rung, Limited):
return on_rung
# A failed replay on a candidate found nothing, so it lowers that rung's count and never lifts it to what a rung needs.
one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung])
recalls.append(one)
if not one.qualifies:
break
lowest = rung
return Recall(rounds, reference, len(chosen) - len(rounds), recalls, lowest)
def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing.Callable[[Round, bool], set[int] | Failure | Limited]) -> int:
"""Replays chosen twice with CLAUDE.md and once without, as found_on(round, bare) finds, and prints the comparison of the rounds no replay failed on."""
runs: list[list[set[int] | Failure]] = []
@@ -152,11 +190,6 @@ def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
return codes
def reproduced(_: Round, found: set[int]) -> list[int]:
"""The indexes of the round's findings that a replay on the reference reviewer found, which each lower rung is held to."""
return sorted(found)
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
projects = projects_on(model, home)
if isinstance(projects, Failure):
@@ -190,7 +223,7 @@ def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Roun
def code_of(found: Round, effects: Effects) -> Code | Failure:
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer of the archived findings, and no rung is held to those.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess shows every rung the same wrong code: the project's rung finds fewer of that round's archived findings, which lowers the bar, and the rungs below find fewer too.
"""
if not os.path.isdir(found.root):
return Failure("the project has no checkout")
@@ -225,15 +258,6 @@ def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home:
return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects))
def findings_found(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
"""findings_replayed with CLAUDE.md, where a failed replay finds nothing and stderr says why."""
matched = findings_replayed(found, code, rung, project, home, effects, False)
if isinstance(matched, Failure):
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
return set()
return matched
@dataclasses.dataclass(frozen=True)
class Copies:
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
+93
View File
@@ -0,0 +1,93 @@
"""The bar review-replay holds a rung to, and its report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
import dataclasses
from rung_replay.command import down_from
from fractions import Fraction
from review_replay.rounds import is_red, Round
from model_routing.ladder import LADDER, Rung
import math
# A rung qualifies with a share of the archived findings up to this far below the project's rung's. The project's rung found 69 to 78% of its own findings again, and its two replays of the same rounds differed by up to 4 points.
MARGIN = Fraction(1, 10)
# The fewest rounds a rung is tried on: 8 of the 10 the tool samples, so up to two may fail on the project's rung.
ENOUGH_ROUNDS = 8
# Lowest first, as Claude Code's --effort takes them.
EFFORTS = ("low", "medium", "high", "xhigh", "max")
# The two replays on the project's rung. Each lists, round by round, the indexes of the findings it found.
Reference = tuple[list[set[int]], list[set[int]]]
@dataclasses.dataclass(frozen=True)
class RungRecall:
"""A rung's replay: how many of the archived findings it found, and each 🔴 it missed that both of the project's rung's replays found, as a round and the finding's index."""
rung: Rung
found: int
missed_red: list[tuple[Round, int]]
qualifies: bool
@dataclasses.dataclass(frozen=True)
class Recall:
"""rounds, the rounds no replay on the project's rung failed on; left_out, how many more it failed on; tried, each candidate tried, highest first; lowest, the lowest that, like each above it, qualifies."""
rounds: list[Round]
reference: Reference
left_out: int
tried: list[RungRecall]
lowest: Rung | None
def candidates(project: Rung) -> list[Rung]:
"""The rungs tried below the project's, highest first: its model at each lower effort, which the ladder leaves out, then each ladder rung below it, down to the ladder's lowest. That reaches below the lowest a worker routes to, since a pass may run below the worker's rung."""
lower_efforts = [Rung(project.model, effort) for effort in reversed(EFFORTS[:EFFORTS.index(project.effort)])]
return lower_efforts + down_from(project, LADDER[0])[1:]
def enough(rounds: list[Round]) -> bool:
return len(rounds) >= ENOUGH_ROUNDS
def count(found: list[set[int]]) -> int:
return sum(map(len, found))
def held(rounds: list[Round]) -> int:
"""How many findings rounds hold."""
return sum(len(one.findings) for one in rounds)
def mean_share(rounds: list[Round], reference: Reference) -> Fraction:
"""The mean share of rounds' findings that the project's rung's two replays found; rounds is never empty, and each holds a finding."""
return Fraction(count(reference[0]) + count(reference[1]), 2 * held(rounds))
def needed(rounds: list[Round], reference: Reference) -> int:
"""How many of rounds' findings a rung needs to find: the fewest that reach the project's rung's mean share less MARGIN. Zero or below, no rung is tried, since a rung that found nothing would qualify."""
return math.ceil((mean_share(rounds, reference) - MARGIN) * held(rounds))
def tried(rung: Rung, rounds: list[Round], reference: Reference, found: list[set[int]]) -> RungRecall:
"""rung's recall, from the indexes of each round's findings it found. It qualifies finding as many as needed, missing no 🔴 that both of the project's rung's replays found."""
missed_red = [(one, index) for one, first, second, got in zip(rounds, *reference, found) for index in sorted((first & second) - got) if is_red(one.findings[index])]
return RungRecall(rung, count(found), missed_red, 0 < needed(rounds, reference) <= count(found) and not missed_red)
def recall_report(reviewed: str, project: Rung, recall: Recall) -> str:
rounds, (first, second) = recall.rounds, recall.reference
lines = [
f"Replayed {len(rounds)} {reviewed} rounds of {project.model} projects, which hold {held(rounds)} 🔴 and 🟡 findings, twice on the project's rung, {project}.",
*([f"Left out {recall.left_out} more, which a replay on the project's rung failed on; stderr says why."] if recall.left_out else []),
]
if not enough(rounds):
return "\n".join([*lines, f"No rung tried: fewer than {ENOUGH_ROUNDS} rounds were replayed on the project's rung without a failure."])
if needed(rounds, recall.reference) <= 0:
return "\n".join([*lines, "No rung tried: the project's rung found too few of them to hold a rung to."])
lines.append(f"The project's rung found {count(first)} and then {count(second)} of the {held(rounds)}, {percent(mean_share(rounds, recall.reference))} on average, so a rung qualifies finding {needed(rounds, recall.reference)} or more of them, missing no 🔴 that both of its replays found.")
for one in recall.tried:
verdict = "it qualifies" if one.qualifies else "it doesn't qualify"
lines += [f"{one.rung} found {one.found}, {percent(Fraction(one.found, held(rounds)))}, and missed {len(one.missed_red) or 'no'} such 🔴: {verdict}.", *(f" {at.root} {at.at}: {at.findings[index].splitlines()[0]}" for at, index in one.missed_red)]
lowest = recall.lowest or "none below the project's rung"
lines.append(f"Lowest rung that qualifies: {lowest}")
return "\n".join(lines)
def percent(fraction: Fraction) -> str:
return f"{float(fraction):.0%}"
+7 -18
View File
@@ -1,4 +1,4 @@
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`."""
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report with --omit-claude-md: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
import dataclasses
import datetime
import pathlib
@@ -6,7 +6,6 @@ import re
import typing
from claude_code.entries import AssistantTurn, Entry, Text, UserText
from rung_replay.search import Replay
from model_routing.ladder import Rung
# A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them.
@@ -34,6 +33,12 @@ class Round:
return stamp_seconds(self.at)
def is_red(finding: str) -> bool:
"""Whether finding, which opens with a line FINDING matches, is raised as 🔴: by the mark it opens with, whatever marks its text names."""
mark = FINDING.match(finding)
return mark is not None and mark[0].endswith("🔴")
def round_from(reviewer: str, root: str, began: float, entries: list[Entry]) -> Round | None:
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
reports = [part.text for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text) and part.text]
@@ -102,22 +107,6 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:]
def report(reviewed: str, model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
total = sum(len(found_round.findings) for found_round in rounds)
lines = [
f"Replayed {len(rounds)} {reviewed} rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
]
for tried in replay.tried:
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {miss.case.root} {miss.case.at}: {miss.case.findings[miss.item].splitlines()[0]}" for miss in tried.missed)]
if not replay.tried:
lines.append("No rung tried: the reference reviewer found no finding to hold one to.")
else:
lowest = replay.lowest or "none below the project's rung"
lines.append(f"Lowest rung that finds every finding the reference reviewer finds: {lowest}")
return "\n".join(lines)
def comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str:
"""What the two replays with CLAUDE.md and the one without found in rounds, and each finding the one without missed that both of the others found; left_out counts the rounds a replay failed on, which rounds leaves out."""
first, second = with_it
+113
View File
@@ -0,0 +1,113 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_replay.recall import candidates, needed, Recall, recall_report, tried
from review_replay.rounds import is_red, Round
from model_routing.ladder import Rung
REFERENCE = Rung("claude-opus-5-5", "medium")
LOW = Rung("claude-opus-5-5", "low")
SONNET = Rung("claude-sonnet-5-5", "high")
def a_round(at, findings):
return Round("prose-reviewer", "/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
# Ten findings over two rounds; the project's rung found 8 and then 6, so its share is 70%, the bar 60% and a rung needs 6. Both found the first round's 🔴, and only the first found the second's.
ROUNDS = [a_round(1, ("🔴 a", "🟡 b", "🟡 c", "🟡 d", "🟡 e")), a_round(2, ("🔴 f\nmore", "🟡 g", "🟡 h", "🟡 i", "🟡 j"))]
FIRST = [{0, 1, 2, 3}, {0, 1, 2, 3}]
SECOND = [{0, 1, 2}, {1, 2, 3}]
# The project's rung found 1 and then 1 of the 10, so the bar is zero.
TENTH = ([{0}, set()], [{0}, set()])
class Candidates(unittest.TestCase):
def test_tries_the_project_models_lower_efforts_first_then_the_ladder_below_it(self):
self.assertEqual(candidates(REFERENCE), [LOW, SONNET])
def test_tries_each_ladder_rung_below_highest_first(self):
self.assertEqual(candidates(Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
def test_tries_each_lower_effort_of_the_ladders_lowest_rung(self):
self.assertEqual(candidates(SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
class Tried(unittest.TestCase):
def test_qualifies_a_rung_no_more_than_the_margin_below_the_project_rungs_share_that_misses_no_red_found_both_times(self):
found = tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1, 2}, {0, 1, 2}])
self.assertEqual((found.found, found.missed_red, found.qualifies), (6, [], True))
def test_fails_a_rung_below_the_bar(self):
found = tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1}, {0, 3}])
self.assertEqual((found.found, found.missed_red, found.qualifies), (4, [], False))
def test_fails_a_rung_that_misses_a_red_found_both_times_and_only_such_a_red(self):
above_the_bar = [{1, 2, 3, 4}, {0, 1, 2, 3}]
found = tried(LOW, ROUNDS, (FIRST, SECOND), above_the_bar)
self.assertEqual((found.found, found.missed_red, found.qualifies), (8, [(ROUNDS[0], 0)], False))
# The first round's 🔴 is found both times; a yellow found both times, such as its b, may be missed.
self.assertTrue(tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 2, 3, 4}, {0, 2, 3, 4}]).qualifies)
# The second round's 🔴, which only the first replay found, may be missed too.
self.assertTrue(tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1, 2, 3}, {1, 2, 3}]).qualifies)
def test_fails_every_rung_where_the_bar_is_zero_or_below(self):
self.assertFalse(tried(LOW, ROUNDS, ([set(), set()], [set(), set()]), [{0}, {0}]).qualifies)
self.assertFalse(tried(LOW, ROUNDS, TENTH, [{0}, {0}]).qualifies)
def test_rounds_the_findings_a_rung_needs_up(self):
# 33 findings, of which the project's rung found 24 and then 23: the bar is 61.2%, which 20 findings, 60.6%, don't reach.
rounds = [a_round(1, ["🟡 a"] * 33)]
reference = ([set(range(24))], [set(range(23))])
self.assertEqual(needed(rounds, reference), 21)
self.assertFalse(tried(LOW, rounds, reference, [set(range(20))]).qualifies)
self.assertTrue(tried(LOW, rounds, reference, [set(range(21))]).qualifies)
def test_lets_a_rung_miss_a_yellow_that_mentions_a_red(self):
rounds = [a_round(1, ("### 🟡 `SKILL.md:80`: the rule says a 🔴 in round 2 escalates", "🟡 b"))]
self.assertFalse(is_red(rounds[0].findings[0]))
self.assertTrue(is_red("### 1. **🔴 a\nwhich is no 🟡"))
found = tried(LOW, rounds, ([{0, 1}], [{0, 1}]), [{1}])
self.assertEqual((found.missed_red, found.qualifies), ([], False))
self.assertEqual(tried(LOW, rounds, ([{0, 1}], [{0}]), [{1}]).missed_red, [])
class RecallReport(unittest.TestCase):
# Eight rounds, enough to try a rung.
EIGHT = (ROUNDS * 4, (FIRST * 4, SECOND * 4))
def test_states_the_bar_each_rung_tried_each_red_it_missed_and_the_lowest_that_qualifies(self):
rounds, reference = self.EIGHT
low = tried(LOW, rounds, reference, [{0, 1, 2}, {0, 1, 2}] * 4)
sonnet = tried(SONNET, rounds, reference, [{1, 2, 3, 4}, {0}] * 4)
lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 1, [low, sonnet], LOW)).splitlines()
self.assertEqual(lines, [
"Replayed 8 prose rounds of claude-opus-5-5 projects, which hold 40 🔴 and 🟡 findings, twice on the project's rung, claude-opus-5-5 at medium effort.",
"Left out 1 more, which a replay on the project's rung failed on; stderr says why.",
"The project's rung found 32 and then 24 of the 40, 70% on average, so a rung qualifies finding 24 or more of them, missing no 🔴 that both of its replays found.",
"claude-opus-5-5 at low effort found 24, 60%, and missed no such 🔴: it qualifies.",
"claude-sonnet-5-5 at high effort found 20, 50%, and missed 4 such 🔴: it doesn't qualify.",
*[" /code/p 2026-10-14T10:00:01Z: 🔴 a"] * 4,
"Lowest rung that qualifies: claude-opus-5-5 at low effort",
])
def test_says_why_no_rung_was_tried(self):
few = recall_report("prose", REFERENCE, Recall(ROUNDS, (FIRST, SECOND), 0, [], None)).splitlines()
self.assertEqual(few[1:], ["No rung tried: fewer than 8 rounds were replayed on the project's rung without a failure."])
rounds, _ = self.EIGHT
for reference in (([set()] * 8, [set()] * 8), (TENTH[0] * 4, TENTH[1] * 4)):
too_few = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [], None)).splitlines()
self.assertEqual(too_few[1:], ["No rung tried: the project's rung found too few of them to hold a rung to."])
def test_names_no_rung_where_none_qualifies(self):
rounds, reference = self.EIGHT
low = tried(LOW, rounds, reference, [{0}, {0}] * 4)
lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [low], None)).splitlines()
self.assertEqual(lines[-2:], ["claude-opus-5-5 at low effort found 8, 20%, and missed no such 🔴: it doesn't qualify.", "Lowest rung that qualifies: none below the project's rung"])
if __name__ == "__main__":
unittest.main()
+52 -37
View File
@@ -14,20 +14,20 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds
from loop_effects.effects import Effects, system_effects
from claude_code.entries import entry_from
from failure import Failure
from review_replay import main
from rung_replay.search import Miss, Replay, Tried
from review_replay import main, recall
from review_rules.reviewer_context import reviewer_context
from review_rules.review_passes import REVIEWERS
from model_routing.ladder import Rung
from rung_replay import search
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
REFERENCE = Rung("claude-opus-5-5", "medium")
LOW = Rung("claude-opus-5-5", "low")
MIDDLE = Rung("claude-sonnet-5-5", "high")
CHEAP = Rung("claude-haiku-5-5", "max")
def entry(kind, text, **fields):
@@ -115,22 +115,6 @@ class Sample(unittest.TestCase):
self.assertEqual(sample(rounds, 2), [rounds[0], rounds[2]])
class Report(unittest.TestCase):
def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self):
rounds = [a_round(1, ("🔴 a\nmore", "🟡 b")), a_round(2)]
lines = report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
self.assertEqual(lines, [
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
"claude-sonnet-5-5 at high effort missed 0.",
"claude-haiku-5-5 at max effort missed 1:",
" /code/p 2026-10-14T10:00:01Z: 🔴 a",
"Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort",
])
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
class Launch(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
@@ -209,6 +193,8 @@ class Main(unittest.TestCase):
for key in ("proj", "other"):
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
# The fixture holds one round.
self.enterContext(unittest.mock.patch.object(recall, "ENOUGH_ROUNDS", 1))
self.reviews = []
self.agents = set()
self.matched_in = []
@@ -311,17 +297,17 @@ class Main(unittest.TestCase):
self.assertEqual(len(self.reviews), 1)
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung == MIDDLE else [0, 1]})
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [1] if rung == LOW else [0, 1]})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE, LOW])
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
# The default branch stands where it stood when the chunk began, so the prompt's diff against it shows the branch's change.
self.assertEqual((reviewed, branch, base), ("1\n", "x\n", "0\n"))
self.assertEqual(prompt, f"Review branch x in {cwd}.")
self.assertFalse(pathlib.Path(cwd).exists())
self.assertIn("The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", out)
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
self.assertTrue(out.endswith("finds: none below the project's rung\n"), out)
self.assertIn("The project's rung found 2 and then 2 of the 2, 100% on average, so a rung qualifies finding 2 or more of them", out)
self.assertIn(f"claude-opus-5-5 at low effort found 1, 50%, and missed 1 such 🔴: it doesn't qualify.\n {self.checkout} 2026-10-14T10:00:00Z: 🔴 a.txt:1 wrong\n", out)
self.assertTrue(out.endswith("qualifies: none below the project's rung\n"), out)
self.assertEqual(set(self.matched_in), {str(self.checkout)})
self.assertTrue(out.startswith("Replayed 1 stability rounds of claude-opus-5-5 projects,"), out)
@@ -334,8 +320,16 @@ class Main(unittest.TestCase):
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"), out)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE, LOW, MIDDLE])
self.assertTrue(out.endswith("qualifies: claude-sonnet-5-5 at high effort\n"), out)
def test_counts_a_failed_replay_on_a_lower_rung_as_finding_nothing(self):
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review=lambda rung: {"type": "result"} if rung == LOW else {"type": "result", "result": f"review on {rung.model} {rung.effort}"})
self.assertEqual(code, 0, err)
self.assertIn(f"replaying 1 prose rounds on {REFERENCE}\n", err)
self.assertIn(f"replaying 1 prose rounds on {LOW}\n", err)
self.assertIn(f"on {LOW} failed: the reviewer replied with no report", err)
self.assertIn("claude-opus-5-5 at low effort found 0, 0%, and missed 1 such 🔴: it doesn't qualify.", out)
def review_folder_with_round_1(self):
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
@@ -388,8 +382,9 @@ class Main(unittest.TestCase):
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: the prompt names the review folder in a spelling the replay does not redirect", err)
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
self.assertIn(f"on {REFERENCE} failed: the prompt names the review folder in a spelling the replay does not redirect", err)
self.assertIn("Left out 1 more, which a replay on the project's rung failed on", out)
self.assertTrue(out.endswith("No rung tried: fewer than 1 rounds were replayed on the project's rung without a failure.\n"), out)
def test_replays_a_round_whose_prompt_names_an_input_written_before_it_began_naming_the_copy(self):
folder = self.review_folder_with_round_1()
@@ -408,9 +403,9 @@ class Main(unittest.TestCase):
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
self.assertIn(f"on {REFERENCE} failed: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
def test_finds_nothing_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
def test_fails_the_replay_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
folder = self.review_folder_with_round_1()
(folder / "stability-round-1.md").chmod(0)
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
@@ -419,7 +414,7 @@ class Main(unittest.TestCase):
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: could not prepare the replay: ", err)
self.assertIn(f"on {REFERENCE} failed: could not prepare the replay: ", err)
self.assertEqual(list(scratch.iterdir()), [], "the clone is removed")
self.assertEqual([path.name for path in folder.parent.parent.iterdir()], ["code"], "the copy is removed")
@@ -429,6 +424,24 @@ class Main(unittest.TestCase):
self.assertEqual(code, 0, err)
self.assertTrue(out.startswith("Replayed 2 stability rounds"), out)
def test_leaves_out_a_round_that_either_replay_on_the_project_rung_failed_on(self):
self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z")
self.enterContext(unittest.mock.patch.object(search, "AT_ONCE", 1))
# One round at a time, three tries on a round reply with no report: the first replay's on its first round, then the second replay's on its first, after the first replay's two reviews. Every other review replies.
for failing in (range(3), range(2, 5)):
with self.subTest(failing=failing):
calls = iter(range(100))
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review=lambda rung: {"type": "result"} if next(calls) in failing else {"type": "result", "result": f"review on {rung.model} {rung.effort}"})
self.assertEqual(code, 0, err)
self.assertTrue(out.startswith("Replayed 1 prose rounds"), out)
self.assertIn("Left out 1 more", out)
def test_tries_no_lower_rung_where_the_project_rung_found_nothing(self):
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": []})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE])
self.assertTrue(out.endswith("No rung tried: the project's rung found too few of them to hold a rung to.\n"), out)
def test_checks_out_the_commit_detached_when_the_reviewer_started_on_the_default_branch(self):
self.set_branch("main")
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
@@ -446,12 +459,14 @@ class Main(unittest.TestCase):
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
self.assertEqual(self.reviews[0][1:4], ("s\n", "x\n", "0\n"))
def test_finds_nothing_in_a_round_whose_review_has_no_report(self):
def test_leaves_out_a_round_whose_review_on_the_project_rung_has_no_report(self):
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 3)
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} found nothing: the reviewer replied with no report", err)
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
# Each of the two replays tries claude three times.
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 6)
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} failed: the reviewer replied with no report", err)
self.assertIn("Left out 1 more, which a replay on the project's rung failed on", out)
self.assertTrue(out.endswith("No rung tried: fewer than 1 rounds were replayed on the project's rung without a failure.\n"), out)
def assert_no_round(self):
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
@@ -491,7 +506,7 @@ class Main(unittest.TestCase):
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
self.assertEqual(code, 1)
self.assertIn("usage limit: You've hit your limit", err)
self.assertIn("review-replay: claude hit a usage limit: You've hit your limit", err)
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
with self.subTest(argv=argv):
self.assertEqual(self.run_main(argv, unused)[0], 1)
+4 -10
View File
@@ -1,7 +1,7 @@
"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages."""
import dataclasses
from claude_code.entries import usage_count
from claude_code.tokens import tokens_of
@dataclasses.dataclass(frozen=True)
@@ -31,16 +31,10 @@ PRICES = {
}
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
def listed(model: str, usage: object) -> float:
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
price = PRICES.get(model)
if not price or not isinstance(usage, dict):
if not price:
return 0.0
written = usage.get("cache_creation")
# A write without the split by lifetime counts as a five-minute one.
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
return (
usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h
+ usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output
) / 1_000_000
tokens = tokens_of(usage)
return (tokens.input * price.input + tokens.write_5m * price.write_5m + tokens.write_1h * price.write_1h + tokens.read * price.read + tokens.output * price.output) / 1_000_000
+1 -1
View File
@@ -1,4 +1,4 @@
"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
"""Replay archived cases on a rung, as judge-replay and review-replay both do; and judge-replay's rung search, which holds each candidate rung to what a reference rung reproduced."""
import concurrent.futures
import dataclasses
import sys
+27 -6
View File
@@ -77,9 +77,15 @@ Then, newest first, each finished chunk's later fixes, naming the fixing chunks,
that has any, then how many have none: the defects that reappear in what already shipped, the
other half of that counter-signal.
Then, newest first, how many of the human's typed answers each finished chunk's judge quoted as
reversing a choice the worker took on its own recommendation, for every chunk loop-claude finished
that has any, then how many have none: how often a choice the worker took on its own recommendation
fails to hold. It reads loop-claude's archive, and counts only chunks whose verdicts record a
Config line, since earlier judges didn't look for reversals.
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
left out.
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors or
loop-claude's archive cannot be read.
"""
import functools
import os
@@ -95,6 +101,8 @@ from score_outcomes.results import file_lines, fixed_later, item_text, misreads,
from release_plan.todo_table import item_details, LEVELS, risk, TOP_SCORE
from records.markdown_text import listed
from release_plan.named_code import named_files
from transcript_archive.location import project_archive
from score_outcomes.reversals import reversal_lines
# The scores score-outcomes takes, in order.
GIVEN = ("L", "E", "I", "S")
@@ -127,12 +135,16 @@ def main(argv: list[str]) -> int:
if isinstance(results, Failure):
return failed(results)
anchored = read_anchors()
print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
return failed(anchored) if isinstance(anchored, Failure) else 0
reversal = read_reversals()
print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None, reversal))
unread = [found for found in (anchored, reversal) if isinstance(found, Failure)]
for failure in unread:
failed(failure)
return 1 if unread else 0
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings, then its later fixes."""
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None, reversal: list[str] | Failure) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings, then its later fixes, then its reversals, as reversal_lines gives them."""
sections = []
if given is not None:
r = risk(given["L"], given["E"], given["I"])
@@ -142,6 +154,7 @@ def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
sections.append(["🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:", "", *misreads(results)])
sections.append(["Later fixes: the chunks that fixed code each finished chunk shipped, newest first:", "", *fixed_later(results)])
sections.append(["Reversals: the human's typed answers that reversed a choice the worker took on its own recommendation, per chunk loop-claude finished, newest first:", "", *([f"- None: {reversal.reason}"] if isinstance(reversal, Failure) else reversal)])
if any(result.landing != "merge" for result in results):
sections.append(UNMERGED)
return "\n\n".join("\n".join(section) for section in sections)
@@ -165,6 +178,14 @@ def read_anchors() -> Anchors | Failure:
return Failure(f"cannot read {ANCHORS_PATH}: {failure}")
def read_reversals() -> list[str] | Failure:
"""The reversals in loop-claude's archive of this project, which the main checkout's path keys, whichever worktree this runs in."""
common = git("rev-parse", "--path-format=absolute", "--git-common-dir")
if isinstance(common, Failure):
return common
return reversal_lines(project_archive(str(pathlib.Path(common.strip()).parent), pathlib.Path.home(), os.environ))
def read_results(default: str) -> list[Result] | Failure:
"""What each chunk on the default branch's first-parent line measured."""
if partial := full_history():
+42
View File
@@ -0,0 +1,42 @@
"""The human's reversals of choices workers took on their own recommendation, per finished chunk in loop-claude's archive. docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, in its entry of 2026-11-08, is valid while they stay few."""
import json
import pathlib
from transcript_archive.read import chunk_outcomes, finished_chunks
from transcript_archive.outcomes import CONFIG, reversals, workers
from failure import Failure
from score_outcomes.results import plural
def reversal_lines(project_archive: pathlib.Path) -> list[str] | Failure:
"""Newest first, each finished chunk the judge looked for reversals in, with how many distinct answers it quoted as reversing, then how many had none. The judge looks for them from the release that records a Config line beside each verdict, so a chunk without one is left out."""
chunks = finished_chunks(project_archive)
if isinstance(chunks, Failure):
return chunks
counted = []
for chunk in reversed(chunks):
texts = []
for path in chunk_outcomes(project_archive / chunk.folder):
try:
texts.append(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive file {path}: {failure}")
if any(f"\n{CONFIG}" in text for text in texts):
# The judge quotes the latest reversal at each ruling, so one answer may be quoted many times.
found = dict.fromkeys(quote for text in texts for quote in reversals(text))
counted.append((f"{chunk.finished}{item_of(texts)}", len(found)))
if not counted:
return ["- None: loop-claude's archive holds no finished chunk whose verdicts record a Config line."]
lines = [f"- {chunk}: {count} reversed" for chunk, count in counted if count]
others = len(counted) - len(lines)
return lines + ([f"- {'The other' if lines else 'All'} {plural(others, 'finished chunk')}: none."] if others else [])
def item_of(texts: list[str]) -> str:
"""`, item <ID>` for the item the chunk's latest worker line routes it by; empty where none does."""
named = sorted(stamped for text in texts for stamped in workers(text))
try:
item = json.loads(named[-1][1]).get("item") if named else None
except (ValueError, AttributeError):
item = None
return f", item {item}" if isinstance(item, int) and not isinstance(item, bool) and item else ""
+80 -12
View File
@@ -14,7 +14,10 @@ from score_outcomes.results import file_lines, NamedCode, nearest, rank_correlat
from review_rules.round_titles import Findings
from test_env import isolated_env
from release_plan.todo_table import Item
from transcript_archive import outcomes
from transcript_archive.location import project_archive
from score_outcomes.main import report_text
from score_outcomes.reversals import reversal_lines
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
@@ -193,7 +196,7 @@ class ReportText(unittest.TestCase):
def test_lists_the_nearest_by_r_then_the_anchors_then_the_medians(self):
found = [result(1, 5, 3, None, merged="2026-10-13T10:00:00Z"), result(2, 1, 3, None, merged="2026-10-12T10:00:00Z")]
too_few = "such chunks record"
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}, ["- None: loop-claude's archive holds no finished chunk whose verdicts record a Config line."]), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
- Item 1, R 5, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 1.**
@@ -217,40 +220,44 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
Later fixes: the chunks that fixed code each finished chunk shipped, newest first:
- None: no later chunk fixed code a finished chunk shipped.""")
- None: no later chunk fixed code a finished chunk shipped.
Reversals: the human's typed answers that reversed a choice the worker took on its own recommendation, per chunk loop-claude finished, newest first:
- None: loop-claude's archive holds no finished chunk whose verdicts record a Config line.""")
def test_lists_each_chunks_findings_with_their_misread_count_newest_first_once_per_chunk(self):
found = [result(1, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,)), result(2, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,)), result(3, 5, 3, None, findings=(0, 4), misread=0, merge="ccccccc", merged="2026-10-14T10:00:00Z", landing="rebase"), result(4, 5, 3, None)]
self.assertIn("""🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
- 2026-10-14T10:00:00Z in ccccccc: at least 0 🔴, 4 🟡 (0 misread)
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None))
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None, []))
def test_lists_each_chunks_later_fixes_newest_first_once_per_chunk_then_counts_the_others(self):
found = [result(1, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,), fixed_by=("ddddddd",)), result(2, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,), fixed_by=("ddddddd",)), result(3, 5, 3, None, merge="ccccccc", merged="2026-10-14T10:00:00Z", fixed_by=("eeeeeee", "ddddddd")), result(4, 5, 3, None), result(5, 5, 3, None, merge="fffffff")]
self.assertTrue(report_text(found, [], None).endswith("""Later fixes: the chunks that fixed code each finished chunk shipped, newest first:
self.assertIn("""Later fixes: the chunks that fixed code each finished chunk shipped, newest first:
- 2026-10-14T10:00:00Z in ccccccc: 2 later fixes, by eeeeeee and ddddddd
- 2026-10-12T10:00:00Z in bbbbbbb: 1 later fix, by ddddddd
- The other 2 finished chunks: none."""))
- The other 2 finished chunks: none.""", report_text(found, [], None, []))
def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self):
text = report_text([result(1, 5, 3, None, landing="rebase")], [], None)
text = report_text([result(1, 5, 3, None, landing="rebase")], [], None, [])
self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1])
self.assertIn("a pull request that shipped nothing adds its lines, files and rounds", text)
self.assertIn("at least what history shows, and the medians count the rebased ones as shown.", text)
self.assertIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None, landing="push")], [], None))
self.assertNotIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None)], [], None))
self.assertIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None, landing="push")], [], None, []))
self.assertNotIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None)], [], None, []))
def test_leaves_a_never_replayed_chunk_out_of_the_s_medians_and_keeps_a_rebased_one(self):
found = [result(id_, 2, 2, None, lines=10 * id_, landing="rebase" if id_ == 1 else "merge") for id_ in range(1, 11)]
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [result(11, 2, 2, None, lines=100000, landing="push")], [], None))
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [result(11, 2, 2, None, lines=100000, landing="push")], [], None, []))
def test_leaves_a_never_replayed_chunk_out_of_the_r_medians_and_the_rank_correlations(self):
levels = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
found = [result(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
pushed = result(11, 2, 2, None, rounds=9, findings=(9, 0), levels={"L": 1, "E": 2, "I": 1}, landing="push")
text = report_text(found + [pushed], [], None)
text = report_text(found + [pushed], [], None, [])
self.assertIn("- R, 🔴 findings: 2 → 2.5 (10 chunks)", text)
self.assertIn("- L, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", text)
self.assertIn("- I, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", text)
@@ -258,7 +265,7 @@ Later fixes: the chunks that fixed code each finished chunk shipped, newest firs
def test_keeps_a_never_replayed_chunk_in_the_nearest_and_anchors_lists(self):
pushed = result(9, 2, 3, None, landing="push")
text = report_text([pushed], [("L 1", (9,))], {"L": 1, "E": 1, "I": 1, "S": 3})
text = report_text([pushed], [("L 1", (9,))], {"L": 1, "E": 1, "I": 1, "S": 3}, [])
nearest_section, anchors_section = text.split("Anchors in ")
self.assertIn("- Item 9, R 2, S 3:", nearest_section)
self.assertIn("never replayed", nearest_section)
@@ -266,7 +273,7 @@ Later fixes: the chunks that fixed code each finished chunk shipped, newest firs
self.assertIn("never replayed", anchors_section.split("Median outcome")[0])
def test_lists_no_nearest_items_where_no_scores_are_given(self):
self.assertTrue(report_text([], [], None).startswith("Anchors in docs/score-anchors.md"))
self.assertTrue(report_text([], [], None, []).startswith("Anchors in docs/score-anchors.md"))
class ScoreOutcomesTool(unittest.TestCase):
@@ -305,6 +312,23 @@ class ScoreOutcomesTool(unittest.TestCase):
def run_tool(self, *args, cwd=None):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True)
def test_counts_the_reversals_in_loop_claudes_archive_of_the_main_checkout_run_from_a_worktree(self):
archive = pathlib.Path(self.env["HOME"], "archive")
self.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(archive)
chunk_file(project_archive(str(self.checkout), pathlib.Path(self.env["HOME"]), self.env), "a", ("2026-11-02T10:00:00Z", outcomes.finished('{"model": "m", "item": 4}', "e", "j", annotation=outcomes.Annotation("c", reversed="No."))))
worktree = pathlib.Path(self.env["HOME"], "proj-item-4")
self.git("worktree", "add", "-q", str(worktree))
ran = self.run_tool(cwd=worktree)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertTrue(ran.stdout.endswith("newest first:\n\n- 2026-11-02T10:00:00Z, item 4: 1 reversed\n"), ran.stdout[-400:])
unreadable = next(archive.rglob("a.outcomes.md"))
unreadable.write_bytes(b"\xff")
ran = self.run_tool()
self.assertEqual(ran.returncode, 1)
self.assertIn("Later fixes:", ran.stdout)
self.assertTrue(ran.stdout.endswith(f"newest first:\n\n- None: could not read the archive file {unreadable}: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte\n"), ran.stdout[-400:])
self.assertEqual(ran.stderr, f"score-outcomes: could not read the archive file {unreadable}: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte\n")
def test_measures_each_merged_chunk_that_removed_an_item(self):
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)})
@@ -467,5 +491,49 @@ class ScoreOutcomesTool(unittest.TestCase):
self.assertIn("usage: score-outcomes [L E I S]", ran.stderr)
def chunk_file(archive, folder, *stamped):
(archive / folder).mkdir(parents=True)
(archive / folder / "a.outcomes.md").write_text("Task: Do it.\n\n" + "".join(f"{stamp} {outcome}\n\n" for stamp, outcome in stamped))
class Reversals(unittest.TestCase):
def test_counts_each_chunks_distinct_reversals_newest_first_only_where_its_verdicts_record_a_config(self):
worker = '{"model": "m", "item": 7}'
with tempfile.TemporaryDirectory() as root:
archive = pathlib.Path(root)
self.assertEqual(reversal_lines(archive), ["- None: loop-claude's archive holds no finished chunk whose verdicts record a Config line."])
chunk_file(archive, "old", ("2026-11-01T10:00:00Z", outcomes.finished(worker, "e", "j", annotation=outcomes.Annotation(reversed="No."))))
chunk_file(archive, "reversed", ("2026-11-02T10:00:00Z", outcomes.unfinished(worker, "e", "j", "", annotation=outcomes.Annotation("c", reversed="No."))), ("2026-11-02T11:00:00Z", outcomes.unfinished(worker, "e", "j", "", annotation=outcomes.Annotation("c", reversed="No."))), ("2026-11-02T12:00:00Z", outcomes.finished(worker, "e", "j", annotation=outcomes.Annotation("c", reversed="Use X."))))
chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", annotation=outcomes.Annotation("c"))))
self.assertEqual(reversal_lines(archive), ["- 2026-11-02T12:00:00Z, item 7: 2 reversed", "- The other 1 finished chunk: none."])
def test_adds_no_line_for_the_others_where_every_chunk_holds_a_reversal(self):
with tempfile.TemporaryDirectory() as root:
chunk_file(pathlib.Path(root), "a", ("2026-11-02T10:00:00Z", outcomes.finished('{"model": "m", "item": 7}', "e", "j", annotation=outcomes.Annotation("c", reversed="No."))))
self.assertEqual(reversal_lines(pathlib.Path(root)), ["- 2026-11-02T10:00:00Z, item 7: 1 reversed"])
def test_says_all_chunks_have_none_and_names_no_item_the_worker_line_lacks(self):
with tempfile.TemporaryDirectory() as root:
archive = pathlib.Path(root)
chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m", "item": 7}', "e", "j", annotation=outcomes.Annotation("c"))))
self.assertEqual(reversal_lines(archive), ["- All 1 finished chunk: none."])
for worker in ('{"model": "m"}', '{"model": "m", "item": true}', '["m"]', "not json"):
with self.subTest(worker=worker):
chunk_file(archive, "reversed", ("2026-11-04T10:00:00Z", outcomes.finished(worker, "e", "j", annotation=outcomes.Annotation("c", reversed="No."))))
self.assertEqual(reversal_lines(archive), ["- 2026-11-04T10:00:00Z: 1 reversed", "- The other 1 finished chunk: none."])
(archive / "reversed" / "a.outcomes.md").unlink()
(archive / "reversed").rmdir()
def test_says_which_archive_it_could_not_read(self):
with tempfile.TemporaryDirectory() as root:
archive = pathlib.Path(root)
chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished("w", "e", "j", annotation=outcomes.Annotation("c"))))
(archive / "kept" / "b.outcomes.md").write_bytes(b"\xff")
found = reversal_lines(archive)
self.assertIsInstance(found, Failure)
self.assertTrue(found.reason.startswith(f"could not read the archive file {archive / 'kept' / 'b.outcomes.md'}: "), found.reason)
if __name__ == "__main__":
unittest.main()
+2
View File
@@ -12,6 +12,8 @@
- <sha256>.jsonl is a copy of the session's transcript, named by the hash of its bytes, so each distinct
transcript is kept once.
- <sha256>.outcomes.md sits beside the copy and holds the task, then each outcome opened by its UTC time (outcomes.py).
A verdict, an interrupt or a quoted answer also records the setup that ran it, what was spent since the
previous outcome that recorded a spend, and any reversal the judge quoted (outcomes.Annotation).
- session/ holds every other file of the session, such as the subagents' transcripts, which Claude
Code keeps in a folder named after the session, beside the transcript. A file there is replaced only by a version that
grew from it. A file Claude Code rewrote whole lands beside its copy as <name>.<hash of its content>
+57 -13
View File
@@ -1,4 +1,5 @@
import re
import typing
from records.markdown_text import quoted
from records.utc_stamp import STAMPED
@@ -28,13 +29,52 @@ JUDGE_COST = "Judge cost: "
JUDGE_COST_AT = re.compile(rf"^{re.escape(JUDGE)}(.+)\n{re.escape(JUDGE_COST)}([0-9.]+)$", re.MULTILINE)
# The claude-config release and commit that ran the cycle, on the line before JUDGE, such as `Config: v0.8.0 (<sha>)`.
CONFIG = "Config: "
# Opens the block of what the work since the previous outcome that recorded a spend spent; an outcome that spent nothing has none.
SPENT = "Spent since "
# Opens the quote of a typed answer of the human's that reversed a choice the worker took on its own recommendation.
REVERSED = "Reversed:"
REVERSED_AT = re.compile(rf"^{re.escape(REVERSED)}\n((?:> .*\n)*> .*)", re.MULTILINE)
class Annotation(typing.NamedTuple):
"""What a verdict, an interrupt or a quoted answer records beside its judge lines, so a change to the setup can be judged before and after: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`. Each part is left out where empty; the cycle always gives config."""
config: str = ""
# The block spend.spent_block renders.
spent: str = ""
# The human's whole typed answer that holds the judge's quote of the reversal, as loop-claude checked it.
reversed: str = ""
def annotation_lines(annotation: Annotation) -> str:
reversed_block = f"{REVERSED}\n{quoted(annotation.reversed)}\n\n" if annotation.reversed else ""
spent_block = f"{annotation.spent}\n\n" if annotation.spent else ""
config_line = f"{CONFIG}{annotation.config}\n" if annotation.config else ""
return f"{reversed_block}{spent_block}{config_line}"
def reversals(outcomes: str) -> list[str]:
"""Each reversing answer the outcomes quote, unquoted, in the order they were written."""
return [unquoted(found[1]) for found in REVERSED_AT.finditer(outcomes)]
def unquoted(block: str) -> str:
return "\n".join(line.removeprefix("> ") for line in block.split("\n"))
def spent_stamps(outcomes: str) -> list[str]:
"""The UTC stamp of each outcome that records a spend, in the order they were written."""
return [stamp for stamp, outcome in each_outcome(outcomes) if f"\n{SPENT}" in outcome]
def judge_lines(judge: str, judge_cost: float) -> str:
"""The judge's rung, and what its run cost where that is known."""
return f"{JUDGE}{judge}" + (f"\n{JUDGE_COST}{judge_cost:.4f}" if judge_cost else "")
def judge_costs(outcomes: str) -> list[tuple[str, float]]:
"""The rung and cost of each judge run the outcomes record a cost for."""
"""The rung and cost of each judge run the outcomes annotation a cost for."""
return [(found[1], float(found[2])) for found in JUDGE_COST_AT.finditer(outcomes)]
@@ -42,26 +82,26 @@ def escalation_block(escalation: str) -> str:
return f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
def finished(worker: WorkerLine, evidence: str, judge: str, judge_cost: float = 0.0) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def finished(worker: WorkerLine, evidence: str, judge: str, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def unfinished(worker: WorkerLine, evidence: str, judge: str, escalation: str, judge_cost: float = 0.0) -> str:
def unfinished(worker: WorkerLine, evidence: str, judge: str, escalation: str, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none."""
escalated = escalation_block(escalation)
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: WorkerLine, judge_cost: float = 0.0) -> str:
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the line naming the route the worker ran on until the interrupt."""
escalated = escalation_block(escalation)
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def answered(*, question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0) -> str:
def answered(*, question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
"""escalation and worker are as on interrupted. Every parameter is keyword-only, since a swap of two str ones would still type-check."""
escalated = escalation_block(escalation)
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def rejected(why: str, reply: str, judge: str, judge_cost: float = 0.0) -> str:
@@ -80,16 +120,20 @@ def stopped(worker: WorkerLine, why: str) -> str:
def workers(outcomes: str) -> list[tuple[str, str]]:
"""The UTC stamp and the worker of each outcome that names one, in the order they were written."""
starts = list(OUTCOME_AT.finditer(outcomes))
found = []
for start, after in zip(starts, [*starts[1:], None]):
outcome = outcomes[start.end():after.start() if after else len(outcomes)].rstrip("\n")
for stamp, outcome in each_outcome(outcomes):
last = outcome.rsplit("\n", 1)[-1]
if outcome.startswith(NAMES_A_WORKER) and last.startswith(WORKER):
found.append((start[1], last.removeprefix(WORKER)))
found.append((stamp, last.removeprefix(WORKER)))
return found
def each_outcome(outcomes: str) -> list[tuple[str, str]]:
"""The UTC stamp and the text after it of each outcome, in the order they were written."""
starts = list(OUTCOME_AT.finditer(outcomes))
return [(start[1], outcomes[start.end():after.start() if after else len(outcomes)].rstrip("\n")) for start, after in zip(starts, [*starts[1:], None])]
def task_of(outcomes: str) -> str | None:
"""The task an outcomes file opens with; None when it opens with none."""
found = TASK_AT.match(outcomes)
+26 -7
View File
@@ -3,7 +3,7 @@ import pathlib
from transcript_archive.location import chunk_folder, FILE_SUFFIX, transcript_of
from failure import Failure
from transcript_archive.outcomes import FINISHED_AT, workers
from transcript_archive.outcomes import FINISHED_AT, spent_stamps, workers
@dataclasses.dataclass(frozen=True)
@@ -18,13 +18,21 @@ class FinishedChunk:
def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure:
found = []
try:
for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()):
copies = sorted((stamps[-1], outcomes) for outcomes in chunk_outcomes(folder) if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))))
if copies:
finished, outcomes = copies[-1]
found.append(FinishedChunk(folder.name, finished, transcript_of(outcomes), sorted(folder.glob("session/*/subagents/*.jsonl"))))
except (OSError, UnicodeDecodeError) as failure:
folders = sorted(path for path in project_archive.glob("*") if path.is_dir())
except OSError as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
for folder in folders:
copies = []
for outcomes in chunk_outcomes(folder):
try:
stamps = FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive file {outcomes}: {failure}")
if stamps:
copies.append((stamps[-1], outcomes))
if copies:
finished, outcomes = max(copies)
found.append(FinishedChunk(folder.name, finished, transcript_of(outcomes), sorted(folder.glob("session/*/subagents/*.jsonl"))))
return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder))
@@ -66,3 +74,14 @@ def latest_worker(project_archive: pathlib.Path, transcript: str) -> str | Failu
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return None
def last_spent(project_archive: pathlib.Path, transcript: str) -> str | Failure:
"""The UTC stamp of the latest outcome in the transcript's chunk that records a spend; empty before any. Stamps share one format, so the greatest is the latest."""
try:
with open(transcript, "rb") as handle:
folder = chunk_folder(project_archive, handle.read())
stamps = [stamp for path in chunk_outcomes(folder) for stamp in spent_stamps(path.read_text(encoding="utf-8"))]
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return max(stamps, default="")
@@ -105,6 +105,36 @@ class Outcomes(unittest.TestCase):
self.assertEqual(read.latest_worker(kept, str(transcript)), "w2")
self.assertIsInstance(read.latest_worker(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure)
def test_a_record_quotes_the_reversal_then_the_spend_then_the_config_before_the_judge(self):
record = outcomes.Annotation("v0.8.0 (abc)", "Spent since the chunk began, in tokens of x:\n- worker, m: 1", "No, keep it.\nUse X.")
self.assertEqual(outcomes.finished("w", "e", "j", annotation=record), "Verdict: finished\n\nEvidence:\n> e\n\nReversed:\n> No, keep it.\n> Use X.\n\nSpent since the chunk began, in tokens of x:\n- worker, m: 1\n\nConfig: v0.8.0 (abc)\nJudge: j\nWorker: w")
self.assertEqual(outcomes.finished("w", "e", "j", annotation=outcomes.Annotation("v0.8.0 (abc)")), "Verdict: finished\n\nEvidence:\n> e\n\nConfig: v0.8.0 (abc)\nJudge: j\nWorker: w")
def test_reads_back_each_reversal_and_the_stamps_of_the_outcomes_that_record_a_spend(self):
spent = outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1", "No, keep it.\nUse X.")
kept = "Task: Do it.\n\n" + "\n".join(f"{utc(NOW + offset)} {outcome}\n" for offset, outcome in enumerate([
outcomes.unfinished("w", "e", "j", "", annotation=spent),
outcomes.stopped("w", "Ctrl-C"),
outcomes.finished("w", "e", "j", annotation=outcomes.Annotation("c", "Spent since x, in tokens of x:\n- judge, m: 1")),
]))
self.assertEqual(outcomes.reversals(kept), ["No, keep it.\nUse X."])
self.assertEqual(outcomes.spent_stamps(kept), [utc(NOW), utc(NOW + 2)])
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w"), (utc(NOW + 1), "w"), (utc(NOW + 2), "w")])
def test_the_last_spend_is_the_latest_outcome_of_the_chunk_that_records_one(self):
with tempfile.TemporaryDirectory() as root:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
self.assertEqual(read.last_spent(kept, str(transcript)), "")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW))
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1))
self.assertEqual(read.last_spent(kept, str(transcript)), utc(NOW))
gone = read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl")))
self.assertIsInstance(gone, Failure)
self.assertTrue(gone.reason.startswith(f"could not read the archive {kept}: "), gone.reason)
class Location(unittest.TestCase):
def test_keys_a_project_by_its_path_under_code_or_else_under_the_root(self):
+26 -10
View File
@@ -15,6 +15,7 @@ Each project principle states one rule that the decisions below apply; their ent
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
@@ -138,6 +139,16 @@ Valid while `~/.claude` is a checkout of this repo.
2026-09-28, lilleman. Serves goals 1 and 3: 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 its outcomes 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: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
2026-11-12, lilleman, todo item 305. Serves goals 1, 1.2 and 1.4. A change to the setup can be judged only by comparing chunks run before it with chunks run after, so each verdict, interrupt and quoted answer in loop-claude's archive records three things beside its judge lines.
- `Config: <release> (<commit>)`: `git describe` and the commit of `~/.claude`, so outcomes group by the setup that produced them. Where git can't tell, it records `unknown` and why, on one line.
- A `Spent since` block: the raw tokens each thread spent, by model and by kind (input, cache write 5m, cache write 1h, cache read, output), then the list prices in force, from `bin/routing_figures/prices.py`. The threads are the worker's main thread, each subagent by its agent type and description, and the judge run that ruled. Each message counts once, by its id. The stretch runs from the previous outcome that recorded a spend, so what a `/talk` or a stopped run spent between rulings is counted once. It keeps tokens, since prices change. The prices recorded beside them give what the stretch cost when it ran. Claude Code doesn't report thinking apart from output, so it is left in output. The judge's tokens come from its json reply's `usage`, until item 303 archives the judge's own transcript.
- A `Reversed:` quote: the human's typed answer that overrides a choice the worker took on its own recommendation and recorded. The judge quotes the latest such `[human]` line; loop-claude keeps the whole typed answer that holds the quote verbatim, and drops a quote no typed answer holds. `score-outcomes` counts the distinct answers per finished chunk. That count is goal 1.2's counter-signal, and the 2026-11-08 entry of `loop-claude: a judge decides each interrupt…` is valid only while it stays low. It counts only chunks that record a Config line, since earlier judges didn't look for reversals.
Valid while score-outcomes reads the reversals from the archive.
## loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
2026-10-27, lilleman's yes to claude's evaluation through todo todo item 231. Serves goal 1.4; its counter-signal, review rounds and unfinished verdicts per chunk, is the check.
@@ -226,7 +237,7 @@ Valid while no published standard sets either number, the reading-cost window st
2026-10-08, lilleman. Serves goal 1.4: run beside the full scan, `/security-review` started seconds apart from it each round and returned a near-identical report. Valid while the full scan covers what `/security-review` reports.
## review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none
## review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none; the stability pass doesn't rerun on a round's fixes where every 🔴 and 🟡 of that round asked only that a named mutant be killed or a named failing test pass, and the tests and the mutation command run clean on the fixes
2026-10-08, lilleman. Serves goal 1.4. An audit of the four costliest archived chunks found nearly every finding that mattered in a pass's first round; when every fix, a nit's included, re-entered review, later rounds mostly re-checked the last fix, reworded what an earlier round wrote, or contradicted another round on the same line. A round 2 caught real bugs only where a fix changed behaviour, so stability still reruns on every fix that does, and security on every fix that opens an untrusted-input boundary or touches authn/authz, secrets or crypto. Valid while round-2 reviews of nit and prose fixes keep changing nothing a user would notice.
@@ -234,6 +245,8 @@ Valid while no published standard sets either number, the reading-cost window st
2026-10-29, lilleman. Serves goals 1.4 and 1.5. A 🟡 fix no longer reruns its pass. One project's chunk on 2026-10-29, a README paragraph and plan rows, took 10 review rounds in 45 minutes, and three of its four second rounds answered only 🟡 findings, such as the wording of a question's options. Round 2 found 12 🔴 in about 200 runs since 2026-10-21, mostly in round 1's fixes of 🔴 findings, so a 🔴 fix still reruns its pass. A 🟡 fix that breaks something merges unreviewed by its pass; another pass whose row it meets for a 🔴 fix in the same round still reviews it. Valid while 🔴 findings in later chunks, fixing code a 🟡 fix wrote, stay rare.
2026-11-12, lilleman through todo item 308. Serves goal 1.4. Since the worker runs the mutation command before each stability round, a finding that asks only that a named mutant be killed or a named failing test pass has an answer a run can check. The archive from 2026-09-30 to 2026-11-12 holds 325 stability reports of round 2 or later, from 13 projects, and 81 of those reports open with BLOCK. For each of the 325, the 🔴 and 🟡 lines of the round before were matched on mutant and test-failure wording. In 4 rounds before, every such line matched; read by hand, 1 of the 4 asked only that a failing test pass, and the round 2 after each of the 4 approved. So none of the 81 BLOCKs fell in a round this skips. The skip needs every 🟡 to be of that kind too: in one chunk on 2026-11-12, round 1's only 🔴 was a red suite, and round 2 blocked on a 🟡 whose answer was wrong, which no test or mutant showed. A fix may not edit the named failing test, since a test made to pass that way shows nothing. Fixes from such a round still rerun every other pass whose row they meet. Valid while code that such a skipped round's fixes wrote is rarely what a later chunk's 🔴 findings fix.
## review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review
2026-10-29, lilleman. Serves goals 1.4 and 1.5. One project's chunk on 2026-10-29 changed a README paragraph, `todo.md` and three lines of `gate.yml`, and the principles, security and stability passes all ran on it, each twice: 6 of the chunk's 10 rounds. A change to config is one that changes what runs, so a comment in it fires only the prose pass, as a comment in code already did. A branch that changes only Markdown no agent follows changes no code, config or tests, so no pass that reads those runs on it. A plan row a chunk files from a finding, re-scores or moves is read by the chunk that ships it, so reviewing it at filing reviewed it twice: that chunk spent a prose round of 4 minutes on its plan change. Markdown an agent follows, such as a skill, is config, since a change there changes what agents do. Valid while defects in prose-only chunks stay rare in later chunks' fixes.
@@ -374,27 +387,30 @@ Only chunks run below the project's rung can prove that a cheaper worker holds q
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung while it runs above the project's: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. loop-claude scores each item the worker names on its `Chunk items:` line by `todo.md` (`routing: loop-claude reads the items a chunk takes`), routes on their highest E + I from the next cycle, and archives it with the route so a rerun keeps it.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. loop-claude scores each item the worker names on its `Chunk items:` line by `todo.md` (`routing: loop-claude reads the items a chunk takes`), routes on their highest E + I from the next cycle, and archives it with the route so a rerun keeps it.
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
2026-10-29, lilleman. Serves goals 1.4 and 1.5. A branch that changes only Markdown no agent follows reviews on the project's rung, whatever its items' E + I. E + I scores an item before its chunk starts, by the change the item asks for, so one project's item, filed to build a control on a CI runner, kept its E + I of 7 when the chunk found no control the repo could build and shipped a README paragraph: five reviewers read prose on Opus 5.5 at xhigh. rule-hook's `reviewer-rung` reads the branch's files, committed or not, against the default branch as last fetched. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` and files under `agents/`, `principles/`, `rules/` or `skills/`. On 2026-11-04 lilleman added the workflow bench's prompts, which an agent follows like a skill. `bin/review_rules/review_passes.py` holds the lists, and the worker's prompt renders them. Valid while a README or docs defect costs a reader no more than review on the project's rung lets through.
## routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
## routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay, and misses no 🔴 that both of the project's rung's replays found; and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it misses nothing.
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. On 2026-11-11 lilleman approved the bar below, as somewhat risky, with a close evaluation a release later: `todo.md` item 321. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it finds nearly as much.
`bin/review-replay <pass> <model>` replays a pass's archived rounds on the code each reviewed. It replays them first on the project's rung, then on each rung below it, highest first, down to the ladder's lowest. It stops at the first rung that misses a finding the project's rung found again. A rung qualifies only where it and each rung above it find every such 🔴 and 🟡.
`bin/review-replay <pass> <model>` replays a pass's archived rounds on the code each reviewed, twice on the project's rung. A rung below qualifies where its replay finds at least the mean share of the archived findings that those two replays found, less 10 percentage points, over at least 8 rounds, and misses no 🔴 that both found. The tool tries the project's model at each lower effort first, since the ladder leaves those out, then each ladder rung below, highest first. It stops at the first rung that doesn't qualify.
A qualifying rung applies only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there the pass runs on that rung, even below the worker's. Otherwise the pass runs where every other pass does: the replay compared reviews on the project's rung only, never reviews on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. No code lowers a pass while no rung qualifies: on 2026-11-04 lilleman had the release review of 0.6.0 delete that code, which no chunk could reach. The chunk that first qualifies a rung, `todo.md` item 196's, writes that code again in `bin/model_routing/`. It records the qualifying rung for each pass and project model, and names the lowered pass in the worker's prompt and in rule-hook's `reviewer-rung`.
The bar used to be every finding the project's rung found again. But the project's rung itself found only 69 to 73% of its own findings again, so a reviewer exactly as good failed that bar, and so would the project's rung on a second replay. The margin of 10 points allows for that spread: in the latest run below, the project's rung's two replays found 41 and 43 of the same 55 findings, 4 points apart. A missed 🔴 still fails a rung, since a 🔴 that both replays found is no matter of chance.
A qualifying rung applies only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there the pass runs on that rung, even below the worker's. Otherwise the pass runs where every other pass does: the replay compared reviews on the project's rung only, never reviews on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. No code lowers a pass while no rung qualifies: on 2026-11-04 lilleman had the release review of 0.6.0 delete that code, which no chunk could reach. The chunk that first qualifies a rung writes that code again in `bin/model_routing/`. It records the qualifying rung for each pass and project model, and names the lowered pass in the worker's prompt and in rule-hook's `reviewer-rung`. For a rung off the ladder, such as the project's model at a lower effort, that chunk also sets the `effort` key in the reviewer's frontmatter under `agents/`, which sets the effort per reviewer.
The runs, each on the latest 10 rounds of Opus 5.5 projects that hold a 🔴 or 🟡:
- 2026-10-15, stability: 40 findings, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴. No rung qualifies.
- 2026-10-18, prose: 39 findings. The project's rung found 27 of them again. Sonnet 5.5 at high missed 12 of those 27. No rung qualifies.
- 2026-10-18, stability again, since that day's change to the reviewer prompts expired the first run: 29 findings. The project's rung found 20 of them again. Sonnet 5.5 at high missed 11 of those 20, 1 of them 🔴. No rung qualifies.
- 2026-10-15, stability, under the old bar: 40 findings, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴. No rung qualifies.
- 2026-10-18, prose, under the old bar: 39 findings. The project's rung found 27 of them again. Sonnet 5.5 at high missed 12 of those 27. No rung qualifies.
- 2026-10-18, stability again, under the old bar, since that day's change to the reviewer prompts expired the first run: 29 findings. The project's rung found 20 of them again. Sonnet 5.5 at high missed 11 of those 20, 1 of them 🔴. No rung qualifies.
- 2026-11-12, prose, under the new bar: 8 rounds, 55 findings, after 2 more rounds failed on the project's rung. The project's rung found 41 and then 43 of them, 76%, so the bar was 66%. Opus 5.5 at low effort found 27, 49%, and missed no 🔴 that both replays found. No rung qualifies, and Sonnet 5.5 at high was not tried.
The prose pass went first: a missed prose finding breaks no behaviour, and a later change fixes it cheaply. Sonnet 5.5 missed 44 to 55% of what the project's rung found again, in the prose pass as in both stability runs. Nothing suggests the other passes' findings are easier to find. So the architecture, principles, overrides and product-owner passes are not replayed yet: a replay would spend money with little chance of a qualifying rung (goal 1.4). `todo.md` item 196 keeps their replays in the plan. Every pass runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer.
The prose pass went first under the new bar: a missed prose finding breaks no behaviour, and a later change fixes it cheaply. Sonnet 5.5 missed 44 to 55% of what the project's rung found again, in the prose pass as in both stability runs, so it is unlikely to reach the new bar either; and Opus 5.5 at low, the likeliest rung, fell 17 points short on the pass whose misses cost least. The architecture, principles, overrides and product-owner passes are not replayed yet: `todo.md` item 196 keeps their replays in the plan.
Valid until a new model joins the ladder, which calls for a replay of every pass, or a pass's reviewer prompt changes, which calls for a replay of that pass.
+34
View File
@@ -1771,3 +1771,37 @@ Read most (opens and searches):
- `bin/release_plan/test_ranking.py` 2
- `bin/todo_item/main.py` 2
- `skills/larv-review/SKILL.md` 2
## Reading cost, chunk f1f5d123e494, finished 2026-11-12T08:38:23Z
114937 new input tokens before the first commit.
Read most (opens and searches):
- `todo.md` 11
- `docs/decisions.md` 2
- `skills/larv-review/SKILL.md` 2
- `README.md` 1
- `bin/failure.py` 1
- `bin/larv_review/main.py` 1
- `bin/reading-cost` 1
- `bin/subagent_rung/main.py` 1
- `bin/subagent_rung/test_subagent_rung.py` 1
- `ci.sh` 1
## Reading cost, chunk ae13d485e994, finished 2026-11-12T10:25:08Z
97469 new input tokens before the first commit.
Read most (opens and searches):
- `bin/review_replay/test_review_replay.py` 15
- `bin/review_replay/main.py` 11
- `docs/decisions.md` 9
- `todo.md` 7
- `README.md` 4
- `bin/model_routing/ladder.py` 4
- `bin/review_replay/rounds.py` 4
- `bin/review_replay/test_recall.py` 3
- `CHANGELOG.md` 2
- `skills/larv-review/SKILL.md` 2
+4 -2
View File
@@ -82,10 +82,10 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
- **Round.** A round is one review by a pass's reviewer: the first and each re-entry. The rerun after the architect returns Stage 0 questions ("Architecture" below) and a relaunch one rung up ("Rung up" below) stay in their round.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts, up to the cap, a round. Its count is the number of its reviews on the PR, less its reviews of a `Record the comprehension check:` commit, and `round-count` doesn't list it. A commit that answers one of its rounds takes an ordinary title, not an `Answer <pass> round` one, and a round that didn't change anything gets no commit.
- **Count.** Close each round of a pass other than the auto-reviewer with one commit that holds the round's fixes. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); …`: `<pass>` is the pass's name in lower case, such as `full scan`, `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported, and `<j>` is how many of those they marked `[misread]` (review-findings.md → "Misread"); a reviewer that marks none, such as `/security-review`, adds 0. Example: `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. A round that didn't change anything gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. A stability pass whose round's fixes skip the next round per "Re-entry" → "Mechanical answers" is done once that rule's run is clean. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most two rounds per chunk, and the release review's architecture and principles passes five; don't ask the user for more. Answer its last round's findings per "Findings": those fixes merge once the gate passes, unreviewed by that pass. rule-hook's `round-cap` refuses a round commit that would take a pass past its cap, and no override waives it. A review the auto-reviewer posts after its second isn't a round: fix none of it and rerun no pass for it, but file a security finding it raises per `~/.claude/CLAUDE.md` → "Working loop", and any other 🔴 in `todo.md`.
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟡, a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 findings re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4. A pass at its cap doesn't run again ("Round cap" → "Cap").
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟡, a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 findings re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4; "Mechanical answers" below names the one exception. A pass at its cap doesn't run again ("Round cap" → "Cap").
| The fix | Reruns |
|---------|--------|
@@ -98,6 +98,8 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
A fix meets every row it fits. Prose has no row, so a comment or doc edit inside a fix doesn't rerun any pass. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
**Mechanical answers.** A stability round's fixes may skip the next stability round. That holds where the round reported a 🔴, and each of its 🔴 and 🟡 findings asked only that a named mutant be killed or a named failing test pass. Run §2's tests and mutation command on the fixes, and fix again per §2 until they leave no failing test and no surviving mutant that changes behaviour. Each named failing test must pass as the round found it, not edited or deleted. Then the stability pass doesn't run again, and the round's answer commit title ends `; tests and mutants clean at <commit>`. The fixes still rerun each other pass whose row they meet. Where the run can't be made clean, or a fix edits a named failing test, the stability pass runs again as the table says.
**What a round reviews.** An agent under `~/.claude/agents/` reviews the branch in round 1. From round 2 it reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against `standards/quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
+9 -34
View File
@@ -14,9 +14,6 @@
|---|---|---|---|---|---|---|---|---|---|---|---|
| 340 | 0.9.0 | | question | **Decide whether a reviewer may start without `CLAUDE.md` where its replay misses no more findings than an unchanged replay does.** | 2 | 2 | 3 | 5 | 4 | 1.4 by 5 | 1.7 |
| 331 | 0.9.0 | | question | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.9 |
| 305 | 0.9.0 | | | **Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4, 1.2 by 3 | 1.8 |
| 318 | 0.9.0 | | | **Let `review-replay` qualify a rung whose recall is no lower than the project's rung's own replay, and replay Opus 5.5 at low effort on the prose pass.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 5 | 1.7 |
| 308 | 0.9.0 | | | **Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test, both of which the worker now checks before review.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3, 1.5 by 2 | 1.6 |
| 319 | 0.9.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 |
| 309 | 0.9.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 |
| 299 | 0.9.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
@@ -35,7 +32,8 @@
| 338 | 0.10.0 | | owner | **Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 |
| 288 | 0.10.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 |
| 77 | 0.10.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
| 321 | 0.10.0 | 318 | | **Evaluate the review passes that run on a rung item 318 qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 2.3 |
| 196 | 0.10.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
| 321 | 0.10.0 | 196 | decision | **Evaluate the review passes that run on a rung `review-replay` qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 2.3 |
| 273 | 0.10.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
| 268 | 0.10.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 2.2 |
| 171 | 0.10.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
@@ -52,7 +50,6 @@
| 5 | 0.10.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
| 291 | 0.10.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.4 |
| 156 | 0.10.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
| 196 | 0.10.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
| 260 | 0.10.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
| 51 | 0.10.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
| 201 | 0.10.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
@@ -85,33 +82,11 @@ The architect's 🔀 answer on PR #493 (item 292): four decisions expire "when a
- `review: each pass keeps a reviewer of its own`: the merge trials ran on Opus 5.5 at medium. Reword the "Valid" line to name that rung.
- `review: the principles audit runs only in the release review…`: its trial ran on the project's rung. Reword the line to name that rung.
- `routing: a review pass runs below the project's rung only on a rung that a replay…`: `review-replay` tests only rungs below the project's rung. Have the line expire when those rungs change, the event item 196 names ("until a cheaper model joins the ladder").
- `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay…`: `review-replay` tests only rungs below the project's rung. Have the line expire when those rungs change, the event item 196 names ("until a cheaper model joins the ladder").
- `routing: on a model judge-replay covered, the judge runs…`: the replays tested the project's rung and below, and each rung above it that a review climbs to. Have the line expire when those rungs change.
Recommendation: reword all four as above. They are decisions the repo held before item 292, so the rewording is lilleman's call.
### 305. Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.
Three records the archive lacks, asked for by lilleman on 2026-11-11 after the token research of that day.
1. **The setup that ran.** A verdict names the worker's model, effort and item, but not the `~/.claude` tag and commit the chunk ran under. Judging any change to the setup means comparing chunks before and after a deploy, and deploys lag behind cuts, so timestamps can't tell. Add a line such as `Config: v0.7.0 (<sha>)` to each verdict, interrupt and answer.
2. **Spend in raw tokens.** Record what each cycle spent as raw token counts per model and per kind: input, cache write 5-minute, cache write 1-hour, cache read, output, thinking where known. Do it for the worker's main thread, each subagent (by agent type and description) and the judge. Dollars are derived later from model and tokens; as a secondary bonus, record the price table in force when the spend was made (from `bin/routing_figures/prices.py`), so a later price change doesn't rewrite history. The token research measured this by hand on 2026-11-11 and had to deduplicate cumulative worker snapshots by `message.id`: count each message once.
3. **Reversals.** The decision of 2026-11-08 (item 262) lets a worker take its own recommendation on an unreserved choice "while the human reverses few of the choices workers take", and no tool counts those reversals. Have the judge flag an answer the human typed that overrides a choice the worker took and recorded, and count them per chunk in `score-outcomes` beside later fixes and misread findings. This is the quality signal a cheaper setup could quietly worsen.
Build on item 303's archive layout for the judge's part.
### 318. Let `review-replay` qualify a rung whose recall is no lower than the project's rung's own replay, and replay Opus 5.5 at low effort on the prose pass.
Today a rung qualifies only if it re-finds every finding the project's rung found. The project's rung itself re-finds only 69 to 73% of its own findings on a replay (29 of 40, 27 of 39, 20 of 29), so even a reviewer exactly as good would fail, and "no pass has such a rung" says less than it seems. Qualify a rung when its share of the archived findings is no lower than the project's rung's own replay share, within a margin, over enough rounds, and it misses no 🔴 that both project-rung runs found. Then replay Opus 5.5 at low effort on the prose pass first, the pass whose misses cost least; the `effort` frontmatter key sets it per reviewer.
lilleman approved on 2026-11-11 as somewhat risky, with a close evaluation in the next release: item 321. Revise the decision `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…`, and its title at the head of `docs/decisions.md`.
### 308. Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test, both of which the worker now checks before review.
Rounds past the first cost $846 of the $9,154 the archive measured from 2026-09-30 to 2026-11-11; stability's were $281 over 440 runs. Now that the worker runs `mutate-changes` before each stability round (`skills/larv-review/SKILL.md` §2 → "Mutation tests"), a 🔴 that named a surviving mutant or a failing test has a mechanical answer: a run of `mutate-changes` on the fix shows the mutant killed, or the test passes. A round 2 whose every 🔴 and 🟡 is of that kind needs no reviewer.
Round 2 still matters elsewhere: 53 of 241 archived stability reports of round 2 or later open with BLOCK. So first count, from the archived round 2s, the BLOCKs that a run of `mutate-changes` and the tests on the fix would not have raised, and ship the skip only if none falls in a round it would skip. Evidence: one review round scored F1 0.376 and a second 0.26 to 0.30 with more false positives (arXiv 2603.16244, `claude -p` with Opus 4.6, 30 artifacts). Revise larv-review §3 → "Re-entry" and the decision `review: a fix for a 🔴 reruns the pass that found it…`.
### 319. Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.
On SWE-bench Verified with Haiku 4.5 and Opus 4.7, handing the strong model the weak model's transcript solved 69.2% at $1.61 a task; starting the strong model fresh solved 79.2% at $0.90 (arXiv 2608.24358, The Handoff Tax). A model switch also rereads the whole context uncached (Claude Code prompt caching docs). A worker that steps from Sonnet 5.5 to Opus 5.5 by `--resume` is the raw handoff; an effort-only step within one model keeps the cache and isn't. The escalated subagent, which starts fresh with the trigger's evidence, already follows the pattern that won.
@@ -254,9 +229,13 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan
Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it.
### 321. Evaluate the review passes that run on a rung item 318 qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.
### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.
lilleman, 2026-11-11: item 318's new bar is a risk, so check it closely a release later. Compare the first 20 chunks reviewed on each newly qualified rung with the 20 before: review rounds past the first, 🔴 and 🟡 per chunk, misread findings, and later fixes that `score-outcomes` counts (defects that escaped review). Revert a pass to the project's rung where any of those worsened beyond the spread of the 20 before.
Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay…` records the runs so far. The release review of 0.6.0 deleted the code that lowered a pass, since no rung had qualified; the decision says where it goes back.
### 321. Evaluate the review passes that run on a rung `review-replay` qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.
The prose pass's replay under item 318's new bar, on 2026-11-12, qualified no rung, so this item waits for item 196's replays of the other passes. lilleman, 2026-11-11: that bar is a risk, so check it closely a release later. Compare the first 20 chunks reviewed on each newly qualified rung with the 20 before: review rounds past the first, 🔴 and 🟡 per chunk, misread findings, and later fixes that `score-outcomes` counts (defects that escaped review). Revert a pass to the project's rung where any of those worsened beyond the spread of the 20 before.
### 273. Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.
@@ -368,10 +347,6 @@ The key names the project's session, archive folder and models entry. `project_k
While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/release_plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too.
### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.
Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far. The release review of 0.6.0 deleted the code that lowered a pass, since no rung had qualified; the decision says where it goes back.
### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.