From 3c4cedd3891409a4dae936bd806256eebf45c8a5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 09:57:56 +0100 Subject: [PATCH 1/7] Record with each archived verdict the setup that ran it, what each model spent by kind, and the human's reversals --- CHANGELOG.md | 1 + README.md | 2 +- bin/claude_code/tokens.py | 28 +++ bin/judge_replay/test_judge_replay.py | 2 +- bin/loop_claude/cycle/judge.py | 16 +- bin/loop_claude/cycle/run.py | 36 +++- bin/loop_claude/cycle/spend.py | 94 ++++++++++ bin/loop_claude/loop/main.py | 19 +- bin/loop_claude/test_black_box.py | 23 +-- bin/loop_claude/test_loop_claude.py | 176 ++++++++++++++---- bin/loop_claude/verdicts.py | 25 ++- bin/routing_figures/prices.py | 14 +- bin/score_outcomes/main.py | 27 ++- bin/score_outcomes/reversals.py | 40 ++++ bin/score_outcomes/test_score_outcomes.py | 48 +++-- bin/transcript_archive/__init__.py | 2 + bin/transcript_archive/outcomes.py | 68 +++++-- bin/transcript_archive/read.py | 13 +- .../test_transcript_archive.py | 28 +++ docs/decisions.md | 11 ++ docs/reading-cost.md | 17 ++ todo.md | 11 -- 22 files changed, 587 insertions(+), 114 deletions(-) create mode 100644 bin/claude_code/tokens.py create mode 100644 bin/loop_claude/cycle/spend.py create mode 100644 bin/score_outcomes/reversals.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2abde8d3..a244841c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- loop-claude records beside each verdict, interrupt and quoted answer the claude-config release and commit that ran it, the tokens each thread 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 itself; `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 []` waits for a line in a background job's log or report. diff --git a/README.md b/README.md index f38692cb..9b1e4865 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `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 ` 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 [...]` 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, code health's two counter-signals per chunk, misread findings and later fixes, and the answers that 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] ` 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. diff --git a/bin/claude_code/tokens.py b/bin/claude_code/tokens.py new file mode 100644 index 00000000..527aba6d --- /dev/null +++ b/bin/claude_code/tokens.py @@ -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")) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 86d8715f..0578b86e 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -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): diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index fd6343d3..cbf1b954 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -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 loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict from claude_code.transcript import 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."}) + # Counts the human's reversals of the worker's own choices, the counter-signal of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, its entry of 2026-11-08; score-outcomes lists them per chunk. + reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took itself 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) @@ -164,7 +167,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 +176,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.shown))) + + +def reversal_of(output: object, shown: str) -> str: + """The reply's reversed quote where the transcript holds it verbatim; empty otherwise. verdict_from has checked the field is a str.""" + quote = output.get("reversed") if isinstance(output, dict) else None + return quote if isinstance(quote, str) and verbatim(quote, shown) else "" def cost_of(reply: dict) -> float: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 04a96e53..1f25385a 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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 ()`, 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) + record = record_of(cycle, transcript_path, entries, verdict.judged) + if isinstance(record, Failure): + return Stop(1, record.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, record), 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 record_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: Judged) -> outcomes.Record | 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.Record(cycle.config, spend.spent_block(since, spent), judged.reversed) + + +def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, record: outcomes.Record) -> 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, record=record) + return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, record) 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) + record = entries if isinstance(entries, Failure) else record_of(cycle, transcript_path, entries, verdict.judged) + if isinstance(record, Failure): + return Stop(1, record.reason) + outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, record) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, record) 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)): diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py new file mode 100644 index 00000000..98f37707 --- /dev/null +++ b/bin/loop_claude/cycle/spend.py @@ -0,0 +1,94 @@ +"""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 setup, the spend and the reversals…`. + +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 claude_code.tokens import Tokens, tokens_of +from claude_code.transcript import read_transcript +from failure import Failure +from routing_figures.prices import PRICES +from transcript_archive.outcomes import SPENT + +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) + + +# The outcome's stamp runs to the second, so a message written in the second it was stamped, before it, counts again; the judge runs for seconds after the worker exits, so none is. +def later(timestamp: str, start: datetime.datetime) -> bool: + try: + return moment(timestamp) > start + except ValueError: + return False + + +def subagents(transcript_path: str) -> list[Subagent] | Failure: + """The subagents' transcripts Claude Code keeps beside the worker's: /subagents/agent-.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 {} + kind, description = str(meta.get("agentType") or "subagent"), 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]) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 2590b206..ce60da0d 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -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 . 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 ()`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 ()`. 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())}" diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index c7e85b2c..ded13e00 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -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 , after checking the copy is named by its content hash.""" + """Each archived transcript's outcomes, with every UTC stamp replaced by and every setup version by , 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 ", " ", kept.read_text(), flags=re.MULTILINE) + stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", " ", kept.read_text(), flags=re.MULTILINE) + outcomes[copy.read_text()] = re.sub(r"^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" Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f" Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f" Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) - self.assertIn('"text": "landed-it"', copies[f" Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + self.assertEqual(sorted(copies), [f" Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f" Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: \nJudge: judge-model\nWorker: {OFF_LADDER}\n", f" Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: \nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + self.assertIn('"text": "landed-it"', copies[f" Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: \nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) self.assertIn('"text": "next chunk"', copies[f" 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(' 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 Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes) - self.assertIn(' 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(' Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: \nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes) + self.assertIn(' Verdict: finished\n\nEvidence:\n> four\n\nConfig: \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(' 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 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(' 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(' Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: \nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n 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(' Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nConfig: \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(' 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 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: \nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n 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 Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n 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 Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nConfig: \nJudge: judge-model\nWorker: {OFF_LADDER}\n\n 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: ") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index d5b6879e..9f348cc2 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -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,7 +396,7 @@ 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 ( @@ -450,7 +483,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 +502,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 +515,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 +528,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 +645,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 +1610,81 @@ 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_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)]: + (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"]) + self.assertEqual(spend.spent("", [], found, "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_reversal_the_judge_quotes_verbatim_and_its_tokens(self): + shown = "[human] No, keep the old name.\nworking" + for quoted, kept in [("No, keep the old name.", "No, keep the old 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, ""), 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"], ["tag", "v0.1.0"]): + 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"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})") + + 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 +1747,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 +1798,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 +1991,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", "record.reason", read), ("cycle/run.py", "rule", "1", "failure.reason", read), ("cycle/run.py", "keep_rejection", "1", "unkept.reason", read), + ("cycle/run.py", "close", "1", "record.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), diff --git a/bin/loop_claude/verdicts.py b/bin/loop_claude/verdicts.py index b76f1c6c..95ee9585 100644 --- a/bin/loop_claude/verdicts.py +++ b/bin/loop_claude/verdicts.py @@ -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() + # A typed answer of the human's that reversed a choice the worker took itself, as the judge quoted it; empty for none, and where the quote isn't in the transcript. + 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 diff --git a/bin/routing_figures/prices.py b/bin/routing_figures/prices.py index ecf74a0b..3110a831 100644 --- a/bin/routing_figures/prices.py +++ b/bin/routing_figures/prices.py @@ -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 diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index ca7ec608..14a36072 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -77,8 +77,13 @@ 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, for every chunk loop-claude finished that has any, +then how many have none: goal 1.2's counter-signal. 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 +clone, the default branch or loop-claude's archive cannot be read; or, after the rest of the report, when the anchors are left out. """ import functools @@ -95,6 +100,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 +134,15 @@ 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)) + reversal = read_reversals() + if isinstance(reversal, Failure): + return failed(reversal) + print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None, reversal)) return failed(anchored) if isinstance(anchored, Failure) 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]) -> 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 +152,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, per chunk loop-claude finished, newest first:", "", *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 +176,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(): diff --git a/bin/score_outcomes/reversals.py b/bin/score_outcomes/reversals.py new file mode 100644 index 00000000..2a613fac --- /dev/null +++ b/bin/score_outcomes/reversals.py @@ -0,0 +1,40 @@ +"""The human's reversals of choices workers took on their own, per finished chunk in loop-claude's archive: the counter-signal docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, its entry of 2026-11-08, is valid under.""" +import json +import pathlib + +from failure import Failure +from score_outcomes.results import plural +from transcript_archive.outcomes import CONFIG, reversals, workers +from transcript_archive.read import chunk_outcomes, finished_chunks + + +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): + try: + texts = [path.read_text(encoding="utf-8") for path in chunk_outcomes(project_archive / chunk.folder)] + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read the archive {project_archive}: {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 ` 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 "" diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index 3a92053c..e3ec36d5 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -14,7 +14,9 @@ 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 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 +195,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 +219,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, 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 +264,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 +272,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): @@ -467,5 +473,23 @@ 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", record=outcomes.Record(reversed="No.")))) + chunk_file(archive, "reversed", ("2026-11-02T10:00:00Z", outcomes.unfinished(worker, "e", "j", "", record=outcomes.Record("c", reversed="No."))), ("2026-11-02T11:00:00Z", outcomes.unfinished(worker, "e", "j", "", record=outcomes.Record("c", reversed="No."))), ("2026-11-02T12:00:00Z", outcomes.finished(worker, "e", "j", record=outcomes.Record("c", reversed="Use X.")))) + chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", record=outcomes.Record("c")))) + self.assertEqual(reversal_lines(archive), ["- 2026-11-02T12:00:00Z, item 7: 2 reversed", "- The other 1 finished chunk: none."]) + + if __name__ == "__main__": unittest.main() diff --git a/bin/transcript_archive/__init__.py b/bin/transcript_archive/__init__.py index 8bbb36e1..b167bed5 100644 --- a/bin/transcript_archive/__init__.py +++ b/bin/transcript_archive/__init__.py @@ -12,6 +12,8 @@ - .jsonl is a copy of the session's transcript, named by the hash of its bytes, so each distinct transcript is kept once. - .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 record and any reversal the judge quoted (outcomes.Record). - 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 . diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index bd8872ec..35ea2c91 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -1,4 +1,5 @@ import re +import typing from records.markdown_text import quoted from records.utc_stamp import STAMPED @@ -28,6 +29,45 @@ 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 ()`. +CONFIG = "Config: " +# Opens the block of what the stretch of work since the previous record spent; a record 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 itself. +REVERSED = "Reversed:" +REVERSED_AT = re.compile(rf"^{re.escape(REVERSED)}\n((?:> .*\n)*> .*)", re.MULTILINE) + + +class Record(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 setup, the spend and the reversals…`. Each part is left out where empty; the cycle always gives config.""" + config: str = "" + # The block spend.spent_block renders. + spent: str = "" + # The judge's quote of the human's reversing answer, as the judge checked it. + reversed: str = "" + + +def record_lines(record: Record) -> str: + reversed_block = f"{REVERSED}\n{quoted(record.reversed)}\n\n" if record.reversed else "" + spent_block = f"{record.spent}\n\n" if record.spent else "" + config_line = f"{CONFIG}{record.config}\n" if record.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 "") @@ -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, record: Record = Record()) -> str: + return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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) diff --git a/bin/transcript_archive/read.py b/bin/transcript_archive/read.py index 18240ab9..440a9465 100644 --- a/bin/transcript_archive/read.py +++ b/bin/transcript_archive/read.py @@ -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) @@ -66,3 +66,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="") diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index d50ae09a..be6cba7c 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -105,6 +105,34 @@ 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.Record("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", record=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", record=outcomes.Record("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.Record("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", "", record=spent), + outcomes.stopped("w", "Ctrl-C"), + outcomes.finished("w", "e", "j", record=outcomes.Record("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", "", record=outcomes.Record("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)) + self.assertIsInstance(read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure) + class Location(unittest.TestCase): def test_keys_a_project_by_its_path_under_code_or_else_under_the_root(self): diff --git a/docs/decisions.md b/docs/decisions.md index 7c27ad7c..77f134ff 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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 setup, the spend and the reversals: the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous record, and the human's typed answer the judge quotes as reversing a choice the worker took itself - 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 setup, the spend and the reversals: the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous record, and the human's typed answer the judge quotes as reversing a choice the worker took itself + +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: ()`: `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 of `bin/routing_figures/prices.py` in force. 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 a `/talk` or a stop between rulings neither counts twice nor drops a stretch. Tokens, not dollars, are kept, since prices change and a past chunk's cost can be derived again from them. 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 latest `[human]` line the judge finds overriding a choice the worker took on its own recommendation and recorded. The quote must appear verbatim in the transcript, or it is dropped. `score-outcomes` counts the distinct quotes per finished chunk, which is the counter-signal of goal 1.2 the 2026-11-08 entry of `loop-claude: a judge decides each interrupt…` is valid under. It counts only chunks that record a Config line, since earlier judges didn't look for reversals. + +Valid while the archive stays the record score-outcomes and routing-figures read. + ## 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. diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 87610076..66ab575d 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1771,3 +1771,20 @@ 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 diff --git a/todo.md b/todo.md index a0f408f2..462226b2 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +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 | @@ -90,16 +89,6 @@ The architect's 🔀 answer on PR #493 (item 292): four decisions expire "when a 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 ()` 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. -- 2.52.0 From 1fc7bf0f5274d3478f76acd0fcbd82f4afab2d60 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:03:47 +0100 Subject: [PATCH 2/7] Kill the surviving mutants of the spend, the setup version and the reversal count, and keep a subagent's type on one line --- bin/loop_claude/cycle/spend.py | 3 +- bin/loop_claude/test_loop_claude.py | 49 +++++++++++++++++-- bin/score_outcomes/test_score_outcomes.py | 36 ++++++++++++++ .../test_transcript_archive.py | 4 +- 4 files changed, 86 insertions(+), 6 deletions(-) diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 98f37707..11d085fc 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -80,7 +80,8 @@ def subagent_name(transcript: pathlib.Path) -> str: except (OSError, UnicodeDecodeError, ValueError): meta = {} meta = meta if isinstance(meta, dict) else {} - kind, description = str(meta.get("agentType") or "subagent"), str(meta.get("description") or "") + # 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 diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 9f348cc2..af7f7dba 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -402,6 +402,7 @@ Worker: {OFF_LADDER} 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: @@ -411,6 +412,36 @@ Worker: {OFF_LADDER} 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", "", record=outcomes.Record("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("") @@ -1620,6 +1651,14 @@ class Spend(unittest.TestCase): 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), @@ -1640,13 +1679,13 @@ class Spend(unittest.TestCase): 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)]: + 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"]) - self.assertEqual(spend.spent("", [], found, "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)}) + 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): @@ -1676,9 +1715,11 @@ class SetupVersion(unittest.TestCase): 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"], ["tag", "v0.1.0"]): + 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() diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index e3ec36d5..4b576894 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -15,6 +15,7 @@ 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 @@ -311,6 +312,20 @@ 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", record=outcomes.Record("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:]) + (archive.rglob("a.outcomes.md").__next__()).write_bytes(b"\xff") + ran = self.run_tool() + self.assertEqual(ran.returncode, 1) + self.assertIn("could not read the archive", ran.stderr) + 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)}) @@ -490,6 +505,27 @@ class Reversals(unittest.TestCase): chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", record=outcomes.Record("c")))) self.assertEqual(reversal_lines(archive), ["- 2026-11-02T12:00:00Z, item 7: 2 reversed", "- The other 1 finished chunk: none."]) + 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", record=outcomes.Record("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", record=outcomes.Record("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", record=outcomes.Record("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 {archive}: "), found.reason) + if __name__ == "__main__": unittest.main() diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index be6cba7c..5d1e042e 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -131,7 +131,9 @@ class Outcomes(unittest.TestCase): self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", record=outcomes.Record("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)) - self.assertIsInstance(read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure) + 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): -- 2.52.0 From ec0b17b03f69811101ceece7f1c2915b7bac6f29 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:09:19 +0100 Subject: [PATCH 3/7] Sort the new modules' imports, and test a reversal count where every chunk holds one --- bin/loop_claude/cycle/spend.py | 4 ++-- bin/score_outcomes/reversals.py | 4 ++-- bin/score_outcomes/test_score_outcomes.py | 5 +++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 11d085fc..349c42db 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -8,11 +8,11 @@ import pathlib import typing from claude_code.entries import AssistantTurn, Entry -from claude_code.tokens import Tokens, tokens_of -from claude_code.transcript import read_transcript 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. diff --git a/bin/score_outcomes/reversals.py b/bin/score_outcomes/reversals.py index 2a613fac..8f0f5b71 100644 --- a/bin/score_outcomes/reversals.py +++ b/bin/score_outcomes/reversals.py @@ -2,10 +2,10 @@ 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 -from transcript_archive.outcomes import CONFIG, reversals, workers -from transcript_archive.read import chunk_outcomes, finished_chunks def reversal_lines(project_archive: pathlib.Path) -> list[str] | Failure: diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index 4b576894..6e01ee2a 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -505,6 +505,11 @@ class Reversals(unittest.TestCase): chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", record=outcomes.Record("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", record=outcomes.Record("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) -- 2.52.0 From 67e272d5efbc3a19ebae10dd5929c1de8e87f42f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:10:29 +0100 Subject: [PATCH 4/7] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From d449c552c6dada16c9c13dd488b3899b3d020fff Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:25:30 +0100 Subject: [PATCH 5/7] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20keep=20the?= =?UTF-8?q?=20whole=20typed=20answer=20that=20holds=20the=20judge's=20quot?= =?UTF-8?q?e=20of=20a=20reversal,=20and=20test=20a=20failing=20rev-parse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/claude_code/transcript.py | 11 +++++++++++ bin/loop_claude/cycle/judge.py | 18 +++++++++++------- bin/loop_claude/cycle/spend.py | 7 ++++--- bin/loop_claude/test_loop_claude.py | 21 ++++++++++++++------- 4 files changed, 40 insertions(+), 17 deletions(-) diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 572a5b7d..a6e05e69 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -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))] diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index cbf1b954..e80fbef0 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -10,7 +10,7 @@ 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, Judged, QuotedAnswer, Unfinished, Verdict -from claude_code.transcript import plain, verbatim +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 @@ -78,8 +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."}) - # Counts the human's reversals of the worker's own choices, the counter-signal of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, its entry of 2026-11-08; score-outcomes lists them per chunk. - reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took itself 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."}) + # 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) @@ -106,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): @@ -176,13 +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, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.shown))) + return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed))) -def reversal_of(output: object, shown: str) -> str: - """The reply's reversed quote where the transcript holds it verbatim; empty otherwise. verdict_from has checked the field is a str.""" +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 quote if isinstance(quote, str) and verbatim(quote, shown) else "" + return next((answer for answer in reversed(typed) if isinstance(quote, str) and verbatim(quote, answer)), "") def cost_of(reply: dict) -> float: @@ -201,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. """ @@ -262,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 \ No newline at end of file diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 349c42db..e1db335a 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -1,4 +1,4 @@ -"""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 setup, the spend and the reversals…`. +"""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. """ @@ -54,11 +54,12 @@ def moment(stamp: str) -> datetime.datetime: return datetime.datetime.fromisoformat(stamp) -# The outcome's stamp runs to the second, so a message written in the second it was stamped, before it, counts again; the judge runs for seconds after the worker exits, so none is. +# 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 ValueError: + except (TypeError, ValueError): return False diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index af7f7dba..1b791e09 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -431,7 +431,7 @@ Worker: {OFF_LADDER} 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", "", record=outcomes.Record("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) + 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) @@ -1699,13 +1699,14 @@ List prices in dollars per million tokens of input, cache write 5m, cache write 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_reversal_the_judge_quotes_verbatim_and_its_tokens(self): - shown = "[human] No, keep the old name.\nworking" - for quoted, kept in [("No, keep the old name.", "No, keep the old name."), ("No, keep the name.", "")]: + 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, ""), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept))) + 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): @@ -1725,6 +1726,12 @@ class SetupVersion(unittest.TestCase): 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): @@ -2032,10 +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", "record.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", "record.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), -- 2.52.0 From 72d9a9f652f022fea2df4e940e9884de0b9e828f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:25:30 +0100 Subject: [PATCH 6/7] =?UTF-8?q?Answer=20product-owner=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20print=20the?= =?UTF-8?q?=20report=20before=20exiting=201=20on=20an=20unreadable=20archi?= =?UTF-8?q?ve,=20naming=20the=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/score_outcomes/main.py | 22 +++++++++--------- bin/score_outcomes/reversals.py | 12 +++++----- bin/score_outcomes/test_score_outcomes.py | 27 +++++++++++++---------- bin/transcript_archive/read.py | 20 ++++++++++++----- 4 files changed, 48 insertions(+), 33 deletions(-) diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index 14a36072..14e85039 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -78,13 +78,14 @@ that has any, then how many have none: the defects that reappear in what already 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, for every chunk loop-claude finished that has any, -then how many have none: goal 1.2's counter-signal. It reads loop-claude's archive, and counts only -chunks whose verdicts record a Config line, since earlier judges didn't look for reversals. +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, the default branch or loop-claude's archive 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 @@ -135,13 +136,14 @@ def main(argv: list[str]) -> int: return failed(results) anchored = read_anchors() reversal = read_reversals() - if isinstance(reversal, Failure): - return failed(reversal) print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None, reversal)) - return failed(anchored) if isinstance(anchored, Failure) else 0 + 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, reversal: list[str]) -> str: +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: @@ -152,7 +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, per chunk loop-claude finished, newest first:", "", *reversal]) + 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) diff --git a/bin/score_outcomes/reversals.py b/bin/score_outcomes/reversals.py index 8f0f5b71..923b1e67 100644 --- a/bin/score_outcomes/reversals.py +++ b/bin/score_outcomes/reversals.py @@ -1,4 +1,4 @@ -"""The human's reversals of choices workers took on their own, per finished chunk in loop-claude's archive: the counter-signal docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, its entry of 2026-11-08, is valid under.""" +"""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 @@ -15,10 +15,12 @@ def reversal_lines(project_archive: pathlib.Path) -> list[str] | Failure: return chunks counted = [] for chunk in reversed(chunks): - try: - texts = [path.read_text(encoding="utf-8") for path in chunk_outcomes(project_archive / chunk.folder)] - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"could not read the archive {project_archive}: {failure}") + 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)) diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index 6e01ee2a..50d8507d 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -222,7 +222,7 @@ Later fixes: the chunks that fixed code each finished chunk shipped, newest firs - 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, per chunk loop-claude finished, newest first: +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.""") @@ -315,16 +315,19 @@ class ScoreOutcomesTool(unittest.TestCase): 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", record=outcomes.Record("c", reversed="No.")))) + 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:]) - (archive.rglob("a.outcomes.md").__next__()).write_bytes(b"\xff") + unreadable = next(archive.rglob("a.outcomes.md")) + unreadable.write_bytes(b"\xff") ran = self.run_tool() self.assertEqual(ran.returncode, 1) - self.assertIn("could not read the archive", ran.stderr) + 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") @@ -500,24 +503,24 @@ class Reversals(unittest.TestCase): 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", record=outcomes.Record(reversed="No.")))) - chunk_file(archive, "reversed", ("2026-11-02T10:00:00Z", outcomes.unfinished(worker, "e", "j", "", record=outcomes.Record("c", reversed="No."))), ("2026-11-02T11:00:00Z", outcomes.unfinished(worker, "e", "j", "", record=outcomes.Record("c", reversed="No."))), ("2026-11-02T12:00:00Z", outcomes.finished(worker, "e", "j", record=outcomes.Record("c", reversed="Use X.")))) - chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", record=outcomes.Record("c")))) + 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", record=outcomes.Record("c", reversed="No.")))) + 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", record=outcomes.Record("c")))) + 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", record=outcomes.Record("c", reversed="No.")))) + 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() @@ -525,11 +528,11 @@ class Reversals(unittest.TestCase): 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", record=outcomes.Record("c")))) + 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 {archive}: "), found.reason) + self.assertTrue(found.reason.startswith(f"could not read the archive file {archive / 'kept' / 'b.outcomes.md'}: "), found.reason) if __name__ == "__main__": diff --git a/bin/transcript_archive/read.py b/bin/transcript_archive/read.py index 440a9465..a56b51dd 100644 --- a/bin/transcript_archive/read.py +++ b/bin/transcript_archive/read.py @@ -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)) -- 2.52.0 From fa54ed46b15c551ff128cebd6986016b0b8221ed Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 10:25:30 +0100 Subject: [PATCH 7/7] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20rename=20Re?= =?UTF-8?q?cord=20to=20Annotation,=20and=20reword=20the=20decision,=20the?= =?UTF-8?q?=20help=20and=20the=20changelog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- README.md | 2 +- bin/loop_claude/cycle/run.py | 26 +++++++------- bin/loop_claude/verdicts.py | 2 +- bin/transcript_archive/__init__.py | 2 +- bin/transcript_archive/outcomes.py | 36 +++++++++---------- .../test_transcript_archive.py | 14 ++++---- docs/decisions.md | 10 +++--- 8 files changed, 47 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a244841c..134ca86d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- loop-claude records beside each verdict, interrupt and quoted answer the claude-config release and commit that ran it, the tokens each thread 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 itself; `score-outcomes` counts those reversals per finished chunk. +- 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 []` waits for a line in a background job's log or report. diff --git a/README.md b/README.md index 9b1e4865..1b13ee79 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `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 ` 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 [...]` 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, code health's two counter-signals per chunk, misread findings and later fixes, and the answers that reversed a worker's choice; `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] ` 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. diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 1f25385a..530084e3 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -163,16 +163,16 @@ 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) - record = record_of(cycle, transcript_path, entries, verdict.judged) - if isinstance(record, Failure): - return Stop(1, record.reason) + 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, record), 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 record_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: Judged) -> outcomes.Record | Failure: +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): @@ -181,14 +181,14 @@ def record_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: if isinstance(subagents, Failure): return subagents spent = spend.spent(since, entries, subagents, judge_of(cycle).model, judged.tokens) - return outcomes.Record(cycle.config, spend.spent_block(since, spent), judged.reversed) + return outcomes.Annotation(cycle.config, spend.spent_block(since, spent), judged.reversed) -def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, record: outcomes.Record) -> str: +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.judged.cost, record=record) - return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, record) + 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: @@ -233,10 +233,10 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str: def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: entries = read_transcript(transcript_path) - record = entries if isinstance(entries, Failure) else record_of(cycle, transcript_path, entries, verdict.judged) - if isinstance(record, Failure): - return Stop(1, record.reason) - outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, record) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, record) + 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)): diff --git a/bin/loop_claude/verdicts.py b/bin/loop_claude/verdicts.py index 95ee9585..77f30698 100644 --- a/bin/loop_claude/verdicts.py +++ b/bin/loop_claude/verdicts.py @@ -22,7 +22,7 @@ class Judged: cost: float = 0.0 # Its reply's usage, on the judge's model. tokens: Tokens = Tokens() - # A typed answer of the human's that reversed a choice the worker took itself, as the judge quoted it; empty for none, and where the quote isn't in the transcript. + # 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 = "" diff --git a/bin/transcript_archive/__init__.py b/bin/transcript_archive/__init__.py index b167bed5..4cd5e985 100644 --- a/bin/transcript_archive/__init__.py +++ b/bin/transcript_archive/__init__.py @@ -13,7 +13,7 @@ transcript is kept once. - .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 record and any reversal the judge quoted (outcomes.Record). + 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 . diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index 35ea2c91..cef18a3b 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -31,26 +31,26 @@ JUDGE_COST_AT = re.compile(rf"^{re.escape(JUDGE)}(.+)\n{re.escape(JUDGE_COST)}([ # The claude-config release and commit that ran the cycle, on the line before JUDGE, such as `Config: v0.8.0 ()`. CONFIG = "Config: " -# Opens the block of what the stretch of work since the previous record spent; a record that spent nothing has none. +# 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 itself. +# 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 Record(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 setup, the spend and the reversals…`. Each part is left out where empty; the cycle always gives config.""" +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 judge's quote of the human's reversing answer, as the judge checked it. + # The human's whole typed answer that holds the judge's quote of the reversal, as loop-claude checked it. reversed: str = "" -def record_lines(record: Record) -> str: - reversed_block = f"{REVERSED}\n{quoted(record.reversed)}\n\n" if record.reversed else "" - spent_block = f"{record.spent}\n\n" if record.spent else "" - config_line = f"{CONFIG}{record.config}\n" if record.config else "" +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}" @@ -74,7 +74,7 @@ def judge_lines(judge: str, judge_cost: float) -> str: 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)] @@ -82,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, record: Record = Record()) -> str: - return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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, record: Record = Record()) -> 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}{record_lines(record)}{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: diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 5d1e042e..ee21ac05 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -106,16 +106,16 @@ class Outcomes(unittest.TestCase): 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.Record("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", record=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", record=outcomes.Record("v0.8.0 (abc)")), "Verdict: finished\n\nEvidence:\n> e\n\nConfig: v0.8.0 (abc)\nJudge: j\nWorker: w") + 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.Record("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1", "No, keep it.\nUse X.") + 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", "", record=spent), + outcomes.unfinished("w", "e", "j", "", annotation=spent), outcomes.stopped("w", "Ctrl-C"), - outcomes.finished("w", "e", "j", record=outcomes.Record("c", "Spent since x, in tokens of x:\n- judge, m: 1")), + 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)]) @@ -128,7 +128,7 @@ class Outcomes(unittest.TestCase): 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", "", record=outcomes.Record("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.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"))) diff --git a/docs/decisions.md b/docs/decisions.md index 77f134ff..c706da90 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -15,7 +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 setup, the spend and the reversals: the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous record, and the human's typed answer the judge quotes as reversing a choice the worker took itself +- 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 @@ -139,15 +139,15 @@ 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 setup, the spend and the reversals: the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous record, and the human's typed answer the judge quotes as reversing a choice the worker took itself +## 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: ()`: `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 of `bin/routing_figures/prices.py` in force. 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 a `/talk` or a stop between rulings neither counts twice nor drops a stretch. Tokens, not dollars, are kept, since prices change and a past chunk's cost can be derived again from them. 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 latest `[human]` line the judge finds overriding a choice the worker took on its own recommendation and recorded. The quote must appear verbatim in the transcript, or it is dropped. `score-outcomes` counts the distinct quotes per finished chunk, which is the counter-signal of goal 1.2 the 2026-11-08 entry of `loop-claude: a judge decides each interrupt…` is valid under. It counts only chunks that record a Config line, since earlier judges didn't look for reversals. +- 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 the archive stays the record score-outcomes and routing-figures read. +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 -- 2.52.0