Files

159 lines
13 KiB
Python

"""What every entry point says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. An entry point places them in a chunk's first prompt, as loop-claude does in bin/loop_claude/chunk/fresh_prompt.py. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
import functools
import typing
from agent_cycle.worker_prompts import answers_recorded, WorkerPrompts
from agent_cycle.escalation_mark import asks_higher_rung
from model_routing.review_choice import chosen, ReviewChoice
from model_routing.route import ESCALATION_MARKER, Route
from agent_cycle.routing import escalation_rungs
from chunk_driver.project.records import HUMAN_RULE_NAMES, RECORD_FILES, RECORDS_NAMED
from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS
from text_files.markdown_text import listed, quoted
from model_routing.ladder import ProjectRung, Rung
# Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises.
QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the plan or a comment"
ANSWERS_RECORDED = answers_recorded(ANSWER_DESTINATIONS)
# How review_launches names the reviews: "each reviewer" covers every pass with an agent.
EACH_REVIEWER = "each reviewer"
EACH_SEAT = "each comprehension seat"
THE_SECURITY_PASS = "the security pass's subagent"
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
def review_launches(route: Route, project: ProjectRung | None) -> list[str]:
"""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)
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice)]
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: ProjectRung) -> list[str]:
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.rung.model} <L>` prints."] if project.ladder.position(route.rung) < project.ladder.position(project.rung) else []
def markdown_launch(choice: ReviewChoice) -> list[str]:
"""The sentence that names choice.markdown_only, the rung a reviewer runs on where the branch changes only Markdown no agent follows. It is empty where that rung is the reviewers'. rule-hook's reviewer-rung holds a launch to the same rung. 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 choice.markdown_only == choice.reviewers:
return []
files = ", ".join(f"`{name}`" for name in INSTRUCTION_FILES)
folders = listed([f"`{folder}/`" for folder in INSTRUCTION_FOLDERS], "or")
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 {choice.markdown_only.agent_args()}."]
def shared_launches(choice: ReviewChoice, route: Route, project: ProjectRung) -> list[str]:
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
For a worker one rung below the project's, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to <rung>, 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 <rung>, 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():
if rung != route.rung:
launched.setdefault(rung, []).append(reviews)
return [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 taken_in_launches(choice: ReviewChoice) -> list[str]:
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since loop-claude reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
For a worker on the project's rung, 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 `<rung>` from 7 and `<rung>` from 8.`
"""
if not choice.higher:
return []
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in choice.higher.items()]
return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."]
def rung_named(rung: Rung, route: Route, project: ProjectRung) -> 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.rung:
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(driver: str, route: Route, project: ProjectRung | None) -> list[str]:
"""The prompt's escalation sentences, the marker's among them. None 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 one rung above the project's, routed by item 3 of L 3, 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 `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `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 `<rung>`.`
"""
if project is None or route.rung not in project.ladder.rungs[:-1]:
return []
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
if not rungs:
return [
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 `{project.ladder.climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; {driver} will not resume you higher for a trigger either, so ask the human for that yes.",
marked,
]
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
return [
f"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 {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
marked,
f"Where the hard part is the rest of the chunk, end your run instead, {asks_higher_rung(driver)} 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 {rungs[-1]}.",
]
def reruns(route: Route, project: ProjectRung | None) -> list[str]:
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
For a worker one rung below the project's, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `<rung>`.`
"""
if project is None or route.rung not in project.ladder.rungs:
return []
choice = chosen(project, route)
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
rerun = {name: project.ladder.climbed(rung, 1) for name, rung in launched if rung != project.ladder.rungs[-1]}
if not rerun:
return []
if len(set(rerun.values())) == 1:
return [f"A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."]
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(driver: str, naming: str, unfinished_evidence: str, route: Route, project: ProjectRung | None) -> str:
"""naming is the sentence that asks the worker to name its chunk's items, empty where the entry point reads none. 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" {driver} 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}.{naming and f' {naming}'}{on}{rungs_held(driver, route, project)}"
def rung_sentences(driver: str, route: Route, project: ProjectRung | None) -> list[str]:
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
return [*review_launches(route, project), *escalation(driver, route, project), *reruns(route, project)]
def rungs_held(driver: str, route: Route, project: ProjectRung | None) -> str:
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
return "".join(f" {sentence}" for sentence in rung_sentences(driver, route, project))
class RecordNames(typing.NamedTuple):
"""The names an entry point's prompts give the places that answer a question, the places that take an answer, and the records the judge reads; WorkerPrompts says what each field is."""
quote_sources: str = QUOTE_SOURCES
answer_destinations: str = ANSWER_DESTINATIONS
records_named: str = RECORDS_NAMED
def worker_prompts(driver: str, fresh: typing.Callable[[str, str, Route, ProjectRung | None, str], str], naming: str, names: RecordNames = RecordNames()) -> WorkerPrompts:
"""The prompts of an entry point's cycles: its own fresh prompt, and the resumed prompt and rung sentences every entry point shares, each naming driver. resumed says what naming is. names is loop-claude's unless the entry point keeps records elsewhere, as do-epic does."""
return WorkerPrompts(driver, fresh, functools.partial(resumed, driver, naming), functools.partial(rungs_held, driver), *names)