diff --git a/CLAUDE.md b/CLAUDE.md index 0d9347a6..f8f551e0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K - **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. - **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records. - **gate** — the merge gate: the checks a PR passes before it merges. -- **interrupt** — `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`, both on loop-claude's terminal. +- **interrupt** — `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it; a release ready to cut opens that session at once, and a routing call opens claude in the setup's development clone, `~/code/claude-config`, both on loop-claude's terminal. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. - **judge's records** — the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`. - **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling. diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 9c9e89d4..939fc441 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -52,7 +52,8 @@ def deploy(checkout: str) -> str | Failure: if tag is None: return Failure("origin has no v* tag to move to") # Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged. - git("update-index", "-q", "--refresh", cwd=checkout) + if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure): + return refreshed changed = git("diff", "--name-only", "HEAD", cwd=checkout) if isinstance(changed, Failure): return changed diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index 4797399e..233b9aba 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -40,7 +40,6 @@ from model_routing.ladder import lowest_worker_rung, project_rung, Rung from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records from claude_code.transcript import read_transcript -from loop_claude.stop import Stop from loop_claude.verdicts import Verdict TOOL = "judge-replay" @@ -93,10 +92,10 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> Kind | Limited: premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript)) - if isinstance(premises, Stop): - return verdict_kind(Failure(premises.reason)) - if isinstance(records, Stop): - return verdict_kind(Failure(records.reason)) + if isinstance(premises, Failure): + return verdict_kind(premises) + if isinstance(records, Failure): + return verdict_kind(records) if isinstance(entries, Failure): return verdict_kind(entries) # 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count. diff --git a/bin/loop_claude/__init__.py b/bin/loop_claude/__init__.py index e69de29b..758986a2 100644 --- a/bin/loop_claude/__init__.py +++ b/bin/loop_claude/__init__.py @@ -0,0 +1,4 @@ +"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/main.py's help). + +Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, project/ reads a checkout's files, and waiting/ shows a question to loop-inbox. The modules at this level are those more than one of them imports, and loop-inbox imports several. A reader finds each by its name, so they stay at one level: docs/decisions.md → `principles: about seven things per level, …`. +""" diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 8798892d..9d832919 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,4 +1,5 @@ import dataclasses +import pathlib import sys import typing import uuid @@ -12,7 +13,6 @@ from claude_code.transcript import human_turns, read_transcript from loop_claude.waiting.listing import listed, shown from loop_claude.waiting.talk import make_way, TALK from loop_claude.stop import needs_human, needs_terminal, Stop -from loop_claude.paths import Paths from model_routing.ladder import Rung ANSWER_QUESTION = "answer the question above" @@ -39,7 +39,7 @@ class Talked: """The human typed in the worker's claude session.""" -def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talked | Stop: +def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop: """Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" say(f"\n{question}", effects) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): @@ -47,18 +47,18 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: P # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) - with listed(paths.waiting, ask, effects): - answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal() + with listed(questions, ask, effects): + answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal() if isinstance(answer, OpenOnTerminal | OpenInInbox): - return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, paths, effects)) or Talked() + return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, questions, effects)) or Talked() return answer -def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop: +def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop: """The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends.""" try: # Annotated since mypy infers input_or's T as object from the lambda. - answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask)) + answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, ask)) except EOFError: print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(ANSWER_QUESTION, "the input ended") @@ -77,17 +77,17 @@ def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | OpenOnTermin return OpenOnTerminal() if text == TALK else text -def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: +def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> Stop | None: """Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened.""" match where: case OpenOnTerminal(): - shown(paths.waiting, dataclasses.replace(ask, state=where), effects) + shown(questions, dataclasses.replace(ask, state=where), effects) if unstarted := hand_over(session.claude_command(), effects): return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}") case OpenInInbox(pid): - make_way(paths.waiting, ask, pid, effects) + make_way(questions, ask, pid, effects) say("claude is open for this question in loop-inbox; waiting for it to end", effects) - while not claude_ended(paths.waiting, ask) and effects.alive(pid): + while not claude_ended(questions, ask) and effects.alive(pid): effects.sleep(POLL_SECONDS) case _: typing.assert_never(where) diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index b736f1d7..a2e1566f 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -97,12 +97,12 @@ class Rejected(Failure): class Grounds(typing.NamedTuple): - """What run_judge checks the judge's quotes against, word for word, since stitched fragments can say what their source does not.""" - # The transcript as the judge saw it. The evidence must quote it, its fragments in order: a misquote is Rejected, which judge retries. + """The texts quotes_checked holds the judge's quotes to, word for word, since stitched fragments can say what their source does not.""" + # The transcript as the judge saw it. shown: str - # escalation_mark.since_step's lines. An escalation must quote both these and shown: a misquote drops the escalation, as escalation_mark.checked says. + # The worker's own lines after the escalation mark, as escalation_mark.since_step renders them. since_step: str - # README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human. + # README.md's premises and the records. quotable: str @@ -179,9 +179,10 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects cost = cost_of(reply) if isinstance(verdict, Failure): return Rejected(verdict.reason, replied, cost) - if not grounded(verdict.evidence, grounds.shown): - return Rejected(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""), replied, cost) - return dataclasses.replace(quotes_checked(verdict, grounds), judge_cost=cost) + checked = quotes_checked(verdict, grounds) + if isinstance(checked, Failure): + return Rejected(checked.reason, replied, cost) + return dataclasses.replace(checked, judge_cost=cost) def cost_of(reply: dict) -> float: @@ -190,8 +191,19 @@ def cost_of(reply: dict) -> float: return float(cost) if isinstance(cost, int | float) and not isinstance(cost, bool) and cost > 0 else 0.0 -def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict: - """The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop.""" +def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure: + """The verdict with each quote it makes held to the text that must hold it, word for word: + + | Quote | Must be in | Where it isn't | + |---|---|---| + | the evidence | grounds.shown, the evidence's fragments in order | a Failure: run_judge rejects the reply, and judge retries it | + | a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried | + | the escalation | grounds.shown and grounds.since_step | the escalation is dropped, so the worker's rung holds, as escalation_mark.checked says | + + Only a misquoted evidence fails: the other two misquotes would otherwise exit an unattended loop. + """ + if not grounded(verdict.evidence, grounds.shown): + return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else "")) if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable): verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, taken_in=verdict.taken_in) return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown) diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 5e400f83..73357cf4 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -57,28 +57,37 @@ def preflight_failed(reason: str) -> str: def review_launches(route: Route, project: Rung | None) -> list[str]: - """The sentences naming where to launch reviews, in this order; none off the ladder: - - one for each rung, other than the worker's, that a reviewer, a seat or the security pass runs on; - - where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent; - - where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items; - - the reviewers' rung each higher E + I picks; - - where the reviewers run above the project's rung, that a branch changing only Markdown no agent follows reviews on it, as rule-hook's reviewer-rung allows. - - For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` - """ + """The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder.""" if project is None: return [] choice = chosen(project, route) - scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.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 {project.model} ` prints."] if position(route.rung) < position(project) else [] + return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice, project)] + + +def scan_launch(choice: ReviewChoice, route: Route) -> list[str]: + """Where the security pass runs on another rung than the worker's, the sentence that a full scan runs only from the security pass's subagent, which shared_launches names just before: `Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.`""" + return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else [] + + +def planning_launch(route: Route, project: Rung) -> list[str]: + """Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `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 claude-opus-5-5 ` prints.`""" + return [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 [] + + +def markdown_launch(choice: ReviewChoice, project: Rung) -> list[str]: + """Where the reviewers run above the project's rung, the sentence that a branch changing only Markdown no agent follows reviews on the project's rung, as rule-hook's reviewer-rung allows. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`""" + if position(choice.reviewers) <= position(project): + return [] files = ", ".join(f"`{name}`" for name in INSTRUCTION_FILES) folders = listed([f"`{folder}/`" for folder in INSTRUCTION_FOLDERS], "or") - markdown = [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {project.agent_args()}."] if position(choice.reviewers) > position(project) else [] - return [*shared_launches(choice, route, project), *scan, *planning, *taken_in_launches(choice), *markdown] + return [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {project.agent_args()}."] def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]: - """A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.""" + """A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on. + + For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` + """ together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security} launched: dict[Rung, list[str]] = {} for reviews, rung in together.items(): diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index b252be4b..cead4a1a 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -2,7 +2,7 @@ import dataclasses import pathlib import typing -from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, TypedAnswer, WorkerRan, Working +from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, to_the_human, transition, TypedAnswer, WorkerRan, Working from transcript_archive.write import archive from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args from claude_code.session import delete_session, Session, session_open, transcript_file @@ -13,7 +13,6 @@ from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession from loop_claude.cycle.judge import judge, Rejected from loop_claude.routing import judge_rung, next_route, step_up, StepUp from transcript_archive import outcomes -from loop_claude.paths import Paths from loop_claude.cycle import prompts from claude_code.transcript import read_transcript from loop_claude.cycle.retry import retried @@ -25,24 +24,26 @@ from model_routing import worker_rungs @dataclasses.dataclass(frozen=True) class Cycle: + """What a cycle runs on, which no step changes but the route. Each step reads the few fields it needs by name, so they stay at one level: docs/decisions.md → `principles: about seven things per level, …`, more where a reader finds them by name.""" effects: Effects # What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began. facts: str judge_model: str - paths: Paths premises: str - project_archive: pathlib.Path - records: str - root: str - session: Session - task: str - route: Route # The project's rung; None for a model off the ladder. project: Rung | None - # Empty when the previous cycle's verdict was not Unfinished. - unfinished_evidence: str + project_archive: pathlib.Path + # Where the loop keeps its questions for loop-inbox: running_loops.Listed.folder. + questions: pathlib.Path + records: str + root: str + route: Route + session: Session # Lists in loop-inbox the items the chunk takes, given the IDs an unfinished ruling found taken in. show_taken_in: typing.Callable[[tuple[int, ...]], None] + task: str + # Empty when the previous cycle's verdict was not Unfinished. + unfinished_evidence: str @dataclasses.dataclass(frozen=True) @@ -59,9 +60,9 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded: event = step(cycle, state) if isinstance(event, Stop): return stopped(cycle, event, event.reason) - # Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states. - if isinstance(event, Ruled) and event.step_up: - cycle = dataclasses.replace(cycle, route=event.step_up.after) + # Only a ruling's step-up changes the route within a cycle, here, once rule has archived the ruling on the route before it. No transition reads the current route, so Cycle holds it, not the states. + if isinstance(event, Ruled) and event.stepped_to: + cycle = dataclasses.replace(cycle, route=event.stepped_to) if isinstance(event, Ruled) and not isinstance(event.verdict, Finished): cycle.show_taken_in(event.verdict.taken_in.items) state = transition(state, event) @@ -93,25 +94,23 @@ def judge_of(cycle: Cycle) -> Rung: def step(cycle: Cycle, state: Active) -> Event | Stop: match state: - case Working(answered, _, step_up): - return work(cycle, answered, step_up) - case Judging(transcript_path, _): - return rule(cycle, transcript_path) - case Interrupting(transcript_path, ruling, _, step_up): - return ask(cycle, transcript_path, ruling, step_up) + case Working(answered, _, stepped): + return work(cycle, answered, stepped) + case Judging(transcript_path, quoted_answers): + return rule(cycle, transcript_path, quoted_answers) + case Interrupting(transcript_path, ruling, _, _): + return ask(cycle, transcript_path, ruling) case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: typing.assert_never(state) -def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop: +def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> WorkerRan | Stop: if isinstance(answered, QuotedAnswer): say(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True) - if stop := keep_answer(cycle, answered, step_up): - return stop # worker_start runs inside the lambda: a failed attempt may have opened the session. - if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, step_up), worker_environment(cycle), cycle.effects), cycle.effects): + if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") @@ -126,33 +125,37 @@ def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession: return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle)) -def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]: +def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]: if isinstance(answered, QuotedAnswer): - return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True) + return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True) if isinstance(answered, TypedAnswer): - return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True) + return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True) if session_open(cycle.session): 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, step_up: StepUp | None) -> Stop | None: - path = transcript_file(cycle.session) - if not path: - return None - # As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then. - quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), ran_on(cycle, step_up).worker_line(), answered.judge_cost) - if failure := archive_stepped(cycle, path, quoted, step_up): - return Stop(1, failure.reason) - return None - - -def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: +def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop: + """The judge's ruling. An interrupt or a quoted answer is archived as it is ruled, on the route the worker ran on until then, and then any step-up it makes, so the figures charge each stretch of work to its own rung.""" entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected)) - return verdict if isinstance(verdict, Stop) else Ruled(verdict, ruling_step_up(cycle, verdict)) + if isinstance(verdict, Stop): + return verdict + if not isinstance(verdict, Interrupt | QuotedAnswer): + return Ruled(verdict) + stepped = ruling_step_up(cycle, verdict) + if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers), stepped): + return Stop(1, failure.reason) + return Ruled(verdict, stepped.after if stepped else None) + + +def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> str: + """The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from README.md or the records.""" + if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers): + return outcomes.answered(ruling.question, prompts.QUOTE_SOURCES, ruling.answer, ruling.evidence, ruling.escalation, str(judge_of(cycle)), cycle.route.worker_line(), ruling.judge_cost) + return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judge_cost) def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None: @@ -162,15 +165,10 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St return None -def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | HumanTalked | Stop: - question = question_for(ruling) - # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. - # The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung. - interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, ran_on(cycle, step_up).worker_line(), ruling.judge_cost) - if failure := archive_stepped(cycle, transcript_path, interrupted, step_up): - return Stop(1, failure.reason) +def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop: + """The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript.""" # Only the human may cut a release, so a release ready to cut opens claude's session at once. - answer = interrupt(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.paths, cycle.effects) + answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.questions, cycle.effects) match answer: case Stop(): return answer @@ -180,11 +178,6 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st return HumanTyped(TypedAnswer(ruling.question, answer)) -def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route: - """The route the worker ran on until the ruling: the one before its step-up, if it made one.""" - return step_up.before if step_up else cycle.route - - def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None: """Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned.""" if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)): diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index b1114561..44d1cbed 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -1,7 +1,7 @@ import dataclasses from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict -from loop_claude.routing import StepUp +from model_routing.route import Route # A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records. QUOTED_ANSWERS_PER_CYCLE = 3 @@ -19,8 +19,8 @@ class Working: """The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one.""" answered: QuotedAnswer | TypedAnswer | None = None quoted_answers: int = 0 - # The step-up made by the ruling that brought the answer, so the worker is told of it; None for none. - step_up: StepUp | None = None + # Whether the ruling that brought the answer stepped the worker up a rung, so the worker is told of it. + stepped: bool = False @dataclasses.dataclass(frozen=True) @@ -36,8 +36,8 @@ class Interrupting: transcript_path: str ruling: Interrupt | QuotedAnswer quoted_answers: int = 0 - # The step-up the ruling made. It holds through the answer the human types, and drops on /talk. - step_up: StepUp | None = None + # Whether the ruling stepped the worker up a rung. It holds through the answer the human types, and drops on /talk. + stepped: bool = False @dataclasses.dataclass(frozen=True) @@ -63,8 +63,8 @@ class WorkerRan: @dataclasses.dataclass(frozen=True) class Ruled: verdict: Verdict - # None unless an interrupt's or a quoted answer's escalation stepped the route; always None for a finished or unfinished verdict. - step_up: StepUp | None = None + # The route an interrupt's or a quoted answer's escalation stepped the worker up to, which the cycle runs on from here; None where the route holds, and always for a finished or unfinished verdict. + stepped_to: Route | None = None @dataclasses.dataclass(frozen=True) @@ -85,20 +85,23 @@ class Archived: Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived +def to_the_human(ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> bool: + """Whether a ruling goes to the human: an interrupt always, a quoted answer once the cycle has used up its QUOTED_ANSWERS_PER_CYCLE.""" + return isinstance(ruling, Interrupt) or quoted_answers >= QUOTED_ANSWERS_PER_CYCLE + + def transition(state: State, event: Event) -> State: match state, event: case Working(_, quoted_answers), WorkerRan(transcript_path): return Judging(transcript_path, quoted_answers) - case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, step_up) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE: - return Working(answered, quoted_answers + 1, step_up) - case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling, step_up) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE: - return Interrupting(transcript_path, ruling, quoted_answers, step_up) - case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling, step_up): - return Interrupting(transcript_path, ruling, quoted_answers, step_up) + case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling, stepped_to) if to_the_human(ruling, quoted_answers): + return Interrupting(transcript_path, ruling, quoted_answers, stepped_to is not None) + case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, stepped_to): + return Working(answered, quoted_answers + 1, stepped_to is not None) case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict): return Closing(transcript_path, verdict) - case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed): - return Working(typed, quoted_answers, step_up) + case Interrupting(_, _, quoted_answers, stepped), HumanTyped(typed): + return Working(typed, quoted_answers, stepped) # The human worked in the worker's claude session, so the judge rules again on the transcript it leaves. case Interrupting(transcript_path, _, quoted_answers), HumanTalked(): return Judging(transcript_path, quoted_answers) diff --git a/bin/loop_claude/loop/close.py b/bin/loop_claude/loop/close.py index a88d3d9e..66b1fe33 100644 --- a/bin/loop_claude/loop/close.py +++ b/bin/loop_claude/loop/close.py @@ -18,13 +18,16 @@ UNFINISHED_LIMIT = 6 def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop: """The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" after = after_verdict(loop_run, project, concluded) + # A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts. + if after.route is None: + return after # The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on. path = transcript_file(session) - if path and after.route and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), effects)): + if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), effects)): return Stop(1, failure.reason) if limit := reached_limit(after): - # An unfinished verdict always leaves a route; the `or` only satisfies LoopRun.route's optional type. The stop is archived with that route, the one the next cycle would run on, so a rerun resumes there. - return archived_stop(archive_folder, session, after.task, after.route or concluded.route, limit, limit.reason, effects) + # Archived with the route the next cycle would run on, so a rerun resumes there. + return archived_stop(archive_folder, session, after.task, after.route, limit, limit.reason, effects) return after diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 041e44c7..2abb0a16 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -133,14 +133,15 @@ from loop_claude.loop.close import closed_cycle 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, say +from failure import Failure from loop_claude.project.model_choice import get_or_ask_models +from loop_claude.running_loops import Listed, shown_running from loop_claude.paths import Paths from project_key import project_key -from model_routing.ladder import project_rung, Rung +from model_routing.ladder import project_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 loop_claude.running_loops import shown_running +from claude_code.session import Session, session_named from loop_claude.stop import Stop @@ -160,44 +161,50 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(loop_run, Stop): return loop_run baseline = fingerprint(launcher) - key = project_key(loop_run.root, paths.home) - archive_folder = project_archive(loop_run.root, paths.home, env) # "A " is the human's cue in the session picker that the session is the loop's. - session = session_named(f"A {key} loop-claude", paths.claude_code_transcripts) + session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts) with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed: - # From here on, paths.waiting is where this loop keeps its questions: the configured folder where the loop holds its session's lock, and else an unlisted folder of its own (running_loops.Listed.folder), so every later question goes there. - paths = dataclasses.replace(paths, waiting=listed.folder) while True: if stop := exec_if_edited(launcher, baseline, loop_run, effects): return stop loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) - premises = read_premises(loop_run.root) - if isinstance(premises, Stop): - return premises - records = read_records(loop_run.root, paths.claude_dir) - if isinstance(records, Stop): - return records - models = get_or_ask_models(key, paths, env, effects) - if isinstance(models, Stop): - 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) - project = project_rung(models.worker) - route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item) - say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True) - show_taken_in = shown_items(listed.show, loop_run.root, route.item) - show_taken_in(loop_run.items_taken_in) - 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, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) + cycle = next_cycle(loop_run, session, listed, paths, env, launcher, effects) + if isinstance(cycle, Stop): + return cycle + concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded - closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects) + closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, session, effects) if isinstance(closed, Stop): return closed loop_run = closed - if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), project or Rung(models.worker), paths, effects): + # Off the ladder the worker runs on the project's model itself, which its route names. + if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), cycle.project or cycle.route.rung, paths, listed.folder, effects): return stop +def next_cycle(loop_run: LoopRun, session: Session, listed: Listed, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> Cycle | Stop: + """The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read.""" + premises = read_premises(loop_run.root) + if isinstance(premises, Failure): + return Stop(1, premises.reason) + records = read_records(loop_run.root, paths.claude_dir) + if isinstance(records, Failure): + return Stop(1, records.reason) + models = get_or_ask_models(project_key(loop_run.root, paths.home), paths, env, effects) + if isinstance(models, Stop): + return models + archive_folder = project_archive(loop_run.root, paths.home, env) + # 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) + project = project_rung(models.worker) + route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item) + say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True) + show_taken_in = shown_items(listed.show, loop_run.root, route.item) + show_taken_in(loop_run.items_taken_in) + return Cycle(effects=effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=listed.folder, records=records, root=loop_run.root, route=route, session=session, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence) + + def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop: if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 75c07afa..363d77ad 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -14,14 +14,14 @@ from loop_claude.stop import Stop from utc_stamp import utc -def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None: +def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None: """Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, session is its worker's session id, which loop-inbox lists the calls under, and rung is the rung of the claude that puts the calls to the human.""" with archive.locked(root) as held: new = new_calls(root, paths, effects) if held else [] if isinstance(new, Failure): say(f"routing figures: {new.reason}", effects) return None - return raise_calls(root, checkout, session, new, rung, paths, effects) if new else None + return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure: @@ -44,18 +44,18 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | return [call for call in found if call not in kept.calls] -def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None: - """Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" +def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None: + """Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" bullets = "".join(f"- {call}\n" for call in new) question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}" say(f"\n{question}", effects) if not effects.on_terminal(): say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None - prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." + prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal()) - with listed(paths.waiting, ask, effects): - unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), effects) + with listed(questions, ask, effects): + unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.config_clone), {}), effects) if unstarted: return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}") # Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice. diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index 39ffc562..6b4b40e8 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -6,6 +6,8 @@ import pathlib class Paths: claude_code_transcripts: pathlib.Path claude_dir: pathlib.Path + # The development clone of this setup, where a change to it is made: claude_dir holds only a release, docs/decisions.md → `deploy:`. + config_clone: pathlib.Path home: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path @@ -18,6 +20,7 @@ def paths_from(home: pathlib.Path) -> Paths: return Paths( claude_code_transcripts=claude / "projects", claude_dir=claude, + config_clone=home / "code" / "claude-config", home=home, model_catalog=claude / "cache" / "model-catalog", models_file=claude / "loop-claude-models.json", diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 1a1a1122..638ba198 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,19 +1,20 @@ +from failure import Failure from loop_claude.project.text_file import read_utf8 from markdown_text import sections -from loop_claude.stop import Stop -def read_premises(root: str) -> str | Stop: +def read_premises(root: str) -> str | Failure: + """README.md's ## Goals and ## Audience in root; a Failure where README.md cannot be read or lacks either, or holds one twice or empty.""" text = read_utf8(root, "README.md", "no premises") - if isinstance(text, Stop): + if isinstance(text, Failure): return text found = sections(text) for name in ("Goals", "Audience"): bodies = found.get(name, []) if not bodies: - return Stop(1, f"README.md has no ## {name} heading - no premises.") + return Failure(f"README.md has no ## {name} heading - no premises.") if len(bodies) > 1: - return Stop(1, f"README.md has ## {name} more than once - no premises.") + return Failure(f"README.md has ## {name} more than once - no premises.") if not bodies[0]: - return Stop(1, f"README.md has nothing under ## {name} - no premises.") + return Failure(f"README.md has nothing under ## {name} - no premises.") return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" diff --git a/bin/loop_claude/project/records.py b/bin/loop_claude/project/records.py index 11314d32..ab90b831 100644 --- a/bin/loop_claude/project/records.py +++ b/bin/loop_claude/project/records.py @@ -1,7 +1,7 @@ import pathlib +from failure import Failure from loop_claude.project.text_file import read_utf8 -from loop_claude.stop import Stop # The records the judge reads beside the README's premises: these project files, then the human's rules below. RECORD_FILES = ("AGENTS.md", "docs/decisions.md") @@ -11,7 +11,7 @@ HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards") HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS)) -def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop: +def read_records(root: str, claude_dir: pathlib.Path) -> str | Failure: """The project's record files, then the human's rules for every project, CLAUDE.md first, each headed by its name; a file that does not exist is left out.""" rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))] sources = [(root, name, name) for name in RECORD_FILES] @@ -21,7 +21,7 @@ def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop: if not pathlib.Path(folder, name).exists(): continue text = read_utf8(folder, name, "the judge cannot read the records") - if isinstance(text, Stop): + if isinstance(text, Failure): return text records.append(f"From {heading}:\n{text.strip()}") return "\n\n".join(records) diff --git a/bin/loop_claude/project/text_file.py b/bin/loop_claude/project/text_file.py index 83d7bc41..0ee0efdd 100644 --- a/bin/loop_claude/project/text_file.py +++ b/bin/loop_claude/project/text_file.py @@ -1,13 +1,14 @@ import pathlib -from loop_claude.stop import Stop +from failure import Failure -def read_utf8(folder: str, name: str, consequence: str) -> str | Stop: +def read_utf8(folder: str, name: str, consequence: str) -> str | Failure: + """The text of the file name in folder; a Failure naming consequence where it cannot be read or is not UTF-8.""" try: return pathlib.Path(folder, name).read_text(encoding="utf-8") except OSError as failure: - return Stop(1, f"{name} in {folder}: {failure.strerror} - {consequence}.") + return Failure(f"{name} in {folder}: {failure.strerror} - {consequence}.") except UnicodeDecodeError as failure: line = failure.object.count(b"\n", 0, failure.start) + 1 - return Stop(1, f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.") + return Failure(f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index b01cc34c..a1d0e819 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -228,15 +228,15 @@ class Transitions(unittest.TestCase): states.transition(state, event) def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self): - step_up = routing.StepUp(Route(Rung("claude-opus-5-5", "medium")), Route(Rung("claude-opus-5-5", "high"), escalated_at=3)) + stepped_to = Route(Rung("claude-opus-5-5", "high"), escalated_at=3) interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴") for state, event, after in ( - (states.Judging("/t"), states.Ruled(quoted, step_up), states.Working(quoted, 1, step_up)), - (states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)), - (states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)), - (states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)), - (states.Interrupting("/t", interrupt, 0, step_up), states.HumanTalked(), states.Judging("/t")), - (states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")), + (states.Judging("/t"), states.Ruled(quoted, stepped_to), states.Working(quoted, 1, True)), + (states.Judging("/t", 3), states.Ruled(quoted, stepped_to), states.Interrupting("/t", quoted, 3, True)), + (states.Judging("/t"), states.Ruled(interrupt, stepped_to), states.Interrupting("/t", interrupt, 0, True)), + (states.Interrupting("/t", interrupt, 0, True), states.HumanTyped(TYPED), states.Working(TYPED, 0, True)), + (states.Interrupting("/t", interrupt, 0, True), states.HumanTalked(), states.Judging("/t")), + (states.Working(TYPED, 0, True), states.WorkerRan("/t"), states.Judging("/t")), ): with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) @@ -258,7 +258,7 @@ class Cycles(unittest.TestCase): self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): - return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", 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, show_taken_in=lambda items: None, task="Do it.", unfinished_evidence=unfinished_evidence) + return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", unfinished_evidence=unfinished_evidence) def archived_outcomes(self): return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md")) @@ -696,7 +696,7 @@ class Interrupts(unittest.TestCase): def put(self, fake, answer_here=True, effects=None, question="Which one?"): """interrupt's answer and what it said, run while the session's lock is held, as a running loop holds it.""" with contextlib.redirect_stderr(io.StringIO()) as said, session_lock.held(self.paths.waiting, str(self.session.id)): - answer = interrupt.interrupt(question, answer_here, self.session, self.paths, effects or fake.effects()) + answer = interrupt.interrupt(question, answer_here, self.session, self.paths.waiting, effects or fake.effects()) return answer, said.getvalue() def asked(self): @@ -859,7 +859,7 @@ class RoutingCheck(unittest.TestCase): """What check_routing returns and says for a loop in /code/log.""" with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: self.enterContext(session_lock.held(self.paths.waiting, "s1")) - stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, fake.effects()) + stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, self.paths.waiting, fake.effects()) return stop, said.getvalue() def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self): @@ -898,7 +898,8 @@ class RoutingCheck(unittest.TestCase): self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"]) self.assertIn(f"change nothing until they answer:\n- {call}", args[6]) self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}]) - self.assertEqual(fake.terminal_folders, [str(self.home / ".claude")]) + self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release") + self.assertIn("Record what they decide in this checkout, the development clone", args[6]) (self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across") self.assertEqual(self.check(FakeEffects(git=[UNREAD]))[0], None) self.assertNotIn(call, self.check(FakeEffects())[1]) @@ -1565,11 +1566,11 @@ class Records(unittest.TestCase): with tempfile.TemporaryDirectory() as root: claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") claude_md.mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parent), Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parent), Failure(f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records.")) pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n") - self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parent), Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) def test_stops_on_a_rule_it_cannot_read(self): @@ -1578,7 +1579,7 @@ class Records(unittest.TestCase): rules = pathlib.Path(claude_md.parent, "rules") rules.mkdir(parents=True) pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n") - self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) class JudgePrompt(unittest.TestCase): def test_shows_the_transcripts_tail_and_returns_what_it_showed(self): @@ -1712,12 +1713,12 @@ class Verdict(unittest.TestCase): self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.")) def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self): - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", taken_in=TakenIn((3,))), judge.Grounds("shown", "shown", "A.")), Interrupt("e", "q", taken_in=TakenIn((3,)))) + self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there", taken_in=TakenIn((3,))), judge.Grounds("shown", "shown", "A.")), Interrupt("s", "q", taken_in=TakenIn((3,)))) self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", TakenIn(highest_likelihood=4)), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4))) def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self): - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("e", "q")) - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("e", "q", "the records")) + self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("s", "q")) + self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("s", "q", "the records")) def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})] @@ -1829,13 +1830,14 @@ class ExitContract(unittest.TestCase): ("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), ("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read), ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), - ("cycle/run.py", "keep_answer", "1", "failure.reason", read), ("cycle/run.py", "rule", "1", "entries.reason", read), + ("cycle/run.py", "rule", "1", "failure.reason", read), ("cycle/run.py", "keep_rejection", "1", "unkept.reason", read), - ("cycle/run.py", "ask", "1", "failure.reason", read), ("cycle/run.py", "close", "1", "failure.reason", read), ("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), ("loop/close.py", "closed_cycle", "1", "failure.reason", read), + ("loop/main.py", "next_cycle", "1", "premises.reason", premises_), + ("loop/main.py", "next_cycle", "1", "records.reason", unreadable), ("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"), ("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"), ("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), @@ -1844,11 +1846,6 @@ class ExitContract(unittest.TestCase): ("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_), ("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_), ("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_), - ("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_), - ("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_), - ("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_), - ("project/text_file.py", "read_utf8", "1", "f'{name} in {folder}:", unreadable), - ("project/text_file.py", "read_utf8", "1", "f'{name} in {folder} is not UTF-8", unreadable), ] root = pathlib.Path(main.__file__).parents[1] found = [] @@ -1875,7 +1872,8 @@ class JudgeFailures(unittest.TestCase): ("verdict_from", "'the judge interrupted without a question'", unasked), ("verdict_from", "'the judge quoted an answer without a question'", unasked), ("run_judge", "verdict.reason", field), - ("run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"), + ("run_judge", "checked.reason", "quotes a passage the transcript does not hold"), + ("quotes_checked", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"), ("claude_reply", "f'could not start claude:", started), ("claude_reply", "proc.stderr.strip() or f'{who} exited", exited), ("claude_reply", 'f"{who} printed no json reply', unparsed), diff --git a/bin/model_routing/ladder.py b/bin/model_routing/ladder.py index 357409d2..3cd8b875 100644 --- a/bin/model_routing/ladder.py +++ b/bin/model_routing/ladder.py @@ -3,7 +3,7 @@ import dataclasses import re import typing -from review_passes import ReviewedPass, REVIEWERS +from review_passes import ReviewedPass # How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back. WORDING = re.compile(r"(?P\S+) at (?P\S+) effort") @@ -92,12 +92,12 @@ def stepped_up(rung: Rung) -> Rung: return climbed(rung, 1) -def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[ReviewKind, Rung]: - """The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I. +def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind) -> Rung: + """The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I. A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay …`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose. """ - return {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project} + return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact) def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung: diff --git a/bin/model_routing/review_choice.py b/bin/model_routing/review_choice.py index 439c6f31..80bcbace 100644 --- a/bin/model_routing/review_choice.py +++ b/bin/model_routing/review_choice.py @@ -2,7 +2,7 @@ import dataclasses from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route -from model_routing.ladder import review_rungs, reviewers_rung, Rung +from model_routing.ladder import reviewers_rung, Rung @dataclasses.dataclass(frozen=True) @@ -17,10 +17,10 @@ class ReviewChoice: def chosen(project: Rung, route: Route) -> ReviewChoice: """The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project.""" - rungs = review_rungs(project, route.rung, route.reviewed_on()) reviewers = reviewers_rung(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): if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers: higher.setdefault(rung, escape_and_impact) - return ReviewChoice(reviewers, rungs["seat"], rungs["security"], higher) + # A seat and the security pass run on the project's rung, as ladder.review_rung says. + return ReviewChoice(reviewers, project, project, higher) diff --git a/bin/model_routing/test_ladder.py b/bin/model_routing/test_ladder.py index b69f61f9..6558016c 100644 --- a/bin/model_routing/test_ladder.py +++ b/bin/model_routing/test_ladder.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS +from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, Rung, stepped_up, worker_rung, WORKER_STEPS from todo_table import LEVELS from review_passes import REVIEWERS @@ -96,10 +96,10 @@ class Ladder(unittest.TestCase): def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self): sonnet, fable = LADDER[0], LADDER[-1] - self.assertEqual(review_rungs(OPUS, sonnet, 4)["stability"], OPUS) - self.assertEqual(review_rungs(OPUS, sonnet, 5)["stability"], Rung("claude-opus-5-5", "high")) - self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable) - self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max")) + self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS) + self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), Rung("claude-opus-5-5", "high")) + self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable) + self.assertEqual(review_rung(OPUS, Rung("claude-opus-5-5", "high"), 7, "stability"), Rung("claude-opus-5-5", "max")) def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self): - self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS}) + self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS]) diff --git a/bin/model_routing/worker_rungs.py b/bin/model_routing/worker_rungs.py index 799238ed..92c0c362 100644 --- a/bin/model_routing/worker_rungs.py +++ b/bin/model_routing/worker_rungs.py @@ -8,7 +8,7 @@ from model_routing.route import Route PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG" WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG" -# The E + I the chunk's reviews are routed on, from which review_rungs works out each review's rung. +# The E + I the chunk's reviews are routed on, from which review_rung works out each review's rung. ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT" diff --git a/bin/release_standing.py b/bin/release_standing.py index ce94b265..2944d62b 100644 --- a/bin/release_standing.py +++ b/bin/release_standing.py @@ -75,7 +75,7 @@ class Unplanned: @dataclasses.dataclass(frozen=True) class Unknown: - """todo.md's texts since the cut, or the changes since it, cannot be read.""" + """The tags, todo.md's texts since the cut, or the changes since it, cannot be read.""" # How the plan stands to the last cut, with the item the next chunk takes first where there is one. @@ -145,9 +145,11 @@ def chunk_item(found: list[Item], cut: LastCut) -> Pick: def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: """The next release after cut, and whether work has landed towards it. found holds the plan's items. - Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read. + Cut where the plan files items under the last cut's version or earlier, and Unknown where the tags, or todo.md's texts since the cut, cannot be read. Where the branch has no tag, todos_since holds every version of todo.md, so a release todo.md named whose items are all done still reads as the next release. """ + if isinstance(cut.tag, Failure): + return Unknown() earliest = min((item.release for item in found), default=None) version = cut_version(cut) if version is None: diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index f33803de..2e8a2ad0 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -119,8 +119,8 @@ def measured(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) delegated[rung] += 1 reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values()))) spent += [Spent(kind, rung, message) for message in messages(subagent.entries)] - dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker)) - add_judge(dollars, chunk) + judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] + dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) start = route_from(cycles[0][1]) if cycles else None return ChunkFigures( dollars=dollars, @@ -136,16 +136,6 @@ def measured(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) ) -def add_judge(dollars: Dollars, chunk: Chunk) -> None: - """Adds to dollars the cost each of the chunk's outcomes records for a judge run, to the judge's rung.""" - for kept in chunk.outcomes: - for rung, cost in judge_costs(kept): - dollars["project"][chunk.project] += cost - dollars["subagent type"][JUDGE] += cost - dollars["rung"][rung] += cost - dollars["tool"][PROMPT] += cost - - def transcripts_lacking(launches: dict[str, tuple[str, dict]], subagents: list[Subagent]) -> int: """How many Agent calls, the worker's and its subagents', have no subagent transcript in the archive. Each transcript answers one call, so they are the calls less the transcripts.""" return max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in subagents) - len(subagents)) @@ -185,8 +175,8 @@ def recorded_costs(worker: list[dict]) -> dict[str, float]: return {} -def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: - """Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" +def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: + """Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float) for _, _, message in spent: listed_by_model[message.model] += message.list_price @@ -199,6 +189,11 @@ def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tupl dollars["rung"][rung] += cost for tool in message.tools: dollars["tool"][tool] += cost / len(message.tools) + for rung, cost in judged: + dollars["project"][project] += cost + dollars["subagent type"][JUDGE] += cost + dollars["rung"][rung] += cost + dollars["tool"][PROMPT] += cost return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model]) diff --git a/bin/rule_hook/reviewer_report.py b/bin/rule_hook/reviewer_report.py index 6061eac8..9c1119bc 100644 --- a/bin/rule_hook/reviewer_report.py +++ b/bin/rule_hook/reviewer_report.py @@ -7,12 +7,12 @@ from rule_hook.call import Call from review_folder import REPORTS # Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined. -REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md")) +AGENT_FILES = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md")) def report_breaches(call: Call, path: str, home: str) -> list[Breach]: """The breach of a file call from a reviewer that is not a Write under REPORTS in home; none from any other agent.""" - if call.agent not in REVIEWERS: + if call.agent not in AGENT_FILES: return [] written = os.path.realpath(os.path.join(call.cwd, path)) reports = os.path.realpath(os.path.join(home, REPORTS)) diff --git a/bin/rule_hook/reviewer_rung.py b/bin/rule_hook/reviewer_rung.py index 5847369d..73de2f5d 100644 --- a/bin/rule_hook/reviewer_rung.py +++ b/bin/rule_hook/reviewer_rung.py @@ -8,7 +8,7 @@ from failure import Failure import git_repo from rule_hook.git import guarded_git from model_routing.worker_rungs import handed -from model_routing.ladder import position, review_rungs, ReviewKind, Rung +from model_routing.ladder import position, review_rung, ReviewKind, Rung from review_passes import prose, REVIEWERS from claude_code.transcript import read_transcript @@ -29,7 +29,7 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Bre kind = review_kind(call.given) if kind is None or project is None or worker is None: return [] - required = review_rungs(project, worker, escape_and_impact)[kind] + required = review_rung(project, worker, escape_and_impact, kind) # A branch that changes only Markdown no agent follows holds no code or config for a reviewer on a higher rung to catch a defect in: skills/larv-review/SKILL.md → "Markdown only". if kind in REVIEWERS and position(required) > position(project) and markdown_only(call.cwd): required = project diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 76ae9c43..929005fb 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -34,14 +34,12 @@ import shutil import sys import typing +from run_heavy.capped_docker import CANNOT_RUN, NOT_FOUND, PATH_ENTRY, SHARE_VARIABLE, without_path_entry from failure import Failure from machine_load.memory import Memory -from run_heavy.capped_docker import PATH_ENTRY, SHARE_VARIABLE, without_path_entry from machine_load.slots import slot_count, slot_folder, waited_slot OWN_FAILURE = 125 -CANNOT_RUN = 126 -NOT_FOUND = 127 HELD = "RUN_HEAVY_SLOT" USAGE = "usage: run-heavy [...]" diff --git a/bin/test_release_standing.py b/bin/test_release_standing.py index c957da2d..119fa20c 100644 --- a/bin/test_release_standing.py +++ b/bin/test_release_standing.py @@ -67,7 +67,8 @@ class ChunkItem(unittest.TestCase): (None, 4, (0, 2, 0), set(), release_standing.Next((0, 2, 0), one((0, 2, 0)))), (None, 4, None, set(), release_standing.Next(None, None)), ("v1.2.3-rc.1", 4, (1, 2, 3), set(), release_standing.Next((1, 2, 3), one((1, 2, 3)))), - (Failure("tags unreadable"), 4, (0, 2, 0), set(), release_standing.Next((0, 2, 0), one((0, 2, 0)))), + (Failure("tags unreadable"), 4, (0, 2, 0), set(), release_standing.Unknown()), + (Failure("tags unreadable"), 4, None, set(), release_standing.Unknown()), ("v1.2.3", 4, (1, 2, 3), set(), release_standing.Cut((1, 2, 3))), ("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Cut((1, 2, 2))), ("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, release_standing.ReadyToCut((1, 2, 4))), diff --git a/bin/todo_table.py b/bin/todo_table.py index 286127cb..a52dbfce 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -24,7 +24,6 @@ CODE_HEALTH = "code health" HEADER_START = "| ID | Release |" # todo.md's ## Details section, its body the first group. DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) -# A release's version, such as 0.2.1. # One line of todo.md's ## Renamed section: the release it renamed and the one it became. RENAME = re.compile(rf"- ({VERSION}) renamed to ({VERSION})") # Each goal an item names, in its order, with how far the item moves it; None in OLD_SHAPE, whose Goals cell names no move.