diff --git a/CHANGELOG.md b/CHANGELOG.md index 5da93588..8c5a7b7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `loop-claude` runs the judge on the rung the chunk's `todo.md` item picks from the project's model, never below that model's cheapest rung, which for Opus 5.5 is medium effort. Before, the judge ran at the effort `settings.json` sets, xhigh. A replay of 39 archived verdicts found every cheaper rung missing verdicts. The judge keeps its rung when the worker steps up, and runs on the cheapest rung when no item routed the chunk. The new `bin/judge-replay ` replays the judge on archived verdicts and prints the cheapest rung that returns them. Expect the judge to cost less on items of R + C 12 or less, and more on items of R + C 15 or more. +- `loop-claude` runs the judge of an Opus 5.5 project on the rung the chunk's `todo.md` item picks, never below Opus 5.5 at medium effort, the project's rung. Before, the judge ran at the effort `settings.json` sets, xhigh. A replay of 39 archived verdicts found every cheaper rung missing verdicts. The judge keeps its rung when the worker steps up, and runs on the project's rung when no item routed the chunk. A project on another model keeps its judge at its settings' effort. The new `bin/judge-replay ` replays the judge on archived verdicts and prints the cheapest rung that returns them. Expect the judge to cost less on items of R + C 12 or less, and more on items of R + C 15 or more. - Every 20 cycles across all projects, `loop-claude` measures every finished chunk in its archive, with no model run, and writes the figures to `routing-figures.md` at the archive's root: tokens by project, subagent type, rung and tool, and, for each chunk a `todo.md` item routed, grouped by the rung it started on: its review rounds past each pass's first, its unfinished verdicts and its subagents' rungs. It interrupts you, with `claude` on the project's model on the terminal in `~/.claude`, when chunks routed onto a rung took more review rounds or unfinished verdicts than chunks routed onto the next rung up, each rung with 5 chunks or more, or when 5 or more subagents of one type wrote reports longer than the tool results they read. Each call is raised once, then listed in `routing-calls-raised.md` beside the figures; the next chunk of this repo files a `todo.md` item for it. Off a terminal, the calls are said on stderr and the loop goes on. They are raised at the next measurement on a terminal. After a routing change, a `- Reset` line in that file makes the figures count only chunks finished after it, and lets its calls be raised again. Expect a pause of about ten seconds at each measurement. - A session delegates a task to a subagent only when it needs just the task's conclusion, such as a search across many files, and keeps edits in its own thread. It scores the task's R and C as for a `todo.md` item, and launches the subagent on the model and effort that the new `bin/subagent-rung ` picks from the project's model, such as `model sonnet, effort high`. `CLAUDE.md` states the rule. Expect searches to run on cheaper models, and less of each session's context to fill with search output. - `loop-claude` routes each chunk's worker on a ladder of model and effort rungs, from Haiku 5.5 at low effort to Fable 5.1 at max, when the project's model is on it. As a chunk starts, the R + C of `todo.md`'s top item in the next release picks the rung: 11–12 picks one rung above the project's rung, so Opus 5.5 at high for an Opus 5.5 project, and so on up to four rungs. An item of R + C 10 or less runs the worker at or below the project's model's cheapest rung, which for Opus 5.5 is medium effort, below the xhigh `settings.json` sets. While the worker runs below the project's model's cheapest rung, it launches every reviewer, comprehension seat and security pass, the full scan included, in a subagent on that rung. While it runs above that rung, it launches each comprehension seat and the security pass on that rung. It steps up one rung after every second unfinished verdict on a chunk, and to a higher rung when it takes in an item of higher R + C. Each cycle's header, and each finished or unfinished verdict, stop and step-up in the archive, name the worker's rung; a rerun resumes an open chunk on the latest rung archived for it. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on an easy item to cost much less than under xhigh, and perhaps to take more review rounds, and one on an item of R + C 15 or more to cost more. diff --git a/README.md b/README.md index 5c1be3b9..6573673a 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ pytest_add_cli_args=-k Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show ` to see a mutant's change. The config keys are mutmut 3's. -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, and `score_outcomes` imports `reading_cost`'s record path. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `score_outcomes` imports `reading_cost`'s record path, and `judge_replay` imports `loop_claude`'s judge. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. ## Tracking a new file diff --git a/bin/judge-replay b/bin/judge-replay index 03dfa0da..0dd72f83 100755 --- a/bin/judge-replay +++ b/bin/judge-replay @@ -5,7 +5,7 @@ import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude.effects import system_effects from judge_replay import main +from loop_claude.effects import system_effects sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects())) diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index 156da325..ff6dc4b6 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -8,15 +8,16 @@ verdicts archived for the projects that ~/.claude/loop-claude-models.json runs o archive is what the judge read for the verdict beside it, so the replay hands the judge that copy, with the task, premises and records each project holds now. -It first replays every verdict on today's judge: the model at its settings' effort. A verdict -today's judge returns another kind on rests on the records and judge rules of its day, so no rung -is held to it. It then replays the rest on each rung from the one the lowest R + C picks up to the -project's rung, cheapest first, and stops at the first rung that returns all of them. It prints -each verdict a rung missed, and the cheapest rung that missed none. +It first replays every verdict on the reference judge: the model at xhigh effort, where the judge +ran before it was routed. A verdict the reference judge returns another kind on rests on the +records and judge rules of its day, so no rung is held to it. It then replays the rest on each rung +from the one the lowest R + C picks up to the model's cheapest rung, cheapest first, and stops at +the first rung that returns all of them. It prints each verdict a rung missed, and the cheapest +rung that missed none. -A verdict whose project or transcript cannot be read replays as failed, and so does a reply the loop -would reject. Exit 1, saying why, on bad arguments, an unreadable archive or models file, or a -usage limit. +Like the loop, it tries a judge three times running before it counts the reply as failed. A +verdict whose project or transcript cannot be read replays as failed too. Exit 1, saying why, on +bad arguments, an unreadable archive or models file, or a usage limit. """ import concurrent.futures import pathlib @@ -24,12 +25,14 @@ import sys import typing from transcript_archive.location import archive_root -from judge_replay.replay import Case, case_from, checkout_root, replayed, sample, verdict_kind +from transcript_archive.read import archived_outcomes, transcript_of +from judge_replay.replay import Case, case_from, Kind, replayed, report, sample, verdict_kind +from project_key import checkout_of from loop_claude.effects import Effects from failure import Failure -from loop_claude.cycle.judge import judge_args, judge_prompt, run_judge +from loop_claude.cycle.retry import FAILURES_RUNNING, Limited +from loop_claude.cycle.judge import judge_once, Verdict from model_routing.ladder import LADDER, picked, position, project_rung, Rung -from loop_claude.cycle.retry import Limited from loop_claude.project.model_choice import read_models_file from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records @@ -37,16 +40,14 @@ from claude_code.transcript import read_transcript, render from loop_claude.stop import Stop PER_KIND = 15 +# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it. +REFERENCE_EFFORT = "xhigh" # claude runs at a time; each judge reads up to JUDGE_PROMPT_CHARS. AT_ONCE = 4 LOWEST_R_PLUS_C = 2 USAGE = "usage: judge-replay , a model on the routing ladder" -class UsageLimit(Exception): - pass - - def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) @@ -60,20 +61,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff print(f"judge-replay: {cases.reason}", file=sys.stderr) return 1 cases = sample(cases, PER_KIND) + reference = Rung(argv[0], REFERENCE_EFFORT) candidates = list(LADDER[position(picked(anchor, LOWEST_R_PLUS_C)):position(anchor) + 1]) - try: - replay = replayed(cases, Rung(argv[0]), candidates, lambda on, rung: rule_all(on, rung, home / ".claude", effects)) - except UsageLimit as limit: - print(f"judge-replay: {limit}", file=sys.stderr) + replay = replayed(cases, reference, candidates, lambda on, rung: rule_all(on, rung, home / ".claude", effects)) + if isinstance(replay, Limited): + print(f"judge-replay: claude hit a usage limit: {replay.said}; replay again once it resets", file=sys.stderr) return 1 - kinds = {kind: sum(found.on_record == kind for found in cases) for kind in dict.fromkeys(found.on_record for found in cases)} - print(f"Replayed {len(cases)} verdicts of {argv[0]} projects: {', '.join(f'{count} {kind}' for kind, count in kinds.items())}.") - print(f"Today's judge, {argv[0]}, reproduced {len(cases) - len(replay.unreproduced)}.{' It returned another kind on:' if replay.unreproduced else ''}") - print_missed(replay.unreproduced) - for tried in replay.tried: - print(f"{tried.rung} missed {len(tried.missed) or 'none'}{':' if tried.missed else '.'}") - print_missed(tried.missed) - print(f"Cheapest rung that returns every verdict today's judge reproduces: {replay.cheapest or 'none up to the project rung'}") + print(report(argv[0], reference, cases, replay)) return 0 @@ -81,24 +75,34 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C models = read_models_file(home / ".claude" / "loop-claude-models.json") if isinstance(models, Stop): return Failure(models.reason) + listed = archived_outcomes(root) + if isinstance(listed, Failure): + return listed found = [] try: - for outcomes in root.rglob("*.outcomes.md"): - key = str(outcomes.parent.parent.relative_to(root)) - if models.get(key) == model and (case := case_from(checkout_root(key, home), outcomes.read_text(encoding="utf-8"), outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"))): - found.append(case) + for key, outcomes in listed: + case = case_from(checkout_of(key, home), outcomes.read_text(encoding="utf-8"), transcript_of(outcomes)) if models.get(key) == model else None + found += [case] if case else [] except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read the archive {root}: {failure}") return found -def rule_all(cases: list[Case], rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> list[str]: +def rule_all(cases: list[Case], rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> list[Kind] | Limited: print(f"replaying {len(cases)} verdicts on {rung}", file=sys.stderr, flush=True) with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool: - return list(pool.map(lambda found: rule(found, rung, claude_dir, effects), cases)) + running = [pool.submit(rule, found, rung, claude_dir, effects) for found in cases] + kinds = [] + for future in running: + kind = future.result() + if isinstance(kind, Limited): + pool.shutdown(cancel_futures=True) + return kind + kinds.append(kind) + return kinds -def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> str: +def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> Kind | Limited: premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript)) if isinstance(premises, Stop): return verdict_kind(Failure(premises.reason)) @@ -106,13 +110,13 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> return verdict_kind(Failure(records.reason)) if isinstance(entries, Failure): return verdict_kind(entries) - prompt, shown = judge_prompt(case.task, premises, records, render(entries)) - verdict = run_judge(case.root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects) - if isinstance(verdict, Limited): - raise UsageLimit(f"{rung} hit a usage limit: {verdict.said}; replay again once it resets") - return verdict_kind(verdict) + verdict = retried_as_the_loop_does(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects)) + return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) -def print_missed(missed: list[tuple[Case, str]]) -> None: - for found, kind in missed: - print(f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}") +def retried_as_the_loop_does(attempt: typing.Callable[[], Verdict | Failure | Limited]) -> Verdict | Failure | Limited: + """The first reply that is no Failure, or the last of FAILURES_RUNNING failures.""" + for _ in range(FAILURES_RUNNING - 1): + if not isinstance(verdict := attempt(), Failure): + return verdict + return attempt() diff --git a/bin/judge_replay/replay.py b/bin/judge_replay/replay.py index dfac983d..ed4c792d 100644 --- a/bin/judge_replay/replay.py +++ b/bin/judge_replay/replay.py @@ -1,101 +1,112 @@ -"""Which archived verdicts to replay, and the cheapest rung that returns them: docs/decisions.md → `routing:`.""" +"""Which archived verdicts to replay, the cheapest rung that returns them, and the report: docs/decisions.md → `routing:`.""" import collections import dataclasses import pathlib -import re import typing +from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict +from loop_claude.cycle.retry import Limited from model_routing.ladder import Rung -from utc_stamp import STAMPED -# The first verdict archived beside a transcript copy: the judge ruled on that copy as it stands. -FIRST_VERDICT = re.compile(rf"^({STAMPED}) Verdict: (finished|unfinished|interrupt|quoted answer)$", re.MULTILINE) -TASK = re.compile(rf"\ATask: (.*?)\n\n{STAMPED} ", re.DOTALL) +# claude's reply as the replay compares it: a verdict as the archive words it, such as FINISHED, or a failure with its reason. +Kind = str @dataclasses.dataclass(frozen=True) class Case: - """One archived verdict: on_record is its kind, as the archive words it, and at its UTC stamp.""" + """One archived verdict: on_record, judged at its UTC stamp.""" root: str task: str transcript: pathlib.Path at: str - on_record: str + on_record: Kind @dataclasses.dataclass(frozen=True) class Tried: - """A rung, and each case it returned another kind of verdict on, with that kind.""" + """A rung, and each case it returned another kind on, with that kind.""" rung: Rung - missed: list[tuple[Case, str]] + missed: list[tuple[Case, Kind]] @dataclasses.dataclass(frozen=True) class Replay: - """unreproduced holds each case today's judge returned another kind on; tried, each rung tried, cheapest first; cheapest, the first rung that missed none, or None.""" - unreproduced: list[tuple[Case, str]] + """unreproduced holds each case the reference judge returned another kind on; tried, each rung tried, cheapest first; cheapest, the first rung that missed none, or None.""" + unreproduced: list[tuple[Case, Kind]] tried: list[Tried] cheapest: Rung | None def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None: - """The case an outcomes file holds; None when it holds no verdict.""" - task, verdict = TASK.match(outcomes), FIRST_VERDICT.search(outcomes) - if not (task and verdict): + """The first verdict an outcomes file holds: the judge ruled on the transcript copy beside it as the copy stands. None when it holds none.""" + task, verdict = task_of(outcomes), first_verdict(outcomes) + if task is None or verdict is None: return None - return Case(root, task[1], transcript, verdict[1], verdict[2]) - - -def checkout_root(key: str, home: pathlib.Path) -> str: - """The checkout an archive key names: the inverse of project_key.""" - under_code = home / "code" / key - return str(under_code) if under_code.is_dir() else f"/{key}" + return Case(root, task, transcript, *verdict) def sample(cases: list[Case], per_kind: int) -> list[Case]: """The latest per_kind cases of each kind of verdict, in the order they were judged.""" - seen: collections.Counter[str] = collections.Counter() + seen: collections.Counter[Kind] = collections.Counter() kept = [] - for found in sorted(cases, key=lambda found: found.at, reverse=True): + for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript)), reverse=True): seen[found.on_record] += 1 if seen[found.on_record] <= per_kind: kept.append(found) return kept[::-1] -def verdict_kind(verdict: Verdict | Failure) -> str: +def verdict_kind(verdict: Verdict | Failure) -> Kind: match verdict: case Finished(): - return "finished" + return FINISHED case Unfinished(): - return "unfinished" + return UNFINISHED case Interrupt(): - return "interrupt" + return INTERRUPTED case QuotedAnswer(): - return "quoted answer" + return ANSWERED case Failure(reason): return f"failed: {reason}" case _: typing.assert_never(verdict) -def replayed(cases: list[Case], today: Rung, candidates: list[Rung], rule_all: typing.Callable[[list[Case], Rung], list[str]]) -> Replay: - """Replays the cases on today's rung, then only those it reproduces on each candidate, cheapest first, until one returns every verdict. +def replayed(cases: list[Case], reference: Rung, candidates: list[Rung], rule_all: typing.Callable[[list[Case], Rung], list[Kind] | Limited]) -> Replay | Limited: + """Replays the cases on the reference rung, then only those it reproduces on each candidate, cheapest first, until one returns every verdict. - A verdict today's judge does not reproduce rests on the records and judge rules of its day, so no rung is held to it. + A verdict the reference judge does not reproduce rests on the records and judge rules of its day, so no rung is held to it. """ - reproduced, unreproduced = [], [] - for found, kind in zip(cases, rule_all(cases, today)): - if kind == found.on_record: - reproduced.append(found) - else: - unreproduced.append((found, kind)) + ruled = rule_all(cases, reference) + if isinstance(ruled, Limited): + return ruled + reproduced = [found for found, kind in zip(cases, ruled) if kind == found.on_record] + unreproduced = [(found, kind) for found, kind in zip(cases, ruled) if kind != found.on_record] tried = [] for rung in candidates: - missed = [(found, kind) for found, kind in zip(reproduced, rule_all(reproduced, rung)) if kind != found.on_record] - tried.append(Tried(rung, missed)) - if not missed: + ruled = rule_all(reproduced, rung) + if isinstance(ruled, Limited): + return ruled + tried.append(Tried(rung, [(found, kind) for found, kind in zip(reproduced, ruled) if kind != found.on_record])) + if not tried[-1].missed: return Replay(unreproduced, tried, rung) return Replay(unreproduced, tried, None) + + +def report(model: str, reference: Rung, cases: list[Case], replay: Replay) -> str: + kinds = collections.Counter(found.on_record for found in cases) + lines = [ + f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.", + f"The reference judge, {reference}, reproduced {len(cases) - len(replay.unreproduced)}{'. It returned another kind on:' if replay.unreproduced else '.'}", + *missed_lines(replay.unreproduced), + ] + for tried in replay.tried: + lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *missed_lines(tried.missed)] + lines.append(f"Cheapest rung that returns every verdict the reference judge reproduces: {replay.cheapest or 'none up to the project rung'}") + return "\n".join(lines) + + +def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]: + return [f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}" for found, kind in missed] diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 05ee422f..e52ecefc 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -1,19 +1,28 @@ +import contextlib +import io +import json import pathlib +import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from judge_replay.replay import Case, case_from, checkout_root, replayed, sample, verdict_kind +from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED +from judge_replay.replay import Case, case_from, Replay, replayed, report, sample, Tried, verdict_kind +from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished +from loop_claude.cycle.retry import Limited +from judge_replay import main from model_routing.ladder import Rung +TOOL = pathlib.Path(__file__).resolve().parents[1] / "judge-replay" TRANSCRIPT = pathlib.Path("/archive/p/c/a.jsonl") CHEAP = Rung("claude-haiku-5-5", "xhigh") MIDDLE = Rung("claude-sonnet-5-5", "high") -TODAY = Rung("claude-opus-5-5") +REFERENCE = Rung("claude-opus-5-5", "xhigh") def case(at, on_record): @@ -23,61 +32,146 @@ def case(at, on_record): class CaseFrom(unittest.TestCase): def test_takes_the_task_and_the_first_verdict_on_the_copy(self): outcomes = "Task: Do the next chunk.\nThen merge it.\n\n2026-10-14T10:00:00Z Stopped: claude failed\n\nWorker: x\n2026-10-14T11:00:00Z Verdict: unfinished\n\nEvidence:\n> on\n\nWorker: x\n2026-10-14T11:00:01Z Stepped up\n\nWorker: y\n" - self.assertEqual(case_from("/code/p", outcomes, TRANSCRIPT), Case("/code/p", "Do the next chunk.\nThen merge it.", TRANSCRIPT, "2026-10-14T11:00:00Z", "unfinished")) + self.assertEqual(case_from("/code/p", outcomes, TRANSCRIPT), Case("/code/p", "Do the next chunk.\nThen merge it.", TRANSCRIPT, "2026-10-14T11:00:00Z", UNFINISHED)) def test_reads_each_kind_of_verdict(self): - for kind in ("finished", "unfinished", "interrupt", "quoted answer"): - found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z Verdict: {kind}\n\nmore\n", TRANSCRIPT) - self.assertEqual(found.on_record, kind) + for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED): + found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT) + self.assertEqual(found.on_record, verdict) def test_skips_a_copy_with_no_verdict(self): self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT)) self.assertIsNone(case_from("/code/p", "not an outcomes file", TRANSCRIPT)) -class CheckoutRoot(unittest.TestCase): - def test_finds_a_key_under_code_or_else_under_the_root(self): - with tempfile.TemporaryDirectory() as home: - (pathlib.Path(home) / "code" / "log").mkdir(parents=True) - self.assertEqual(checkout_root("log", pathlib.Path(home)), f"{home}/code/log") - self.assertEqual(checkout_root("home/me/.claude", pathlib.Path(home)), "/home/me/.claude") - - class Sample(unittest.TestCase): def test_keeps_the_latest_of_each_kind_in_the_order_they_were_judged(self): - cases = [case("2026-10-14T10:00:01Z", "finished"), case("2026-10-14T10:00:03Z", "finished"), case("2026-10-14T10:00:02Z", "finished"), case("2026-10-14T10:00:00Z", "interrupt")] + cases = [case("2026-10-14T10:00:01Z", FINISHED), case("2026-10-14T10:00:03Z", FINISHED), case("2026-10-14T10:00:02Z", FINISHED), case("2026-10-14T10:00:00Z", INTERRUPTED)] self.assertEqual(sample(cases, 2), [cases[3], cases[2], cases[1]]) class VerdictKind(unittest.TestCase): def test_names_each_verdict_as_the_archive_does(self): - self.assertEqual(verdict_kind(Finished("e")), "finished") - self.assertEqual(verdict_kind(Unfinished("e", 3)), "unfinished") - self.assertEqual(verdict_kind(Interrupt("e", "q?")), "interrupt") - self.assertEqual(verdict_kind(QuotedAnswer("e", "q?", "a")), "quoted answer") + self.assertEqual(verdict_kind(Finished("e")), FINISHED) + self.assertEqual(verdict_kind(Unfinished("e", 3)), UNFINISHED) + self.assertEqual(verdict_kind(Interrupt("e", "q?")), INTERRUPTED) + self.assertEqual(verdict_kind(QuotedAnswer("e", "q?", "a")), ANSWERED) self.assertEqual(verdict_kind(Failure("the judge quoted x")), "failed: the judge quoted x") class Replayed(unittest.TestCase): - def test_tries_rungs_cheapest_first_on_the_verdicts_todays_judge_reproduces_and_stops_at_the_first_that_returns_all(self): - cases = [case("2026-10-14T10:00:00Z", "finished"), case("2026-10-14T10:00:01Z", "interrupt"), case("2026-10-14T10:00:02Z", "finished")] - replies = {TODAY: ["finished", "interrupt", "unfinished"], CHEAP: ["finished", "finished"], MIDDLE: ["finished", "interrupt"]} + def test_tries_rungs_cheapest_first_on_the_verdicts_the_reference_reproduces_and_stops_at_the_first_that_returns_all(self): + cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED), case("2026-10-14T10:00:02Z", FINISHED)] + replies = {REFERENCE: [FINISHED, INTERRUPTED, UNFINISHED], CHEAP: [FINISHED, FINISHED], MIDDLE: [FINISHED, INTERRUPTED]} asked = [] def rule_all(on, rung): asked.append((len(on), rung)) return replies[rung] - replay = replayed(cases, TODAY, [CHEAP, MIDDLE, Rung("claude-opus-5-5", "medium")], rule_all) - self.assertEqual(replay.unreproduced, [(cases[2], "unfinished")]) - self.assertEqual([(tried.rung, tried.missed) for tried in replay.tried], [(CHEAP, [(cases[1], "finished")]), (MIDDLE, [])]) - self.assertEqual(replay.cheapest, MIDDLE) - self.assertEqual(asked, [(3, TODAY), (2, CHEAP), (2, MIDDLE)]) + replay = replayed(cases, REFERENCE, [CHEAP, MIDDLE, Rung("claude-opus-5-5", "medium")], rule_all) + self.assertEqual(replay, Replay([(cases[2], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE)) + self.assertEqual(asked, [(3, REFERENCE), (2, CHEAP), (2, MIDDLE)]) def test_names_no_rung_when_every_candidate_misses_a_verdict(self): - replay = replayed([case("2026-10-14T10:00:00Z", "finished")], TODAY, [CHEAP], lambda on, rung: ["finished"] if rung == TODAY else ["interrupt"]) + replay = replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else [INTERRUPTED]) self.assertIsNone(replay.cheapest) + def test_stops_at_a_usage_limit(self): + limit = Limited(None, "limit") + self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: limit), limit) + self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else limit), limit) + + +class Report(unittest.TestCase): + def test_counts_the_verdicts_and_names_each_miss_and_the_cheapest_rung(self): + cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)] + replay = Replay([(cases[0], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE) + self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [ + "Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.", + "The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:", + " /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished", + "claude-haiku-5-5 at xhigh effort missed 1:", + " /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished", + "claude-sonnet-5-5 at high effort missed 0.", + "Cheapest rung that returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort", + ]) + self.assertTrue(report("claude-opus-5-5", REFERENCE, cases, Replay([], [Tried(CHEAP, [(cases[1], FINISHED)])], None)).endswith(": none up to the project rung")) + + +def unused(*_): + raise AssertionError("not called") + + +class Main(unittest.TestCase): + """The tool on a temporary home: a project on Opus 5.5 with one finished and one interrupt verdict, and one on another model.""" + + def setUp(self): + self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) + (self.home / ".claude").mkdir() + (self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) + for key, verdicts in (("proj", (FINISHED, INTERRUPTED)), ("other", (FINISHED,))): + (self.home / "code" / key).mkdir(parents=True) + (self.home / "code" / key / "README.md").write_text("# p\n\n## Goals\n\n1. Ship.\n\n## Audience\n\nMe.\n") + chunk = self.home / ".claude" / "loop-claude-transcripts" / key / "c1" + chunk.mkdir(parents=True) + for n, verdict in enumerate(verdicts): + (chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {verdict}"}]}}) + "\n") + (chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {verdict}\n\nEvidence:\n> e\n") + self.calls = [] + + def run_main(self, argv, reply): + def claude(args, cwd, prompt): + self.calls.append((args[args.index("--model") + 1], args[args.index("--effort") + 1], cwd)) + result = reply(args[args.index("--model") + 1], "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) + return subprocess.CompletedProcess(args, 0, json.dumps(result), "") + + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.main(argv, {}, self.home, effects) + return code, out.getvalue(), err.getvalue() + + @staticmethod + def verdict(interrupt, evidence): + output = {"answer": "", "bundled": 0, "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""} + return {"type": "result", "structured_output": output} + + def test_replays_the_models_projects_on_the_reference_then_cheapest_first_and_prints_the_rung_that_returns_all(self): + # Haiku misses the interrupt; Sonnet returns both. + def reply(model, interrupted): + return self.verdict(interrupted and model != "claude-haiku-5-5", f"said {INTERRUPTED if interrupted else FINISHED}") + + code, out, err = self.run_main(["claude-opus-5-5"], reply) + self.assertEqual(code, 0, err) + self.assertEqual({cwd for _, _, cwd in self.calls}, {str(self.home / "code" / "proj")}) + self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-haiku-5-5", "xhigh"), ("claude-haiku-5-5", "max"), ("claude-sonnet-5-5", "high")]) + self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out) + self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n")) + + def test_tries_up_to_the_models_cheapest_rung_and_retries_a_failed_reply_as_the_loop_does(self): + def reply(model, interrupted): + return self.verdict(interrupted, "not in the transcript" if model != "claude-opus-5-5" else f"said {INTERRUPTED if interrupted else FINISHED}") + + code, out, _ = self.run_main(["claude-opus-5-5"], reply) + self.assertEqual(code, 0) + self.assertEqual(sum(model == "claude-sonnet-5-5" for model, _, _ in self.calls), 6) + self.assertIn("claude-opus-5-5 at medium effort missed 0.", out) + + def test_exits_1_on_a_usage_limit_bad_arguments_or_an_unreadable_models_file(self): + code, _, err = self.run_main(["claude-opus-5-5"], lambda model, interrupted: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"}) + self.assertEqual(code, 1) + self.assertIn("usage limit: You've hit your limit", err) + for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]): + self.assertEqual(self.run_main(argv, unused)[0], 1) + (self.home / ".claude" / "loop-claude-models.json").write_text("[") + self.assertEqual(self.run_main(["claude-opus-5-5"], unused)[0], 1) + + def test_the_launcher_prints_the_help(self): + ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True) + self.assertEqual(ran.returncode, 0) + self.assertIn("usage: judge-replay ", ran.stdout) + if __name__ == "__main__": unittest.main() diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 310750ca..554d2a3e 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -121,8 +121,13 @@ def verdict_from(output: object) -> Verdict | Failure: def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Stop: + return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects) + + +def judge_once(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Failure | Limited: + """One judge run, as judge retries it; judge-replay replays it.""" prompt, shown = judge_prompt(task, premises, records, rendered_transcript) - return retried("judge", lambda: run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects), effects) + return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects) def judge_args(rung: Rung) -> list[str]: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 57f2eee3..e366e61b 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -9,6 +9,7 @@ from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Unfinished from loop_claude.cycle.interrupt import interrupt +from loop_claude.routing import judge_rung from transcript_archive import outcomes from loop_claude.paths import Paths from loop_claude.cycle import prompts @@ -23,7 +24,7 @@ from loop_claude.stop import Stop @dataclasses.dataclass(frozen=True) class Cycle: effects: Effects - judge_rung: Rung + judge_model: str paths: Paths premises: str project_archive: pathlib.Path @@ -103,7 +104,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) - verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), cycle.judge_rung, cycle.effects) + verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), judge_rung(cycle.judge_model, cycle.route), cycle.effects) return verdict if isinstance(verdict, Stop) else Ruled(verdict) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 653ed7c8..9f9f2984 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -47,9 +47,9 @@ todo.md's top item in the next release, skipping an item marked question, picks counts from the model's cheapest rung, and an R + C of 8 or less picks a rung below it; without such an item, or with a C missing, the chunk runs on the model's cheapest rung. The worker's first prompt names the rung and the item, and asks the worker to name each item the chunk takes, with its -R + C. The judge runs on the rung that item's R + C picks from the judge's model, never below that -model's cheapest rung, whatever rung the worker steps to; without such an item, on the cheapest -rung. When the worker's rung is below the model's cheapest, the prompt also has the worker launch each +R + C. On a model judge-replay has replayed, the judge runs on the rung that item's R + C picks from +the judge's model, never below that model's cheapest rung, whatever rung the worker steps to; +without such an item, on the cheapest rung. When the worker's rung is below the model's cheapest, the prompt also has the worker launch each reviewer, each comprehension seat and the security pass in subagents on the cheapest rung. When it is above, the prompt has the worker launch only each comprehension seat and the security pass on the cheapest rung. The prompt after each unfinished verdict @@ -127,7 +127,7 @@ from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Unfinished -from loop_claude.routing import first_route, judge_rung, kept, routed_item, stepped +from loop_claude.routing import first_route, kept, routed_item, stepped from loop_claude.project.model_choice import get_or_ask_models from todo_table import Item from transcript_archive.read import latest_worker @@ -179,7 +179,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(root)) route = loop_run.route or Route(Rung(models.worker)) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) - verdict = run_cycle(Cycle(anchor=anchor, effects=effects, judge_rung=judge_rung(models.judge, route), paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) + verdict = run_cycle(Cycle(anchor=anchor, effects=effects, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) if isinstance(verdict, Stop): return verdict before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict) diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index e51cfc66..e0aa1367 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -7,6 +7,8 @@ from todo_table import Item, items from model_routing.route import Route UNFINISHED_PER_STEP = 2 +# The models `judge-replay` found returning every verdict on their cheapest rung: docs/decisions.md → `routing:`. +JUDGE_REPLAYED = ("claude-opus-5-5",) def routed_item(todo: str) -> Item | Failure | None: @@ -28,7 +30,12 @@ def first_route(anchor: Rung, item: Item | None) -> Route: def kept(route: Route, anchor: Rung) -> bool: """Whether a chunk keeps route: its rung is on the ladder at or above the rung its item's R + C picks from anchor, the project's rung, or anchor itself when no item routed it.""" - return highest(route.rung, picked(anchor, route.risk_and_complexity) if route.item else anchor) == route.rung + return highest(route.rung, item_rung(anchor, route)) == route.rung + + +def item_rung(anchor: Rung, route: Route) -> Rung: + """The rung the route's item's R + C picks from anchor, the project's rung, or anchor itself when no item routed it.""" + return picked(anchor, route.risk_and_complexity) if route.item else anchor def stepped(anchor: Rung, route: Route, bundled: int) -> Route: @@ -42,9 +49,12 @@ def stepped(anchor: Rung, route: Route, bundled: int) -> Route: def judge_rung(judge_model: str, route: Route) -> Rung: - """The rung the chunk's item picks from the judge model's cheapest rung, never below that rung, whatever rung the worker stepped to; the model alone, at its settings' effort, off the ladder.""" - # judge-replay found every rung below Opus 5.5's cheapest one missing verdicts it returns. + """The rung the route's item picks from the judge model's cheapest rung, never below that rung, whatever rung the worker stepped to. + + A model judge-replay has not replayed runs alone, at its settings' effort, as does one off the ladder. + """ + # The archive records no judge rung: each verdict's worker line names the item and R + C that pick it, and judge-replay holds rungs to its own reference judge. anchor = project_rung(judge_model) - if anchor is None: + if anchor is None or judge_model not in JUDGE_REPLAYED: return Rung(judge_model) - return highest(anchor, picked(anchor, route.risk_and_complexity)) if route.item else anchor + return highest(anchor, item_rung(anchor, route)) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 1bf69ef7..4dd5d1f4 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -175,7 +175,7 @@ class Cycles(unittest.TestCase): self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) def cycle(self, fake, records="", unfinished_evidence=""): - return run.Cycle(anchor=None, effects=fake.effects(), judge_rung=Rung("judge-model"), paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence) + return run.Cycle(anchor=None, effects=fake.effects(), judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence) def archived_outcomes(self): return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md")) @@ -539,6 +539,7 @@ class Routing(unittest.TestCase): self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2)), self.OPUS) self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.HIGH)), self.OPUS) self.assertEqual(routing.judge_rung("judge-model", Route(self.HIGH, 3, 11)), Rung("judge-model")) + self.assertEqual(routing.judge_rung("claude-sonnet-5-5", Route(self.HIGH, 3, 11)), Rung("claude-sonnet-5-5")) def test_archives_the_route_in_a_line_it_reads_back(self): route = Route(self.HIGH, 3, 11) diff --git a/bin/project_key.py b/bin/project_key.py index 2a70ca6f..29dd3502 100644 --- a/bin/project_key.py +++ b/bin/project_key.py @@ -4,3 +4,9 @@ import pathlib def project_key(checkout_root: str, home: pathlib.Path) -> str: """The checkout's path relative to ~/code, or to / outside it: what names a project's loop-claude session, its entry in the models file and its archive folder.""" return checkout_root.removeprefix(f"{home / 'code'}/").lstrip("/") + + +def checkout_of(key: str, home: pathlib.Path) -> str: + """The checkout a project key names, the inverse of project_key: under ~/code where that folder exists, else under /.""" + under_code = home / "code" / key + return str(under_code) if under_code.is_dir() else f"/{key}" diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index 77bc8e77..b9488bee 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -7,9 +7,9 @@ import pathlib import re import typing +from transcript_archive.read import archived_outcomes, finished_chunks from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent from failure import Failure -from transcript_archive.read import finished_chunks from claude_code.entries import parse_entry from file_writes import replace_file from utc_stamp import STAMPED @@ -76,10 +76,10 @@ class Measured: def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Failure: """The figures of each chunk that finished after since, measured one chunk at a time because the archive outgrows memory. Only an archive that cannot be listed fails.""" - try: - projects = sorted({path.parent.parent for path in root.rglob("*.outcomes.md")}) - except OSError as failure: - return Failure(f"could not read the archive {root}: {failure}") + listed = archived_outcomes(root) + if isinstance(listed, Failure): + return listed + projects = sorted({root / key for key, _ in listed}) found = [] skipped = [] for project in projects: diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index a7ffcde2..07a0883f 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -3,8 +3,14 @@ import re from markdown_text import quoted from utc_stamp import STAMPED +TASK = "Task: " FINISHED = "Verdict: finished" UNFINISHED = "Verdict: unfinished" +INTERRUPTED = "Verdict: interrupt" +ANSWERED = "Verdict: quoted answer" +# The file opens with the task, then a blank line, then the first stamped outcome. +TASK_AT = re.compile(rf"\A{re.escape(TASK)}(.*?)\n\n{STAMPED} ", re.DOTALL) +ANY_VERDICT_AT = re.compile(rf"^({STAMPED}) ({'|'.join(re.escape(verdict) for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED))})$", re.MULTILINE) FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE) UNFINISHED_AT = re.compile(rf"^{STAMPED} {re.escape(UNFINISHED)}$", re.MULTILINE) # A verdict closes each cycle the judge ruled on; an interrupt or a stop closes none. @@ -24,11 +30,11 @@ def unfinished(worker: str, evidence: str) -> str: def interrupted(question: str, evidence: str) -> str: - return f"Verdict: interrupt\n\n{question}\n\nEvidence:\n{quoted(evidence)}" + return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}" def answered(question: str, sources: str, answer: str, evidence: str) -> str: - return f"Verdict: quoted answer\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}" + return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}" def stepped_up(worker: str) -> str: @@ -50,3 +56,15 @@ def workers(outcomes: str) -> list[tuple[str, str]]: if outcome.startswith(NAMES_A_WORKER) and last.startswith(WORKER): found.append((start[1], last.removeprefix(WORKER))) return found + + +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) + return found[1] if found else None + + +def first_verdict(outcomes: str) -> tuple[str, str] | None: + """The UTC stamp and the verdict, such as FINISHED, of the first verdict in an outcomes file; None when it holds none.""" + found = ANY_VERDICT_AT.search(outcomes) + return (found[1], found[2]) if found else None diff --git a/bin/transcript_archive/read.py b/bin/transcript_archive/read.py index 6db532eb..3e608194 100644 --- a/bin/transcript_archive/read.py +++ b/bin/transcript_archive/read.py @@ -22,12 +22,25 @@ def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Fail copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8")))) if copies: finished, outcomes = copies[-1] - found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl")))) + found.append(FinishedChunk(folder.name, finished, transcript_of(outcomes), sorted(folder.glob("session/*/subagents/*.jsonl")))) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read the archive {project_archive}: {failure}") return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder)) +def archived_outcomes(root: pathlib.Path) -> list[tuple[str, pathlib.Path]] | Failure: + """Each outcomes file in the archive at root, with the key of the project it belongs to, sorted.""" + try: + return sorted((str(path.parent.parent.relative_to(root)), path) for path in root.rglob("*.outcomes.md")) + except OSError as failure: + return Failure(f"could not read the archive {root}: {failure}") + + +def transcript_of(outcomes: pathlib.Path) -> pathlib.Path: + """The transcript copy an outcomes file sits beside.""" + return outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl") + + def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: """The worker's transcript, then each subagent's.""" try: diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index abeefc2a..767660e3 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -8,10 +8,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from project_key import checkout_of, project_key from failure import Failure from transcript_archive import outcomes, read, write from transcript_archive.location import project_archive -from project_key import project_key from utc_stamp import utc NOW = 1790000000 @@ -94,6 +94,12 @@ class Location(unittest.TestCase): self.assertEqual(project_archive("/h/code/log", home, {}), pathlib.Path("/h/.claude/loop-claude-transcripts/log")) self.assertEqual(project_archive("/h/code/log", home, {"LOOP_CLAUDE_TRANSCRIPTS": "/a"}), pathlib.Path("/a/log")) + def test_finds_the_checkout_a_key_names_under_code_or_else_under_the_root(self): + with tempfile.TemporaryDirectory() as home: + (pathlib.Path(home) / "code" / "log").mkdir(parents=True) + self.assertEqual(checkout_of("log", pathlib.Path(home)), f"{home}/code/log") + self.assertEqual(checkout_of("home/me/.claude", pathlib.Path(home)), "/home/me/.claude") + if __name__ == "__main__": unittest.main() diff --git a/bin/transcript_archive/write.py b/bin/transcript_archive/write.py index ba72e7ea..9020fc74 100644 --- a/bin/transcript_archive/write.py +++ b/bin/transcript_archive/write.py @@ -7,6 +7,7 @@ from transcript_archive.location import chunk_folder from failure import Failure from file_writes import make_private, replace_file from claude_code.session import session_files +from transcript_archive.outcomes import TASK from utc_stamp import utc @@ -27,7 +28,7 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a if copy.exists() and outcomes.exists(): return add_outcome(outcomes, stamped) # The copy lands last, so a copy on disk always has its outcomes and its session's files beside it. - for dest, data in ((outcomes, f"Task: {task}\n\n{stamped}\n".encode()), (copy, raw)): + for dest, data in ((outcomes, f"{TASK}{task}\n\n{stamped}\n".encode()), (copy, raw)): if unwritten := replace_file(dest, data): return unarchived(dest, unwritten.reason) print(f"transcript: {copy}", file=sys.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index fe27e387..2b142089 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -182,7 +182,7 @@ The cost of a cheaper worker shows as extra review rounds and unfinished verdict A model off the ladder routes nothing: claude runs it at the effort its settings give. R + C steps a task from the project's rung: 2–4 three rungs down, 5–6 two down, 7–8 one down, 9–10 none, 11–12 one up, 13–14 two up, 15–16 three up, 17 and above four up. A step past either end stops there. The bands spread the R + C that `todo.md`'s items held on 2026-10-14, 2 to 12, across the rungs, so most tasks step down. S never moves a rung, so a huge task with low R and C runs cheap. While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers inherit the worker's higher rung until item 90 routes them. `score-outcomes` had too few finished chunks to ground the bands, and a change to the ladder or the bands is lilleman's. -The judge runs on the rung its chunk's item picks, never below the project's rung, and keeps that rung when the worker steps up. Without an item, it runs on the project's rung. On 2026-10-15, `bin/judge-replay claude-opus-5-5` replayed the latest 15 archived verdicts of each kind from the Opus 5.5 projects, 39 in all. Today's judge, Opus 5.5 at the xhigh `settings.json` sets, reproduced 31 of them. The other 8 rest on records and judge rules that have since changed, so no rung is held to them. On the 31, Haiku 5.5 missed 7 at xhigh and 8 at max, misquoting the transcript in 4 of the 15. Sonnet 5.5 at high missed 3 interrupts, and Opus 5.5 at medium missed none. A missed interrupt lets the worker settle a decision that is lilleman's (goal 1.2), so the judge never runs below the project's rung. Above it, an item of R + C 12 or less still runs the judge below xhigh (goal 1.4). Replay again when a new model joins the ladder. +The judge runs on the rung its chunk's item picks, never below the project's rung, and keeps that rung when the worker steps up. Without an item, it runs on the project's rung. On 2026-10-15, `bin/judge-replay claude-opus-5-5` replayed the latest 15 archived verdicts of each kind from the Opus 5.5 projects, 39 in all. The reference judge, Opus 5.5 at the xhigh effort `settings.json` gave every judge before, reproduced 31 of them. The other 8 rest on records and judge rules that have since changed, so no rung is held to them. On the 31, Haiku 5.5 missed 7 at xhigh and 8 at max. Even without the 4 replies that misquoted the transcript, which the loop would have retried, it missed 6 and 5. Sonnet 5.5 at high returned another kind on 3 interrupts, and Opus 5.5 at medium missed none. A missed interrupt lets the worker settle a decision that is lilleman's (goal 1.2), so the judge never runs below the project's rung. Only Opus 5.5 was replayed, so the judge of a project on another model keeps the effort its settings give until `judge-replay` covers that model (goal 1.1); `JUDGE_REPLAYED` in `bin/loop_claude/routing.py` lists the covered models. Above the project's rung, the judge climbs with the item as the worker does. Every routed chunk on record had an item of R + C 9, so the replay could not show that the project's rung suffices for harder items. For R + C 11 to 14 the judge still runs at or below xhigh (goal 1.4), and from 15 lilleman wants the highest quality at any price. Replay again when a new model joins the ladder. The worker delegates a task only when it needs just the task's conclusion: a search or read across many files, or work independent enough to run in parallel. Edits, and whatever it must check line by line, stay in its own thread, since it would read a delegated diff again to check it. Measured over archived worker transcripts, subagent reports cost a median 8% of the worker's peak context, and `sed -n` and `grep` output made up 41% of its Bash results, so delegated searches save the most context. It scores each delegated task's R and C as for an item, and `bin/subagent-rung` turns them into the Agent tool's model and effort, counted from the project's rung. The rule names both, because the Agent tool sets a subagent's effort only when instructions ask. `CLAUDE.md` states the rule, since it holds in every session.