diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e65db3e..a25c6d4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `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 one rung above the project's model, which for Opus 5.5 is Opus 5.5 at high effort, and so on up to four rungs. The worker never runs below the project's model. 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 archived verdict name the worker's rung. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on a hard item to cost more, and to need fewer review rounds. A loop started before this change exits 1 at its next reload; rerun it. +- `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 one rung above the project's model, which for Opus 5.5 is Opus 5.5 at high effort, and so on up to four rungs. The worker never runs below the project's model's cheapest rung, which for Opus 5.5 is medium effort, below the xhigh `settings.json` sets. 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 verdict and stop in the archive, name the worker's rung; a rerun resumes an open chunk on the rung it last ran. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on an easy item to cost less than under xhigh, and one on a hard item to cost more. - A session reads `todo.md` up to `## Details`, and the details of only the items its chunk takes. It reads a `docs/decisions.md` entry only where the entry's title leaves open what it needs. Both rules are in `CLAUDE.md`, so they hold from a session's start. The decisions rule replaces one in `rules/decisions.md`, which loads only once a session has opened `docs/decisions.md` or `AGENTS.md`. A chunk's opening line now counts the unreleased changes instead of listing them. Expect fewer tokens read before a chunk's first commit. - larv-review's stability and product-owner reviewers report only a defect, a requirement of the plan or the goals that the change breaks, a breach of a technical principle, or for stability a hard place the change touches; the stability reviewer leaves the style of comments to the prose reviewer, which now also reads help and error text. Each architect finding names a concrete later change the PR makes harder, and one that names none is dropped. The prose pass runs only on a chunk that changes prose a reader reads, such as docs, comments, help text or `todo.md`, and skips a code-only chunk. Expect fewer findings and fewer review rounds. - Every `todo.md` item carries a C score, how hard the change is to get right, from 1 to 10, in a column after S. C stays out of the score. `rank_todo.py` fails on an items table without the column, and the rule hook then blocks committing that `todo.md`. Before the next commit that changes a project's `todo.md`, add the column and score every item's C, as `rank_todo.py --help` shows. diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 772ff76b..14881d83 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -10,6 +10,7 @@ from claude_code.entries import hit_limit, limit_said, parse_entry, structured_o from loop_claude.project.records import HUMAN_RULE_NAMES from loop_claude.cycle.retry import Limited, retried from loop_claude.stop import Stop +from todo_table import TOP_SCORE # Routes the next cycle's worker; loop-claude never steps it down, so the item the chunk was routed on may count too. BUNDLED = "The highest R + C the agent states for a todo.md item it took into this chunk; 0 when it states none." @@ -61,8 +62,7 @@ class Reply: REPLY_TYPES = typing.get_type_hints(Reply) JSON_TYPES = {bool: "boolean", int: "integer", str: "string"} -# R and C each run from 1 to 10. -HIGHEST_R_PLUS_C = 20 +HIGHEST_R_PLUS_C = 2 * TOP_SCORE JUDGE_SCHEMA = { "properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)}, "required": list(REPLY_TYPES), diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 85acf13e..103f03ed 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -1,6 +1,6 @@ from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES from markdown_text import quoted -from loop_claude.loop.routing import Route +from loop_claude.routing import Route def either(names: tuple[str, ...]) -> str: """The names as `a, b or c`.""" diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 04810d3c..3b5fc656 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -14,7 +14,7 @@ from loop_claude.paths import Paths from loop_claude.cycle import prompts from claude_code.transcript import read_transcript, render from loop_claude.cycle.retry import retried -from loop_claude.loop.routing import Route +from loop_claude.routing import Route from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.stop import Stop @@ -50,7 +50,7 @@ def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished: def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: path = transcript_file(cycle.session) - failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(why), cycle.effects.now()) if path else None + failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None # A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once. return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index f1f6b0c6..e025ac25 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -48,8 +48,10 @@ model's cheapest rung. The worker's first prompt names the rung and the item, an each other item the chunk takes in, with its R + C. The judge reports the highest R + C it sees the worker state, and the next cycle steps up to the rung that picks, never down. Every second unfinished verdict on a chunk steps it up one rung. A rung an edit took off the ladder counts as -the model's cheapest. A rerun routes an open chunk afresh. The archive records each verdict's rung, -with the item and R + C that routed the chunk. +the model's cheapest. Each verdict and each stop archived names the worker's rung, with the item +and R + C that routed the chunk; a rerun resumes an open chunk on the latest rung named there, while +that is at or above the model's cheapest. A todo.md that cannot be read or parsed is said on stderr, +and the chunk runs on the model's cheapest rung. A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds: the loop reloads into the edited script. @@ -95,16 +97,19 @@ from loop_claude.project.checkout import checkout_root from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG from loop_claude.effects import Effects +from failure import Failure from loop_claude.cycle.judge import Finished, Unfinished -from loop_claude.loop.routing import first_route, Route, routed_item, stepped +from loop_claude.routing import first_route, kept, Route, route_from, 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 from loop_claude.paths import Paths from transcript_archive.location import project_archive from project_key import project_key from model_routing.ladder import project_rung, Rung from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records -from claude_code.session import session_named +from claude_code.session import Session, session_named, transcript_file from loop_claude.stop import Stop @@ -141,7 +146,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(models, Stop): return models anchor = project_rung(models.worker) - loop_run = routed(loop_run, anchor) + root = loop_run.root + loop_run = routed(loop_run, anchor, lambda: archived_route(archive, 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(effects=effects, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) @@ -150,28 +156,44 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc loop_run = after_verdict(loop_run, anchor, verdict) -def routed(loop_run: LoopRun, anchor: int | None) -> LoopRun: - """The loop run with its chunk's route; a chunk is routed once, as it starts, and not at all off the ladder.""" +def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun: + """The loop run with its chunk's route, none off the ladder. A chunk keeps its route, or on a rerun the one its archive last names, + while that is at or above anchor, the project's rung; else the plan item routes it afresh.""" if anchor is None: return dataclasses.replace(loop_run, route=None) - if loop_run.route: - return loop_run - return dataclasses.replace(loop_run, route=first_route(anchor, routed_item(read_todo(loop_run.root)))) + route = loop_run.route or archived() + return dataclasses.replace(loop_run, route=route if route and kept(route, anchor) else first_route(anchor, item())) -def after_verdict(loop_run: LoopRun, anchor: int | None, verdict: Finished | Unfinished) -> LoopRun: +def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun: if isinstance(verdict, Finished): return dataclasses.replace(loop_run, route=None, unfinished_evidence="") - route = stepped(anchor, loop_run.route, verdict.bundled) if anchor is not None and loop_run.route else loop_run.route + route = stepped(anchor, loop_run.route, verdict.bundled) if anchor and loop_run.route else loop_run.route return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence) -def read_todo(root: str) -> str: - """The checkout's todo.md, empty where it cannot be read: a chunk without a plan item runs on the project's rung.""" +def archived_route(archive: pathlib.Path, session: Session) -> Route | None: + """The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged.""" + transcript = transcript_file(session) + worker = latest_worker(archive, transcript) if transcript else None + if isinstance(worker, Failure): + print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr) + return None + return route_from(worker) if worker else None + + +def plan_item(root: str) -> Item | None: + """The item that routes a chunk; None without one, so the chunk runs on the project's rung.""" try: - return pathlib.Path(root, "todo.md").read_text(encoding="utf-8") - except (OSError, ValueError): - return "" + item = routed_item(pathlib.Path(root, "todo.md").read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (OSError, ValueError) as failure: + item = Failure(f"could not read todo.md: {failure}") + if isinstance(item, Failure): + print(f"routing on the project's rung: {item.reason}", file=sys.stderr) + return None + return item def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop: diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 6e7f1d77..31e7f818 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -7,7 +7,7 @@ import types import typing from loop_claude.effects import Effects -from loop_claude.loop.routing import Route +from loop_claude.routing import Route from loop_claude.stop import Stop RELOAD_FLAG = "--reloaded" @@ -32,21 +32,23 @@ def decode_handed(handed: str, kind: type[T]) -> T | None: except ValueError: return None decoded = decoded_as(fields, kind) - return None if decoded is REJECTED else decoded + return None if decoded is REJECTED else typing.cast(T, decoded) REJECTED = object() def decoded_as(value: object, kind: typing.Any) -> typing.Any: - """value as kind, or REJECTED: a dataclass from an object holding exactly its fields, a union's first member that fits, else a value of exactly kind.""" + """value as kind, or REJECTED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind.""" if isinstance(kind, types.UnionType): return next((found for option in typing.get_args(kind) if (found := decoded_as(value, option)) is not REJECTED), REJECTED) if isinstance(kind, type) and dataclasses.is_dataclass(kind): shape = typing.get_type_hints(kind) - if not isinstance(value, dict) or value.keys() != shape.keys(): + # A field with a default may be missing, so a field added since the running script started does not stop the loop. + required = {field.name for field in dataclasses.fields(kind) if field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING} + if not isinstance(value, dict) or not required <= value.keys() <= shape.keys(): return REJECTED - fields = {name: decoded_as(value[name], type_) for name, type_ in shape.items()} + fields = {name: decoded_as(field, shape[name]) for name, field in value.items()} return REJECTED if any(field is REJECTED for field in fields.values()) else kind(**fields) return value if type(value) is kind else REJECTED diff --git a/bin/loop_claude/loop/routing.py b/bin/loop_claude/loop/routing.py deleted file mode 100644 index 26fb380c..00000000 --- a/bin/loop_claude/loop/routing.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Which ladder rung a chunk's worker runs on: docs/decisions.md → `routing:`.""" -import dataclasses - -from model_routing.ladder import climbed, index_of, LADDER, picked, Rung -from failure import Failure -from todo_table import Item, items - -UNFINISHED_PER_STEP = 2 - - -@dataclasses.dataclass(frozen=True) -class Route: - """A chunk's worker rung, the plan item whose R + C picked it (0 for none), and the unfinished verdicts since it last stepped up.""" - rung: Rung - item: int = 0 - risk_and_complexity: int = 0 - unfinished: int = 0 - - def __str__(self) -> str: - return f"{self.rung}, routed by item {self.item}'s R + C of {self.risk_and_complexity}" if self.item else str(self.rung) - - -def routed_item(todo: str) -> Item | None: - """The next release's first item that waits on no question, as rank_todo.py ranks the table; None when there is none, or it has no C.""" - found = items(todo) - if not found or isinstance(found, Failure): - return None - next_release = min(item.release for item in found) - takes = next((item for item in found if item.release == next_release and item.exempt != "question"), None) - return takes if takes and takes.risk_and_complexity else None - - -def first_route(anchor: int, item: Item | None) -> Route: - """The route a chunk starts on: the rung its item's R + C picks from anchor, the project's rung, never below it.""" - if item is None: - return Route(LADDER[anchor]) - return Route(LADDER[max(anchor, picked(anchor, item.risk_and_complexity))], item.id, item.risk_and_complexity) - - -def stepped(anchor: int, route: Route, bundled: int) -> Route: - """The route after one more unfinished verdict; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none. - - A rung an edit took off the ladder counts as the project's rung. - """ - rung = index_of(route.rung) - rung = max(anchor if rung is None else rung, picked(anchor, bundled) if bundled else anchor) - unfinished = route.unfinished + 1 - if unfinished >= UNFINISHED_PER_STEP: - return dataclasses.replace(route, rung=LADDER[climbed(rung, 1)], unfinished=0) - return dataclasses.replace(route, rung=LADDER[rung], unfinished=unfinished) diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py new file mode 100644 index 00000000..bdb0410f --- /dev/null +++ b/bin/loop_claude/routing.py @@ -0,0 +1,64 @@ +"""Which ladder rung a chunk's worker runs on: docs/decisions.md → `routing:`.""" +import dataclasses +import re + +from failure import Failure +from model_routing.ladder import highest, picked, Rung, stepped_up +from todo_table import Item, items + +UNFINISHED_PER_STEP = 2 +ROUTED = re.compile(r"(?P\S+) at (?P\S+) effort(?:, routed by item (?P[0-9]+)'s R \+ C of (?P[0-9]+))?") + + +@dataclasses.dataclass(frozen=True) +class Route: + """A chunk's worker rung and the plan item whose R + C picked it, 0 for none. + + unfinished is the loop's count of unfinished verdicts since the rung last stepped up, kept here so a reload hands it over with the rung. + """ + rung: Rung + item: int = 0 + risk_and_complexity: int = 0 + unfinished: int = 0 + + def __str__(self) -> str: + """What the archive records as each verdict's worker; ROUTED reads it back.""" + return f"{self.rung}, routed by item {self.item}'s R + C of {self.risk_and_complexity}" if self.item else str(self.rung) + + +def route_from(worker: str) -> Route | None: + """The route an archived worker line names; None for a model run off the ladder.""" + found = ROUTED.fullmatch(worker) + if not found: + return None + return Route(Rung(found["model"], found["effort"]), int(found["item"] or 0), int(found["sum"] or 0)) + + +def routed_item(todo: str) -> Item | Failure | None: + """The next release's first row that waits on no question, in the table's order, which rank_todo.py keeps ranked; None when there is none, or it has no C.""" + found = items(todo) + if isinstance(found, Failure) or not found: + return found if isinstance(found, Failure) else None + next_release = min(item.release for item in found) + takes = next((item for item in found if item.release == next_release and item.exempt != "question"), None) + return takes if takes and takes.risk_and_complexity else None + + +def first_route(anchor: Rung, item: Item | None) -> Route: + """The route a chunk starts on: the rung its item's R + C picks from anchor, the project's rung, never below it.""" + if item is None: + return Route(anchor) + return Route(highest(anchor, picked(anchor, item.risk_and_complexity)), item.id, item.risk_and_complexity) + + +def kept(route: Route, anchor: Rung) -> bool: + """Whether a route carries on from anchor, the project's rung: its rung is on the ladder at or above it.""" + return highest(route.rung, anchor) == route.rung + + +def stepped(anchor: Rung, route: Route, bundled: int) -> Route: + """The route after one more unfinished verdict; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none.""" + rung = highest(route.rung, anchor, picked(anchor, bundled) if bundled else anchor) + if route.unfinished + 1 >= UNFINISHED_PER_STEP: + return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0) + return dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 8b1970c3..a52d9a20 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -364,9 +364,9 @@ class Cycles(unittest.TestCase): self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name]) self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout) copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()} - self.assertEqual(sorted(copies), [" Stopped: Ctrl-C\n", " Verdict: finished\n\nWorker: worker-model\n\nEvidence:\n> landed-it\n", " Verdict: unfinished\n\nWorker: worker-model\n\nEvidence:\n> started\n"]) - self.assertIn('"text": "landed-it"', copies[" Verdict: finished\n\nWorker: worker-model\n\nEvidence:\n> landed-it\n"]) - self.assertIn('"text": "next chunk"', copies[" Stopped: Ctrl-C\n"]) + self.assertEqual(sorted(copies), [" Stopped: Ctrl-C\n\nWorker: worker-model\n", " Verdict: finished\n\nEvidence:\n> landed-it\n\nWorker: worker-model\n", " Verdict: unfinished\n\nEvidence:\n> started\n\nWorker: worker-model\n"]) + self.assertIn('"text": "landed-it"', copies[" Verdict: finished\n\nEvidence:\n> landed-it\n\nWorker: worker-model\n"]) + self.assertIn('"text": "next chunk"', copies[" Stopped: Ctrl-C\n\nWorker: worker-model\n"]) self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1) def test_routes_the_worker_by_its_items_r_plus_c_and_steps_it_up_within_the_chunk(self): @@ -392,8 +392,20 @@ class Cycles(unittest.TestCase): self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)}) self.assertIn("loop-claude runs you on claude-opus-5-5 at high effort, the rung item 4's R + C of 11 picks. When the chunk takes in another todo.md item, say so, naming that item and its R + C.", argument(workers[0], "-p")) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) - self.assertIn(" Verdict: unfinished\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n\nEvidence:\n> three\n", outcomes) - self.assertIn(" Verdict: finished\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n\nEvidence:\n> four\n", outcomes) + self.assertIn(" Verdict: unfinished\n\nEvidence:\n> three\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n", outcomes) + self.assertIn(" Verdict: finished\n\nEvidence:\n> four\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes) + + def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self): + checkout = Checkout(self) + checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" + (checkout.root / "todo.md").write_text(TODO) + run = checkout.run([worker(), judge(), worker(), judge()]) + self.assertEqual(run.code, 130) + self.assertEqual(argument(run.calls[-1], "--effort"), "xhigh") + (checkout.root / "todo.md").unlink() + run = checkout.run([worker()]) + self.assertIsNotNone(argument(run.calls[0], "--resume")) + self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh")) def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self): checkout = Checkout(self) @@ -517,7 +529,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\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") + self.assertEqual(verdict, f"Task: {TASK}\n\n Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\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: worker-model\n") self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700) self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr) session = argument(run.calls[0], "--session-id") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index da80fc86..5de17c25 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -21,10 +21,10 @@ from claude_code import entries, session from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker -from model_routing.ladder import LADDER, project_rung, Rung +from model_routing.ladder import LADDER, Rung from loop_claude.cycle.retry import Limited -from loop_claude.loop import main, reload, routing -from loop_claude import paths +from loop_claude.loop import main, reload +from loop_claude import paths, routing from transcript_archive.location import project_archive from loop_claude.stop import Stop @@ -178,7 +178,7 @@ 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)), Finished("working")) - self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nWorker: worker-model\n\nEvidence:\n> working\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nWorker: worker-model\n"]) self.assertIsNone(session.transcript_file(self.session)) def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self): @@ -190,14 +190,14 @@ 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(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nWorker: worker-model\n\nEvidence:\n> working\n"] * 2) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nWorker: worker-model\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) self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) - self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: worker-model\n"]) def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) @@ -243,7 +243,7 @@ class Cycles(unittest.TestCase): return 0 fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()]) self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working")) - self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nWorker: worker-model\n\nEvidence:\n> working\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nWorker: worker-model\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) @@ -261,7 +261,7 @@ class Cycles(unittest.TestCase): 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 = "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" - 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\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) + 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\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) def test_stops_when_a_quoted_answer_cannot_be_archived(self): self.archive.parent.mkdir(parents=True) @@ -290,7 +290,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\nWorker: worker-model\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n"]) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: worker-model\n"]) def test_stops_when_the_worker_leaves_no_transcript(self): fake = FakeEffects(streams=[Streamed(0)]) @@ -396,38 +396,57 @@ TODO = """# todo class Routing(unittest.TestCase): - OPUS = project_rung("claude-opus-5-5") + OPUS = Rung("claude-opus-5-5", "medium") + HIGH = Rung("claude-opus-5-5", "high") + XHIGH = Rung("claude-opus-5-5", "xhigh") def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): self.assertEqual(routing.routed_item(TODO).id, 3) self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"))) self.assertIsNone(routing.routed_item("# todo\n")) - self.assertIsNone(routing.routed_item(TODO.replace("| 5 | 3 |", "| x | 3 |"))) + self.assertEqual(routing.routed_item(TODO.replace("| 5 | 3 |", "| x | 3 |")), Failure("item 3's R 'x' is not a whole number from 1 to 10")) def test_starts_a_chunk_on_the_rung_its_items_r_plus_c_picks_never_below_the_projects(self): - self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), routing.Route(Rung("claude-opus-5-5", "high"), 3, 11)) + self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), routing.Route(self.HIGH, 3, 11)) cheap = routing.routed_item(TODO.replace("| 5 | 3 | 6 |", "| 1 | 3 | 1 |")) - self.assertEqual(routing.first_route(self.OPUS, cheap), routing.Route(LADDER[self.OPUS], 3, 2)) - self.assertEqual(routing.first_route(self.OPUS, None), routing.Route(LADDER[self.OPUS])) + self.assertEqual(routing.first_route(self.OPUS, cheap), routing.Route(self.OPUS, 3, 2)) + self.assertEqual(routing.first_route(self.OPUS, None), routing.Route(self.OPUS)) def test_steps_up_a_rung_after_every_second_unfinished_verdict(self): - route = routing.Route(LADDER[self.OPUS], 3, 9) - once = routing.stepped(self.OPUS, route, 0) - self.assertEqual(once, routing.Route(LADDER[self.OPUS], 3, 9, 1)) - self.assertEqual(routing.stepped(self.OPUS, once, 0), routing.Route(LADDER[self.OPUS + 1], 3, 9, 0)) + once = routing.stepped(self.OPUS, routing.Route(self.OPUS, 3, 9), 0) + self.assertEqual(once, routing.Route(self.OPUS, 3, 9, 1)) + self.assertEqual(routing.stepped(self.OPUS, once, 0), routing.Route(self.HIGH, 3, 9, 0)) self.assertEqual(routing.stepped(self.OPUS, routing.Route(LADDER[-1], unfinished=1), 0).rung, LADDER[-1]) def test_steps_up_to_the_rung_a_bundled_items_r_plus_c_picks_and_never_down(self): - self.assertEqual(routing.stepped(self.OPUS, routing.Route(LADDER[self.OPUS]), 13).rung, LADDER[self.OPUS + 2]) - self.assertEqual(routing.stepped(self.OPUS, routing.Route(LADDER[self.OPUS + 2]), 11).rung, LADDER[self.OPUS + 2]) - self.assertEqual(routing.stepped(self.OPUS, routing.Route(LADDER[self.OPUS], unfinished=1), 13).rung, LADDER[self.OPUS + 3]) + self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.OPUS), 13).rung, self.XHIGH) + self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.XHIGH), 11).rung, self.XHIGH) + self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.OPUS, unfinished=1), 13).rung, Rung("claude-opus-5-5", "max")) def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): - self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 0).rung, LADDER[self.OPUS]) + self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 0).rung, self.OPUS) - def test_names_the_item_that_routed_the_chunk(self): - self.assertEqual(str(routing.Route(Rung("claude-opus-5-5", "high"), 3, 11)), "claude-opus-5-5 at high effort, routed by item 3's R + C of 11") + def test_archives_the_route_in_a_line_it_reads_back(self): + route = routing.Route(self.HIGH, 3, 11) + self.assertEqual(str(route), "claude-opus-5-5 at high effort, routed by item 3's R + C of 11") + self.assertEqual(routing.route_from(str(route)), route) + self.assertEqual(routing.route_from(str(routing.Route(self.HIGH))), routing.Route(self.HIGH)) self.assertEqual(str(routing.Route(Rung("worker-model"))), "worker-model") + self.assertIsNone(routing.route_from("worker-model")) + + def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_projects_rung_and_else_routes_afresh(self): + def run_with(route=None): + return main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=route) + item = routing.routed_item(TODO) + archived = routing.Route(self.XHIGH, 3, 11) + def never(): + raise AssertionError("not asked") + self.assertIsNone(main.routed(run_with(archived), None, never, never).route) + self.assertEqual(main.routed(run_with(archived), self.OPUS, never, never).route, archived) + self.assertEqual(main.routed(run_with(), self.OPUS, lambda: archived, never).route, archived) + self.assertEqual(main.routed(run_with(), self.OPUS, lambda: None, lambda: item).route, routing.Route(self.HIGH, 3, 11)) + below = routing.Route(Rung("claude-sonnet-5-5", "high")) + self.assertEqual(main.routed(run_with(below), self.OPUS, never, lambda: None).route, routing.Route(self.OPUS)) class WorkerArgs(unittest.TestCase): @@ -527,6 +546,14 @@ class Verdict(unittest.TestCase): self.assertEqual(verdict_from({"bundled": 0, "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) self.assertEqual(verdict_from(None), Failure("the judge returned no reply")) + def test_takes_a_bundled_r_plus_c_from_0_to_20_on_an_unfinished_verdict(self): + reply = {"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""} + self.assertEqual(verdict_from({**reply, "bundled": 20}), Unfinished("e", 20)) + self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer")) + for bundled in (21, -1): + with self.subTest(bundled=bundled): + self.assertEqual(verdict_from({**reply, "bundled": bundled}), Failure(f"the judge's bundled R + C {bundled} is not from 0 to 20")) + class LoopRuns(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): @@ -553,6 +580,9 @@ class LoopRuns(unittest.TestCase): del handed["route"]["rung"] self.assertIsNone(reload.decode_handed(json.dumps(handed), main.LoopRun)) + def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self): + self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""}), main.LoopRun), main.LoopRun(3, "/r", "do it", "")) + def test_stops_when_the_reload_cannot_start_python(self): with tempfile.TemporaryDirectory() as root: launcher = pathlib.Path(root, "loop-claude") diff --git a/bin/model_routing/ladder.py b/bin/model_routing/ladder.py index be62bdad..b6a2d62b 100644 --- a/bin/model_routing/ladder.py +++ b/bin/model_routing/ladder.py @@ -1,11 +1,11 @@ -"""The routing ladder, and the step an R + C moves a task from the project's rung: docs/decisions.md → `routing:`.""" +"""The routing ladder, and the rung an R + C picks from the project's rung: docs/decisions.md → `routing:`.""" import dataclasses @dataclasses.dataclass(frozen=True) class Rung: model: str - # Empty leaves the effort to claude's default for the model, as for a model off the ladder. + # Empty leaves the effort to claude's settings, as for a model off the ladder. effort: str = "" def flags(self) -> list[str]: @@ -35,24 +35,29 @@ BANDS = ((4, -3), (6, -2), (8, -1), (10, 0), (12, 1), (14, 2), (16, 3)) ABOVE_THE_BANDS = 4 -def project_rung(model: str) -> int | None: - """The index of the model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder.""" - return next((index for index, rung in enumerate(LADDER) if rung.model == model), None) +def project_rung(model: str) -> Rung | None: + """The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder.""" + return next((rung for rung in LADDER if rung.model == model), None) -def steps(risk_and_complexity: int) -> int: - return next((step for highest, step in BANDS if risk_and_complexity <= highest), ABOVE_THE_BANDS) +def picked(anchor: Rung, risk_and_complexity: int) -> Rung: + """The rung a task's R + C picks from anchor, the project's rung, stopping at either end of the ladder.""" + return climbed(anchor, next((step for highest, step in BANDS if risk_and_complexity <= highest), ABOVE_THE_BANDS)) -def climbed(index: int, by: int) -> int: - """The rung by steps from index, stopping at either end of the ladder.""" - return max(0, min(len(LADDER) - 1, index + by)) +def stepped_up(rung: Rung) -> Rung: + """The rung above, or the top one; a rung off the ladder steps to the bottom one.""" + return climbed(rung, 1) -def picked(anchor: int, risk_and_complexity: int) -> int: - """The rung a task's R + C picks from anchor, the project's rung.""" - return climbed(anchor, steps(risk_and_complexity)) +def highest(*rungs: Rung) -> Rung: + """The most competent of the rungs; one off the ladder ranks below every rung on it.""" + return max(rungs, key=position) -def index_of(rung: Rung) -> int | None: - return LADDER.index(rung) if rung in LADDER else None +def climbed(rung: Rung, by: int) -> Rung: + return LADDER[max(0, min(len(LADDER) - 1, position(rung) + by))] + + +def position(rung: Rung) -> int: + return LADDER.index(rung) if rung in LADDER else -1 diff --git a/bin/model_routing/test_ladder.py b/bin/model_routing/test_ladder.py index 873d543f..3f01adda 100644 --- a/bin/model_routing/test_ladder.py +++ b/bin/model_routing/test_ladder.py @@ -4,7 +4,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from model_routing.ladder import climbed, LADDER, project_rung, Rung, steps +from model_routing.ladder import highest, LADDER, picked, project_rung, Rung, stepped_up + +OPUS = Rung("claude-opus-5-5", "medium") class Ladder(unittest.TestCase): @@ -15,20 +17,26 @@ class Ladder(unittest.TestCase): self.assertEqual(len(set(LADDER)), len(LADDER)) def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self): - self.assertEqual(LADDER[project_rung("claude-opus-5-5")], Rung("claude-opus-5-5", "medium")) - self.assertEqual(LADDER[project_rung("claude-sonnet-5-5")], Rung("claude-sonnet-5-5", "high")) + self.assertEqual(project_rung("claude-opus-5-5"), OPUS) + self.assertEqual(project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high")) self.assertIsNone(project_rung("claude-opus-5")) self.assertIsNone(project_rung("opus")) def test_steps_each_band_of_r_plus_c_from_the_projects_rung(self): - self.assertEqual([steps(total) for total in range(2, 21)], [-3, -3, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4]) + position = LADDER.index(OPUS) + self.assertEqual([LADDER.index(picked(OPUS, total)) - position for total in range(2, 21)], [-3, -3, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4]) def test_a_step_past_either_end_stops_there(self): - opus = project_rung("claude-opus-5-5") - self.assertEqual(LADDER[climbed(opus, steps(4))], Rung("claude-haiku-5-5", "xhigh")) - self.assertEqual(LADDER[climbed(opus, steps(17))], Rung("claude-fable-5-1", "max")) - self.assertEqual(climbed(0, -3), 0) - self.assertEqual(climbed(len(LADDER) - 1, 1), len(LADDER) - 1) + self.assertEqual(picked(OPUS, 4), Rung("claude-haiku-5-5", "xhigh")) + self.assertEqual(picked(OPUS, 17), Rung("claude-fable-5-1", "max")) + self.assertEqual(picked(LADDER[1], 2), LADDER[0]) + self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1]) + self.assertEqual(stepped_up(OPUS), Rung("claude-opus-5-5", "high")) + + def test_ranks_a_rung_off_the_ladder_below_every_rung_on_it(self): + self.assertEqual(highest(OPUS, LADDER[-1], LADDER[0]), LADDER[-1]) + self.assertEqual(highest(Rung("claude-opus-5-5", "low"), LADDER[0]), LADDER[0]) + self.assertEqual(stepped_up(Rung("claude-opus-5-5", "low")), LADDER[0]) def test_passes_the_effort_only_where_the_rung_names_one(self): self.assertEqual(Rung("claude-opus-5-5", "high").flags(), ["--model", "claude-opus-5-5", "--effort", "high"]) diff --git a/bin/todo_table.py b/bin/todo_table.py index 63da3cd8..5d1db610 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -3,6 +3,8 @@ import re from failure import Failure +# Each of R, S, C, A and G runs from 1 to TOP_SCORE. +TOP_SCORE = 10 EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security") COLUMNS = ("ID", "Release", "Exempt", "Item", "R", "S", "C", "A", "G", "Goals", "Score") ITEMS_HEADER = "| " + " | ".join(COLUMNS) + " |" @@ -87,8 +89,8 @@ def parse_row(row: str, header: str = ITEMS_HEADER) -> Item | Failure: for name in ("R", "S", "C", "A", "G"): if name not in named: continue - if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= 10: - return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to 10") + if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= TOP_SCORE: + return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {TOP_SCORE}") scores[name] = int(named[name]) cited = tuple(goal.strip() for goal in named["Goals"].split(",")) major, minor, patch = (int(part) for part in release.split(".")) diff --git a/bin/transcript_archive/location.py b/bin/transcript_archive/location.py index fd866667..e0e4ff7b 100644 --- a/bin/transcript_archive/location.py +++ b/bin/transcript_archive/location.py @@ -1,9 +1,16 @@ +import hashlib import pathlib import typing +from claude_code.transcript import first_timestamped_line from project_key import project_key def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path: archive = pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else home / ".claude" / "loop-claude-transcripts" return archive / project_key(checkout_root, home) + + +def chunk_folder(project_archive: pathlib.Path, transcript: bytes) -> pathlib.Path: + # Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh. + return project_archive / hashlib.sha256(first_timestamped_line(transcript)).hexdigest() diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index 20b96464..2a6746e1 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -5,14 +5,18 @@ from utc_stamp import STAMPED FINISHED = "Verdict: finished" FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE) +# An outcome opens with its UTC stamp; a verdict that closes a cycle, or a stop, ends with the worker line. +OUTCOME_AT = re.compile(rf"^({STAMPED}) ", re.MULTILINE) +CLOSES_A_CYCLE = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ") +WORKER = "Worker: " def finished(worker: str, evidence: str) -> str: - return f"{FINISHED}\n\nWorker: {worker}\n\nEvidence:\n{quoted(evidence)}" + return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}" def unfinished(worker: str, evidence: str) -> str: - return f"Verdict: unfinished\n\nWorker: {worker}\n\nEvidence:\n{quoted(evidence)}" + return f"Verdict: unfinished\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}" def interrupted(question: str, evidence: str) -> str: @@ -23,5 +27,17 @@ 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)}" -def stopped(why: str) -> str: - return f"Stopped: {why}" +def stopped(worker: str, why: str) -> str: + return f"Stopped: {why}\n\n{WORKER}{worker}" + + +def workers(outcomes: str) -> list[tuple[str, str]]: + """The UTC stamp and the worker of each outcome that closes a cycle, 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") + last = outcome.rsplit("\n", 1)[-1] + if outcome.startswith(CLOSES_A_CYCLE) and last.startswith(WORKER): + found.append((start[1], last.removeprefix(WORKER))) + return found diff --git a/bin/transcript_archive/read.py b/bin/transcript_archive/read.py index 5f47d7c6..3672fc2c 100644 --- a/bin/transcript_archive/read.py +++ b/bin/transcript_archive/read.py @@ -1,8 +1,9 @@ import dataclasses import pathlib +from transcript_archive.location import chunk_folder from failure import Failure -from transcript_archive.outcomes import FINISHED_AT +from transcript_archive.outcomes import FINISHED_AT, workers @dataclasses.dataclass(frozen=True) @@ -33,3 +34,14 @@ def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)] except OSError as failure: return Failure(f"could not read {failure.filename}: {failure.strerror}") + + +def latest_worker(project_archive: pathlib.Path, transcript: str) -> str | Failure | None: + """The worker the latest verdict archived for the transcript's chunk names; None before its first verdict.""" + try: + with open(transcript, "rb") as handle: + folder = chunk_folder(project_archive, handle.read()) + found = sorted(stamped for outcomes in folder.glob("*.outcomes.md") for stamped in workers(outcomes.read_text(encoding="utf-8"))) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read the archive {project_archive}: {failure}") + return found[-1][1] if found else None diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 9f6670a3..f9c3e00f 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -8,7 +8,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from transcript_archive import outcomes, write +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 @@ -26,8 +27,8 @@ class Archive(unittest.TestCase): self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working"), NOW)) (kept_outcomes,) = kept.glob("*/*.outcomes.md") kept_outcomes.unlink() - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("Ctrl-C"), NOW)) - self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n") + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW)) + self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: m\n") class CopyFor(unittest.TestCase): @@ -46,6 +47,28 @@ class Outcomes(unittest.TestCase): def test_the_archive_stamps_what_it_reads_back(self): self.assertRegex(f"{utc(NOW)} {outcomes.finished('m', 'merged')}", outcomes.FINISHED_AT) + def test_reads_back_the_worker_of_each_outcome_that_closes_a_cycle(self): + kept = "Task: Do it.\n\n" + "\n".join(f"{utc(NOW + offset)} {outcome}\n" for offset, outcome in enumerate([ + outcomes.unfinished("w1", "Worker: not this"), + outcomes.interrupted("Which one?\nWorker: nor this", "e"), + outcomes.stopped("w2", "the judge failed\nthree times"), + outcomes.finished("w3", "merged"), + ])) + self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")]) + + def test_names_the_worker_the_latest_outcome_of_the_transcripts_chunk_records(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.assertIsNone(read.latest_worker(kept, str(transcript))) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working"), NOW)) + transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n{"more": 1}\n') + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w2", "Ctrl-C"), NOW + 1)) + self.assertEqual(read.latest_worker(kept, str(transcript)), "w2") + self.assertIsInstance(read.latest_worker(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/bin/transcript_archive/write.py b/bin/transcript_archive/write.py index c32ba86a..ba72e7ea 100644 --- a/bin/transcript_archive/write.py +++ b/bin/transcript_archive/write.py @@ -3,8 +3,8 @@ import os import pathlib import sys +from transcript_archive.location import chunk_folder from failure import Failure -from claude_code.transcript import first_timestamped_line from file_writes import make_private, replace_file from claude_code.session import session_files from utc_stamp import utc @@ -14,8 +14,7 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a try: with open(path, "rb") as handle: raw = handle.read() - # Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh. - folder = project_archive / hashlib.sha256(first_timestamped_line(raw)).hexdigest() + folder = chunk_folder(project_archive, raw) make_private(folder) except OSError as failure: return unarchived(failure.filename, failure.strerror) diff --git a/docs/decisions.md b/docs/decisions.md index 4cbcd261..b643723e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -176,8 +176,8 @@ Valid while a mutation run on a chunk's changed lines stays cheap beside the rev The rungs, least competent first: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. -A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at its default effort. 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. The comprehension panel and the security pass stay on the project's model. `score-outcomes` had too few finished chunks to ground the bands; `todo.md` item 94 measures the routes' outcomes, and a change to the ladder or the bands is lilleman's. +A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. lilleman chose medium knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes. A model off the ladder routes nothing: claude runs it at its default effort. 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. The comprehension panel and the security pass stay on the project's model. `score-outcomes` had too few finished chunks to ground the bands; `todo.md` item 94 measures the routes' outcomes, and a change to the ladder or the bands is lilleman's. -A chunk's worker starts on the rung its item's R + C picks, never below the project's rung, until `todo.md` item 93 shows a cheaper worker costs no review rounds (goal 1.1). It steps up only as the chunk starts, after every second unfinished verdict, or when the judge reports an item taken into the chunk whose R + C picks a higher rung. A model switch inside a session discards its prompt cache. loop-claude routes on the first row of the next release in `todo.md`'s table that waits on no question. It reads neither an order the plan states in prose nor the task, so a chunk may start on another item's rung; since the worker never goes below the project's rung, that costs money, never quality. +A chunk's worker starts on the rung its item's R + C picks, never below the project's rung, until `todo.md` item 93 shows a cheaper worker costs no review rounds (goal 1.1). The project's rung itself sits below xhigh, by lilleman's choice above. It steps up only as the chunk starts, after every second unfinished verdict, or when the judge reports an item taken into the chunk whose R + C picks a higher rung. A model switch inside a session discards its prompt cache. loop-claude routes on the first row of the next release in `todo.md`'s table that waits on no question. It reads neither an order the plan states in prose nor the task, so a chunk may start on another item's rung: a higher one costs money, and a lower one holds until the judge reports the item the worker took in, after the first cycle. `todo.md` item 136 ends this, routing on the item the worker says it takes. Valid while the index ranks these models, and while no newer model joins the catalog. diff --git a/todo.md b/todo.md index d188cd45..0a967e40 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 9` -`Next ID = 136` +`Next ID = 137` | Goal | W | |---|---| @@ -31,6 +31,7 @@ Release 0.2.0 takes items 125, 114 and 124 first, whatever their scores: Shape i | 90 | 0.1.0 | | **Route each reviewer by the chunk's R + C, once a replay of past chunks shows the routed reviewer finds the 🔴 and 🟡 findings on record.** | 4 | 5 | 8 | 6 | 7 | 1.4 | 20.2 | | 92 | 0.1.0 | | **Have the worker route each subagent by its task's R + C, and delegate a task only when the worker needs just its conclusion.** | 2 | 2 | 5 | 5 | 6 | 1.4 | 19.0 | | 89 | 0.1.0 | | **Run the judge on the rung its chunk's R + C picks, once a replay of archived transcripts shows it returns the verdicts on record.** | 3 | 4 | 7 | 5 | 6 | 1.4 | 17.5 | +| 136 | 0.1.0 | decision | **Route a chunk on the item its worker says it takes, in place of the next release's first row.** | 2 | 3 | 4 | 4 | 5 | 1.4 | 14.8 | | 105 | 0.2.0 | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 3 | 5 | 6 | 1.4 | 20.0 | | 112 | 0.2.0 | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 2 | 3 | 5 | 5 | 6 | 1.1 | 19.1 | | 110 | 0.2.0 | | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed R.** | 2 | 4 | 6 | 5 | 6 | 1.1, 1.4 | 18.9 | @@ -107,6 +108,10 @@ State in `CLAUDE.md` when the worker delegates: a search or read that spans many loop-claude starts the judge itself (`bin/loop_claude/cycle/judge.py`), so it routes without any skill change. Replay the judge on archived cycles at the candidate rung, and switch only when its interrupts and verdicts match those on record. +### 136. Route a chunk on the item its worker says it takes, in place of the next release's first row. + +loop-claude routes on the first row of the next release, while the worker takes the item the plan's prose orders first, or a prerequisite, as this chunk took 88 over 93. A first row of higher R + C pays for a dearer rung all chunk; one of lower R + C holds until the judge reports the item taken in. The worker names its item in its first reply, so the judge can report that item's R + C after the first cycle; routing the first cycle right needs the item before the worker starts. + ### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose. The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer round :` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision.