diff --git a/CHANGELOG.md b/CHANGELOG.md index de27cd93..ef54f3d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them. - loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`. - A chunk now takes every unblocked item of its release that fires the same review passes, whatever its purpose: one PR title no longer has to state what the items achieve together. An item with R above 5 ships alone. `chunk-preflight` says so for such an item, and never lists one as an item that may join another. - A branch whose name is not UTF-8 now shows no branch in the status line, in place of a name with replacement characters. diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index f9650627..c16f2a76 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -1,3 +1,4 @@ +"""What loop-claude says to the worker each cycle. routed_by, review_launches, escalation and reruns build the sentences about its rungs; rungs_held says the last three again in a prompt after a step-up or an unfinished verdict.""" from model_routing.ladder import climbed, LADDER, position, review_rungs, reviewers_rung, ReviewKind, Rung from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Route from loop_claude.routing import escalation_rungs @@ -18,15 +19,15 @@ REVIEWS: tuple[tuple[str, ReviewKind], ...] = (*((f"each {agent}", kind) for kin AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it' -def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str: +def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str: """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" - escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip() - routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") + escalated = f"{escalation(route, project)}{reruns(route, project)}".lstrip() + routed = f"{routed_by(route, project)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" -def routed_by(route: Route, anchor: Rung | None) -> str: - return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}" +def routed_by(route: Route, project: Rung | None) -> str: + return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, project)}{escalation(route, project)}{reruns(route, project)}" def recount(route: Route) -> str: @@ -44,28 +45,28 @@ def preflight_failed(reason: str) -> str: return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}" -def review_launches(route: Route, anchor: Rung | None) -> str: - """Which reviews to launch on a rung other than the worker's, and on which, then the rung of each pass a replay lowered; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder. +def review_launches(route: Route, project: Rung | None) -> str: + """Which reviews to launch on a rung other than the worker's, and on which, then the rung of each pass a replay lowered; below the project's rung also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder. For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: ` Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.` """ - if anchor is None: + if project is None: return "" - rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on()) + rungs, reviewers = review_rungs(project, route.rung, route.reviewed_on()), reviewers_rung(project, route.rung, route.reviewed_on()) lowered_launches = "".join(f" Launch {reviews} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for reviews, rung in lowered(rungs, reviewers)) scan = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." if rungs["security"] != route.rung else "" - planning = f" Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {anchor.model} ` prints." if position(route.rung) < position(anchor) else "" - return f"{shared_launches(rungs, reviewers, route, anchor)}{lowered_launches}{scan}{planning}{taken_in_launches(route, anchor)}" + planning = f" Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} ` prints." if position(route.rung) < position(project) else "" + return f"{shared_launches(rungs, reviewers, route, project)}{lowered_launches}{scan}{planning}{taken_in_launches(route, project)}" -def shared_launches(rungs: dict[ReviewKind, Rung], reviewers: Rung, route: Route, anchor: Rung) -> str: +def shared_launches(rungs: dict[ReviewKind, Rung], reviewers: Rung, route: Route, project: Rung) -> str: """A sentence for each rung other than the worker's that a review runs on. "each reviewer" names every pass no replay lowered; those run on reviewers.""" together = {"each reviewer": reviewers} | {reviews: rungs[kind] for reviews, kind in REVIEWS if kind not in REVIEWERS} launched: dict[Rung, list[str]] = {} for reviews, rung in together.items(): if rung != route.rung: launched.setdefault(rung, []).append(reviews) - return "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items()) + return "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, project)}." for rung, reviews in launched.items()) def lowered(rungs: dict[ReviewKind, Rung], reviewers: Rung) -> list[tuple[str, Rung]]: @@ -73,42 +74,42 @@ def lowered(rungs: dict[ReviewKind, Rung], reviewers: Rung) -> list[tuple[str, R return [(reviews, rungs[kind]) for reviews, kind in REVIEWS if kind in REVIEWERS and rungs[kind] != reviewers] -def taken_in_launches(route: Route, anchor: Rung) -> str: +def taken_in_launches(route: Route, project: Rung) -> str: """The rung each higher E + I picks for the reviewers, so the worker reviews an item it takes in on that rung in the same run; the judge reports it as the cycle ends, so loop-claude routes on it only from the next cycle. Empty where no higher E + I picks a higher rung. For a worker on Opus 5.5 at medium, routed by an item of E + I 6, it reads: ` Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.` """ - now = review_rungs(anchor, route.rung, route.reviewed_on()) + now = review_rungs(project, route.rung, route.reviewed_on()) higher: dict[Rung, int] = {} for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1): # An E + I that lifts any pass puts every pass on reviewers_rung, since a replay lowers a pass only where the E + I steps no review up. - if review_rungs(anchor, route.rung, escape_and_impact) != now: - higher.setdefault(reviewers_rung(anchor, route.rung, escape_and_impact), escape_and_impact) + if review_rungs(project, route.rung, escape_and_impact) != now: + higher.setdefault(reviewers_rung(project, route.rung, escape_and_impact), escape_and_impact) if not higher: return "" picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in higher.items()] return f" Where an item you take into the chunk has an E + I of {min(higher.values())} or more, launch each reviewer with the Agent tool set to {listed(picks, 'and')}." -def rung_named(rung: Rung, route: Route, anchor: Rung) -> str: - """Why a review runs on rung: it is the project's, anchor, or the one the route's reviewed_on E + I picks, the item's or one taken in.""" - if rung == anchor: +def rung_named(rung: Rung, route: Route, project: Rung) -> str: + """Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in.""" + if rung == project: return "the project's rung" if route.escape_and_impact_taken_in: return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk" return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks" -def escalation(route: Route, anchor: Rung | None) -> str: +def escalation(route: Route, project: Rung | None) -> str: """The prompt's escalation sentences, the marker's among them, each led by a space. Empty off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes. Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs. For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: ` When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.` """ - if anchor is None or route.rung not in LADDER[:-1]: + if project is None or route.rung not in LADDER[:-1]: return "" marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} :`, n the trigger's number." - rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(anchor, route)] + rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)] if not rungs: return " " + " ".join(( f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.", @@ -122,14 +123,14 @@ def escalation(route: Route, anchor: Rung | None) -> str: )) -def reruns(route: Route, anchor: Rung | None) -> str: +def reruns(route: Route, project: Rung | None) -> str: """The prompt's sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. Empty off the ladder. For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: ` A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.` """ - if anchor is None or route.rung not in LADDER: + if project is None or route.rung not in LADDER: return "" - rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on()) + rungs, reviewers = review_rungs(project, route.rung, route.reviewed_on()), reviewers_rung(project, route.rung, route.reviewed_on()) lowered_reruns = "".join(f" Rerun {reviews} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for reviews, rung in lowered(rungs, reviewers)) return f"{shared_reruns(reviewers, rungs['seat'])}{lowered_reruns}" @@ -145,26 +146,26 @@ def shared_reruns(reviewers: Rung, seats: Rung) -> str: return f" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`." -def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str: +def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str: """Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it.""" - on = f" loop-claude runs you on {route.rung}." if anchor else "" + on = f" loop-claude runs you on {route.rung}." if project else "" ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " " - return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{on}{rungs_held(route, anchor)}" + return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{on}{rungs_held(route, project)}" -def rungs_held(route: Route, anchor: Rung | None) -> str: +def rungs_held(route: Route, project: Rung | None) -> str: """The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run.""" - return f"{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}" + return f"{review_launches(route, project)}{escalation(route, project)}{reruns(route, project)}" -def answered(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str: +def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str: """stepped is whether the answer's ruling stepped the worker up.""" - return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}" + return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}" -def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str: +def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str: """The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" - return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, anchor, stepped)}" + return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}" # Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds. @@ -180,9 +181,9 @@ def typed_answer(prompt: str) -> Typed | None: return Typed(rest, answer) -def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str: +def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str: """The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise.""" - return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, anchor)}" if stepped else "" + return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else "" def past_the_cap(question: str, answer: str, cap: int) -> str: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index dc24b1d7..7197926b 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -38,7 +38,7 @@ class Cycle: task: str route: Route # The project's rung; None for a model off the ladder. - anchor: Rung | None + project: Rung | None # Empty when the previous cycle's verdict was not Unfinished. unfinished_evidence: str # Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states. @@ -72,9 +72,9 @@ def escalated(cycle: Cycle, event: Event) -> Cycle: if isinstance(event, HumanTyped): return cycle cycle = dataclasses.replace(cycle, stepped_from=None) - if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor): + if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.project): return cycle - route = after_ruling(cycle.anchor, cycle.route, event.verdict) + route = after_ruling(cycle.project, cycle.route, event.verdict) return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None) @@ -120,17 +120,17 @@ def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> WorkerRan def worker_environment(cycle: Cycle) -> dict[str, str]: """The rungs the worker's claude is handed, which rule-hook holds its review launches to.""" - return worker_rungs.environment(cycle.anchor, cycle.route) + return worker_rungs.environment(cycle.project, cycle.route) def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> list[str]: if isinstance(answered, QuotedAnswer): - return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True) + return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, cycle.stepped_from is not None), resume=True) if isinstance(answered, TypedAnswer): - return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True) + return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, cycle.stepped_from is not None), resume=True) if session_open(cycle.session): - return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True) - return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False) + return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True) + return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False) def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None: diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 1614f0b0..8cef7e70 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -46,102 +46,30 @@ time. The layout, and when a copy is replaced, are in bin/transcript_archive/__i Every claude loop-claude starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker, -the session /talk opens and the judge on another rung; a project without an entry, as on its first -run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL -for the worker and the session /talk opens; with both set, nothing is asked. - -Routing: the worker's rung +the session /talk opens and the judge on another rung, a model at an effort. A project without an +entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the +judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing +is asked. Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the -session /talk opens run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is -routed on the item chunk-preflight names, read from todo.md on the default branch as the preflight -just fetched it (chunk_pick.chunk_item). That item is the earliest release's top item that does not -wait, but only where that release is the next one: the earliest after the newest vX.Y.Z tag that -todo.md has named at that tag or since, skipping a release its ## Renamed section marks renamed, or, -where no tag names a version, the earliest release. Otherwise no item routes the chunk. An item -waits while it is marked question, or while an item that blocks it is still in the table. The item's -L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in -bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I -unscored, the chunk runs on the model's cheapest rung. +session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some +models on another; a chunk no item routes runs on the project's model. The worker's prompts name the +rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when +the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher +rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, and the prompts' +wording in bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and +step-up in the archive ends with a Worker: line, the route's JSON record (Route.record in +bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A +todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed +without it. -Routing: the reviewers' rung - -The routed item's E + I picks the reviewers' rung, stepping up from the cheapest rung by -REVIEW_STEPS in bin/model_routing/ladder.py, never below the worker's rung. Where it steps none and -the worker runs no higher than the cheapest rung, a pass REPLAYED in that file names runs on the -rung it names, the lowest a review-replay run found finding what the cheapest rung finds, even below -the worker's. - -Routing: what the worker's prompts say - -The worker's first prompt names the rung and the item, and asks the worker to name each item the -chunk takes, with its L and E + I, and to count the item's size again once it has read the code -(prompts.recount). The prompt names the rung of each review that runs on a rung other than the -worker's: the reviewers' rung or the replay's for each pass's reviewer, and the cheapest rung for -each comprehension seat and the security pass. It also names the reviewers' rung each higher E + I -picks, so the worker reviews an item it takes in on that rung in the same run. When the worker runs -below the cheapest rung, the prompt has it launch each subagent that files or scores todo.md items -on the rung subagent-rung --plan prints. The prompt after each unfinished verdict says this again, -since a step-up may have moved the worker. A reviewer or seat that rules the work below standard may -ask to rerun one rung up; each prompt names that rung. loop-claude hands the worker's claude its own -rung, the project's and the reviews' E + I, in LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and -LOOP_CLAUDE_ESCAPE_AND_IMPACT, and rule-hook refuses a review launched below the rung those pick for -it. - -Routing: step-ups - -The judge reports the highest L and the highest E + I the worker states for an item it takes in. The -next cycle steps the worker up to the rung that L picks, never down, and the reviewers to the rung -picked by the higher of two: that E + I, or the routed item's (Route.reviewed_on in -bin/model_routing/route.py). A level off its scale counts as none. Every second unfinished verdict -on a chunk steps it up one rung (routing.after_unfinished). So does an unfinished verdict on a -worker that ended its run asking for a higher rung, once the judge quotes the transcript showing -that the escalation trigger it named fired (~/.claude/CLAUDE.md → "Working with the codebase" lists -them). An interrupt or a quoted answer with such a quote steps the rung as it comes in, before the -human is asked or the worker resumes (routing.after_ruling). Each such step marks how many -transcript entries the session held, and from then on the judge must quote the worker's own lines -after that mark, where it reads a [step] line. Each step on an escalation stops two rungs above the -rung the chunk's item picks, and the worker's prompts offer it only while the worker is below that -limit. - -Routing: the archive and reruns - -Each finished or unfinished verdict, interrupt, quoted answer, stop and step-up in the archive ends -with a Worker: line, the route's JSON record (Route.record in bin/model_routing/route.py). A rerun -resumes an open chunk on the latest route named there, and counts its unfinished verdicts afresh. -It also reads a Worker: line an older loop-claude wrote as a sentence, such as "claude-opus-5-5 at -high effort, routed by item 3's L of 4 and E + I of 5". A rung no longer on the ladder, or below the -one its item's L picks, is dropped, and the chunk is routed afresh from todo.md. So is a chunk whose -archived line names an R + C, as loop-claude wrote before it routed on L. A todo.md or an archive -that cannot be read or parsed is said on stderr, and the chunk is routed without it. - -Routing: the judge's rung - -The judge of a model listed in JUDGE_REPLAYED (bin/loop_claude/routing.py) runs on the rung that the -reviewers' E + I (Route.reviewed_on) picks for a review from that model. It never runs below the -model's cheapest rung, and runs on it when no item routed the chunk or was taken in. Its rung stays -put when the worker steps up. A model is listed once judge-replay found its cheapest rung returning -every verdict the reference judge reproduced. Any other model's judge runs at the effort its -settings give. - -Routing: the figures - -Counting the cycles a verdict closed across all projects in the archive, the first loop to close one -20 or more cycles after the last measurement measures every finished chunk there, with no model run: -tokens by project, subagent type, rung and the tool whose results they took in, 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 writes them to routing-figures.md at the -archive's root. They call for a routing change 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 the reports of 5 or more subagents of one type were longer than the tool results they -read. Each call not raised before is an interrupt: claude, on the project's model, on the terminal -in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls are listed in -routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the calls are said -on stderr, the loop goes on, and they are raised again at the next measurement. A line -`- Reset` in routing-calls-raised.md restarts both: the figures count only chunks that -finished after it, and a call raised before it may be raised again. A chunk that cannot be read is skipped and -named in the figures; figures that cannot be measured or written are said on stderr, and the loop -goes on. +Once 20 cycles have closed across all projects in the archive since the last measurement, the next +loop to close one measures every finished chunk there, with no model run, and writes +routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures +make for a routing change, unless raised before, is an interrupt: claude, on the project's model, +on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls +are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the +calls are said on stderr, the loop goes on, and they are raised again at the next measurement. 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. @@ -194,7 +122,7 @@ from chunk_pick import default_plan, DefaultPlan from git_repo import default_ref from loop_claude.effects import Effects from failure import Failure -from loop_claude.verdicts import Finished +from loop_claude.verdicts import Finished, Unfinished from loop_claude.project.model_choice import get_or_ask_models from todo_table import Item from transcript_archive.read import latest_worker @@ -247,37 +175,41 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc return models # After the reads above, so a loop that stops on one makes no worktree. facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects) - anchor = project_rung(models.worker) - route = routed(loop_run.route, anchor, models.worker, lambda: archived_route(archive_folder, session), item) + project = project_rung(models.worker) + route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session), item) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) - concluded = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, 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)) + concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, 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(concluded, Stop): return concluded - loop_run = after_verdict(loop_run, anchor, concluded) + loop_run = after_verdict(loop_run, project, concluded) if stop := archive_step(archive_folder, session, loop_run.task, concluded.route, loop_run.route, effects): return stop - if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects): + if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects): return stop -def routed(route: Route | None, anchor: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route: - """The route the cycle runs on. anchor is the project's rung, and model the project's model. +def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route: + """The route the cycle runs on. project is the project's rung, and model the project's model. - Where anchor is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, while that route's rung is at or above the one its item's L picks from anchor. Else the plan item routes the chunk afresh. + Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh. """ - if anchor is None: + if project is None: return Route(Rung(model)) route = route or archived() - return route if route and kept(route, anchor) else first_route(anchor, item()) + return route if route and kept(route, project) else first_route(project, item()) -def after_verdict(loop_run: LoopRun, anchor: Rung | None, concluded: Concluded) -> LoopRun: - """The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one takes the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; off the ladder, it keeps that route.""" +def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun: + """The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one takes the route stepped_route makes, and the evidence the judge gave for the verdict.""" verdict = concluded.verdict if isinstance(verdict, Finished): return dataclasses.replace(loop_run, route=None, unfinished_evidence="") - route = after_unfinished(anchor, concluded.route, verdict) if anchor else concluded.route - return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence) + return dataclasses.replace(loop_run, route=stepped_route(project, concluded.route, verdict), unfinished_evidence=verdict.evidence) + + +def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route: + """The route an unfinished chunk's next cycle starts on: the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised. Off the ladder there is no rung to step, and it keeps that route.""" + return after_unfinished(project, ended_on, verdict) if project else ended_on def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None: diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 34958d49..61dde258 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -1,4 +1,12 @@ -"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.""" +"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`. + +The worker, and the session /talk opens, run on a Route (model_routing/route.py). A model off the ladder gets a route without an item, and it is never stepped. + +- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item. +- Rerun. kept decides whether a rerun resumes the route its archive last names. +- Step-up. after_unfinished raises the route after an unfinished verdict, after_ruling after an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation. +- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model. +""" import dataclasses from chunk_pick import chunk_item, LastCut, Next @@ -27,64 +35,64 @@ def routed_item(todo: str, cut: LastCut) -> Item | Failure | None: return takes if takes and takes.likelihood and takes.escape_and_impact else None -def first_route(anchor: Rung, item: Item | None) -> Route: - """The route a chunk starts on: the rung its item's L picks from anchor, the project's rung.""" +def first_route(project: Rung, item: Item | None) -> Route: + """The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item.""" if item is None: - return Route(anchor) - return Route(worker_rung(anchor, item.likelihood), item.id, item.likelihood, item.escape_and_impact) + return Route(project) + return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact) -def kept(route: Route, anchor: Rung) -> bool: +def kept(route: Route, project: Rung) -> bool: """Whether a chunk keeps route: its rung is on the ladder and at or above item_rung.""" - return kept_rung(anchor, route) == route.rung + return kept_rung(project, route) == route.rung -def kept_rung(anchor: Rung, route: Route) -> Rung: +def kept_rung(project: Rung, route: Route) -> Rung: """The route's rung, raised to item_rung where it is lower or off the ladder.""" - return highest(route.rung, item_rung(anchor, route)) + return highest(route.rung, item_rung(project, route)) -def item_rung(anchor: Rung, route: Route) -> Rung: - """The rung the route's item's L picks from anchor, the project's rung, or anchor itself when no item routed it. The worker may run on a rung below anchor.""" - return worker_rung(anchor, route.likelihood) if route.item else anchor +def item_rung(project: Rung, route: Route) -> Rung: + """The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's.""" + return worker_rung(project, route.likelihood) if route.item else project -def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]: +def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]: """The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder.""" if route.rung not in LADDER: return () - return LADDER[position(route.rung) + 1:position(escalation_cap(anchor, route)) + 1] + return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1] -def escalation_cap(anchor: Rung, route: Route) -> Rung: +def escalation_cap(project: Rung, route: Route) -> Rung: """The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`. It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it. """ - return climbed(item_rung(anchor, route), ESCALATION_CAP) + return climbed(item_rung(project, route), ESCALATION_CAP) -def after_unfinished(anchor: Rung, route: Route, verdict: Unfinished) -> Route: +def after_unfinished(project: Rung, route: Route, verdict: Unfinished) -> Route: """The route the next cycle runs on after an unfinished verdict. Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the route's mark, Route.escalated_at, to where the judge stopped reading, so the trigger it quoted buys no second step; a step on the count of unfinished verdicts alone keeps the mark. Last, the route takes in the verdict's highest E + I, as Route.taking_in does. """ - rung = raised(anchor, route, verdict.highest_likelihood_taken_in) + rung = raised(project, route, verdict.highest_likelihood_taken_in) mark = escalation_mark(verdict) - if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(anchor, route, rung)): + if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)): after = one_rung_up(route, rung, route.escalated_at if mark is None else mark) else: after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1) return after.taking_in(verdict.highest_escape_and_impact_taken_in) -def after_ruling(anchor: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route: +def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route: """The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step.""" mark = escalation_mark(verdict) if mark is None: return route - rung = raised(anchor, route, verdict.highest_likelihood_taken_in) - return one_rung_up(route, rung, mark) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung) + rung = raised(project, route, verdict.highest_likelihood_taken_in) + return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung) def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route: @@ -92,14 +100,14 @@ def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route: return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at) -def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool: +def below_cap(project: Rung, route: Route, rung: Rung) -> bool: """Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung.""" - return position(rung) < position(escalation_cap(anchor, route)) + return position(rung) < position(escalation_cap(project, route)) -def raised(anchor: Rung, route: Route, likelihood_taken_in: int) -> Rung: - """kept_rung, raised to the rung that likelihood_taken_in picks from anchor. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none.""" - return highest(kept_rung(anchor, route), worker_rung(anchor, likelihood_taken_in)) if likelihood_taken_in else kept_rung(anchor, route) +def raised(project: Rung, route: Route, likelihood_taken_in: int) -> Rung: + """kept_rung, raised to the rung that likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none.""" + return highest(kept_rung(project, route), worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else kept_rung(project, route) def judge_rung(judge_model: str, route: Route) -> Rung: @@ -107,7 +115,7 @@ def judge_rung(judge_model: str, route: Route) -> Rung: A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give. """ - anchor = project_rung(judge_model) - if anchor is None or judge_model not in JUDGE_REPLAYED: + cheapest = project_rung(judge_model) + if cheapest is None or judge_model not in JUDGE_REPLAYED: return Rung(judge_model) - return review_floor(anchor, route.reviewed_on()) + return review_floor(cheapest, route.reviewed_on()) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 66c1b5e1..683787a0 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -17,7 +17,7 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from routing_figures import archive +from routing_figures import archive, measure from loop_claude.project import checkout, model_choice, records from chunk_pick import DefaultPlan, LastCut from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python @@ -210,7 +210,7 @@ class Cycles(unittest.TestCase): self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): - return run.Cycle(anchor=None, effects=fake.effects(), facts=facts, 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) + return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, 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")) @@ -232,7 +232,7 @@ class Cycles(unittest.TestCase): def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviews_e_plus_i_in_its_environment(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) + cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}]) @@ -242,7 +242,7 @@ class Cycles(unittest.TestCase): handle.write(json.dumps(human("the second")) + "\n") return 0 fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""]) - cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) + cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) with contextlib.redirect_stderr(io.StringIO()): self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) self.assertEqual(fake.terminal_environments, fake.worker_environments) @@ -364,7 +364,7 @@ class Cycles(unittest.TestCase): def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stdout(io.StringIO()): concluded = run.run_cycle(cycle) self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) @@ -381,7 +381,7 @@ class Cycles(unittest.TestCase): def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self): steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")] fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed")) kept = "".join(self.archived_outcomes()) @@ -389,7 +389,7 @@ class Cycles(unittest.TestCase): self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept) def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self): - cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4)) + cycle = dataclasses.replace(self.cycle(FakeEffects()), project=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4)) for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)): with self.subTest(ruling=ruling): self.assertEqual(run.escalated(cycle, states.Ruled(ruling)), cycle) @@ -400,7 +400,7 @@ class Cycles(unittest.TestCase): streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)] rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")] fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): concluded = run.run_cycle(cycle) self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4)) @@ -413,7 +413,7 @@ class Cycles(unittest.TestCase): streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)] rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)] fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stderr(io.StringIO()): concluded = run.run_cycle(cycle) self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))) @@ -437,7 +437,7 @@ class Cycles(unittest.TestCase): def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stderr(io.StringIO()): concluded = run.run_cycle(cycle) self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) @@ -1169,6 +1169,7 @@ class WorkerArgs(unittest.TestCase): self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)) self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus)) + self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 4, 5), opus)) self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus)) @@ -1482,6 +1483,7 @@ class HelpLimits(unittest.TestCase): self.assertIn("fails three times running, retried a minute apart", said) self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said) + self.assertIn(f"Once {measure.CYCLES_PER_CHECK} cycles have closed across all projects", said) class ExitContract(unittest.TestCase): diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index ff3092cb..2eb07e69 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -19,7 +19,7 @@ FIGURES = "routing-figures.md" LOCK = "routing-figures.lock" RAISED = "routing-calls-raised.md" RAISED_HEADING = "# Routing calls raised\n" -# Each line is a call and when it was raised, or a reset: `- ` or `- Reset`. +# Each line is a call and when it was raised, or a reset: `- ` or `- Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again. RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE) RESET = "Reset" diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index ab728351..8ad1e507 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -1,4 +1,4 @@ -"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`.""" +"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures.""" import collections import dataclasses import re diff --git a/docs/reading-cost.md b/docs/reading-cost.md index ad8d4e28..3a163b80 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -795,3 +795,7 @@ Read most (opens and searches): ## Reading cost, chunk 1034c157d8d2, finished 2026-10-22T19:29:13Z 100386 new input tokens before the first commit. + +## Reading cost, chunk a38d4733c268, finished 2026-10-22T20:33:05Z + +207415 new input tokens before the first commit. diff --git a/todo.md b/todo.md index 41ea46a8..0ca13661 100644 --- a/todo.md +++ b/todo.md @@ -6,16 +6,14 @@ `Bar = 0.1` -`Next ID = 219` +`Next ID = 220` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 211 | 0.4.0 | | | **State each routing rule once, in the docstring of the code that enforces it, and cut `loop-claude --help`'s routing paragraph to what the human running the loop needs.** | 2 | 2 | 1 | 3 | 4 | code health by 9, 1.4 by 9 | 32.9 | | 212 | 0.4.0 | | | **Split `review_launches` into a choice of each pass's rung, made in `bin/model_routing` beside `ladder.review_rungs`, and whole prompt sentences that render that choice.** | 2 | 2 | 3 | 5 | 4 | code health by 9 | 26.9 | | 214 | 0.4.0 | | | **Have rule-hook refuse a round commit past round 3 of its pass, unless an override quotes the human's answer, so a program holds the round cap.** | 2 | 1 | 3 | 4 | 3 | code health by 3, 1.1 by 3 | 16.6 | -| 172 | 0.4.0 | | | **Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.** | 2 | 1 | 3 | 4 | 3 | code health by 3, 1.4 by 3 | 16.5 | | 210 | 0.4.0 | | | **Hold the escalation mark in one module that states that one trigger buys one step, so a reader changes it without opening four files.** | 3 | 2 | 3 | 6 | 5 | code health by 9 | 16.2 | | 190 | 0.4.0 | | | **Rewrite the `docs/decisions.md` entries `todo.md: one table …`, `loop-claude: a judge decides …` and `loop-claude: before it opens claude …` as the current state, so a reader no longer replays superseded paragraphs to learn what holds.** | 2 | 2 | 1 | 3 | 3 | code health by 3, 1.4 by 2 | 15.5 | | 82 | 0.4.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | code health by 4, 1.4 by 4 | 14.6 | @@ -28,6 +26,7 @@ | 6 | 0.4.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 | | 1 | 0.5.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | | 218 | 0.5.0 | 170 | | **Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only the JSON record.** | 1 | 2 | 1 | 2 | 1 | code health by 2 | 14.4 | +| 219 | 0.5.0 | | | **Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.** | 1 | 1 | 3 | 3 | 2 | code health by 2 | 12.0 | | 123 | 0.5.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | code health by 5, 1.4 by 5 | 11.0 | | 139 | 0.5.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 | | 158 | 0.5.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 | @@ -76,10 +75,6 @@ ## Details -### 211. State each routing rule once, in the docstring of the code that enforces it, and cut `loop-claude --help`'s routing paragraph to what the human running the loop needs. - -Release 0.3.0's scoring runs (PR #324 at c713910) named `bin/loop_claude/loop/main.py:1` "loop-claude --help" at two seats in both runs: "a 160-line spec whose routing paragraph carries about 15 rules, re-describing what routing.py, ladder.py and retry.py enforce" (Maintainability senior), and "its routing paragraphs packing every rule into one block that routed and after_verdict need open" (Junior A). Mid A named `:259` `after_verdict`: "the 164-line docstring is the only full map of routing, and after_verdict chains it all in one expression". This lowers Locality: to change `routed` or `after_verdict`, a reader opens the help for rules the code enforces. Split `after_verdict`'s one expression into named steps. Make "loop-claude --help" and `after_verdict` easier to read. Item 184 rewraps two of the help's lines. - ### 212. Split `review_launches` into a choice of each pass's rung, made in `bin/model_routing` beside `ladder.review_rungs`, and whole prompt sentences that render that choice. Release 0.3.0's scoring runs named `bin/loop_claude/cycle/prompts.py:46` `review_launches` at three seats in both runs (first run: PR #324 at c713910; rerun: PR #324 rerun at c713910). Junior A, rerun: "with ladder.review_rungs, REPLAYED and escalation_rungs open at once". Mid A: "fragments that each start with a space, so no whole prompt is visible without running it in your head" (first run), and "routing policy and English wording interleaved" (rerun). Maintainability senior, rerun: "which conditional sentences reach which prompt means tracing fresh, routed_by, resumed, rungs_held and stepped_to". This lowers Locality, since choosing a rung needs the ladder's units open, and Shape, since one unit holds both policy and wording. Make `review_launches` easier to read. @@ -88,10 +83,6 @@ Release 0.3.0's scoring runs named `bin/loop_claude/cycle/prompts.py:46` `review Release 0.3.0's inherited architect named `bin/round_titles.py:4` `CAP` in the first run (PR #324 at c713910): "no program loops the reviewers; the cap lives in SKILL.md prose and the code only counts rounds and prints a note". The same seat named `bin/rule_hook/rules.py:55` `round-title-counts` in the rerun: "no program blocks a fourth review round; rule-hook checks only the counts inside a round's title". This lowers Self-sufficiency: a reader of `CAP` must know larv-review's "Round cap" to learn what holds it. The cap is `docs/decisions.md` → `review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human`. Make `CAP` and `round-title-counts` easier to read. -### 172. Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it. - -The architecture pass of PR #296 found one rung under two names: `bin/model_routing/ladder.py` calls it `project`, while `bin/loop_claude/routing.py`, `cycle/prompts.py`, `cycle/run.py`'s `Cycle.anchor` and `loop/main.py` call it `anchor`, and gloss it as "anchor, the project's rung" in docstring after docstring. A reader works out that the two are one rung each time. Make `bin/loop_claude/routing.py`'s `first_route` easier to read. - ### 210. Hold the escalation mark in one module that states that one trigger buys one step, so a reader changes it without opening four files. Release 0.3.0's scoring runs found the mark spread out (first run: PR #324 at c713910; rerun: PR #324 rerun at c713910). `bin/model_routing/route.py:66` `Route.escalated_at`: "the escalation mark lives in six units across four files" (Junior A, first run), "one concept spread over five files" (Mid A, rerun). `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: "no single place states that one trigger buys one step" (Maintainability senior, rerun). `bin/loop_claude/cycle/run.py:45` `Cycle.stepped_from` and `:69` `escalated`: "state outside the state machine, cleared on every event but HumanTyped" (Mid A, rerun). `bin/loop_claude/cycle/judge.py:216` `quotes_checked` checks the escalation against `Grounds.since_step` beside the quoted answer: "three quote checks follow different rules" (Junior A, rerun). This lowers Locality: changing the mark means opening `route.py`, `judge.py`, `run.py` and `routing.py` together. Move the mark's stamping, `STEP_LINE`, the since-step grounds and their check, and the step's state into one module, and make `stepped_from` part of the cycle's state machine. Make `Route.escalated_at`, `escalation_mark`, `Cycle.stepped_from`, `escalated` and `quotes_checked` easier to read. The archive's `Worker:` record holds the mark as `escalated_at`, so a rerun keeps it; the move keeps that field. `escalation_mark` now lives in `bin/loop_claude/verdicts.py`. @@ -144,6 +135,10 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go PR #357 archived the route as a JSON record, and kept `LEGACY_WORKER` to read the `Worker:` lines an older loop-claude wrote as sentences. The routing figures still count chunks whose archive holds such lines: 51 when PR #357 shipped, every chunk finished after the reset of 2026-10-21T22:16:41Z. Item 170 changes the routing steps, after which `AGENTS.md` has a `Reset` appended to `routing-calls-raised.md`, and the figures then count only chunks that hold records. So this item waits for item 170. Before starting, check that `routing-calls-raised.md` holds a `Reset` stamped after PR #357's merge; where none does, block this item on the next item that changes the ladder or its steps instead. Delete `LEGACY_WORKER`, `legacy_fields`, the tests that read sentences (in `bin/loop_claude/test_loop_claude.py` and `bin/routing_figures/test_routing_figures.py`), and the sentence on them in "loop-claude --help". Reword `route_from`'s docstring, and the comment at `Rung.__str__` in `bin/model_routing/ladder.py`, which gives the old lines as a reason `parse` must keep reading that spelling. +### 219. Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it. + +Item 172 renamed `anchor` to `project` across `bin/loop_claude`, after release 0.3.0's inherited architect named `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: "the project's rung is also called anchor". Three tools outside it still call the same rung `anchor`: `bin/judge_replay/main.py:54` (`anchor = arguments_or_exit(...)`, a `Rung` parsed from the model argument), `bin/subagent_rung/main.py:26` (`anchor = project_rung(model)`), and `bin/review_replay/main.py:74`, `:100` and `:180`, with `findings_found`'s docstring. While the name differs between tools, a reader works out each time that the two are one rung. The rename keeps behaviour. `bin/score_outcomes/anchors.py` uses `anchor` for score anchors, a different thing, and keeps the name. + ### 123. Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat. Three seats of PR #257's scoring run named `bin/comprehension_history.py:106` `latest_places`; the logic it rests on is `:114` `worse_places` and `:126` `worse_votes`. They regex the markdown the module writes. `worse_votes` keeps a seat's first row through `setdefault`, because the votes table comes first. `worse_places` recovers the seat with `label.split(",")[0]`. `Entry` still holds scoring seats' places for rulings recorded before PR #255. Release 0.3.0's seats named near-synonyms left from before PR #255: `:150` `scoring_runs`, "near-synonyms scored and scoring_runs differ only on a ruling from before PR #255" (Maintainability senior), `:130` `newest_scored`, "four near-identical names over two concepts", and `:159` `scored`. Make these functions easier to read.