220 lines
12 KiB
Python
220 lines
12 KiB
Python
import dataclasses
|
|
import json
|
|
import re
|
|
import typing
|
|
|
|
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED
|
|
from claude_code.reply import claude_reply, Limited
|
|
from loop_claude.effects import Effects
|
|
from failure import Failure
|
|
from loop_claude.project.records import HUMAN_RULE_NAMES
|
|
from todo_table import LEVELS
|
|
from markdown_text import listed
|
|
from model_routing.route import on_its_scale
|
|
from loop_claude.cycle.retry import retried
|
|
from model_routing.ladder import Rung
|
|
from loop_claude.stop import Stop
|
|
from claude_code.entries import structured_output
|
|
|
|
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
|
|
JUDGE_PROMPT_CHARS = 400000
|
|
JUDGE_RULES = (
|
|
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
|
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
|
|
"README.md nor the records settle the matter\n"
|
|
"- it asks again a question a [loop] line already answered\n"
|
|
"- it carried on under an assumption that decides the deliverable, that the human could "
|
|
"reasonably reject and that neither README.md nor the records settle; a caveat about "
|
|
"transient state it then handled is not one\n"
|
|
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
|
|
"outside the repo, or a release ready to cut, which only the human may publish\n"
|
|
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
|
|
"- it chose between alternatives that neither README.md nor the records discriminate "
|
|
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
|
|
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
|
|
"where a note goes - is not on its own a reason to interrupt. A run that ends asking loop-claude for a higher "
|
|
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is. The human may have replied inside the transcript, on a [human] line: judge only what "
|
|
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
|
|
"the agent, such as an answer quoted from README.md or the records.\n\n"
|
|
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
|
"wording; never construct another from facts it stated.\n\n"
|
|
"Where README.md or the records answer the agent's own question and no [loop] line has "
|
|
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
|
|
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
|
|
"outranks finished.\n\n"
|
|
"The chunk is the piece of work the agent is on, shipped as one pull request. "
|
|
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
|
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
|
|
f"where README.md or the records above hold it, {', '.join(HUMAN_RULE_NAMES)} included. It also counts where "
|
|
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
|
|
f"{listed(HUMAN_RULE_NAMES, 'or')} does not count. finished=false when work remains that a further run can "
|
|
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
|
|
)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Reply:
|
|
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
|
|
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
|
|
bundled: int = dataclasses.field(metadata={"description": "The highest L the agent states for a todo.md item it took into this chunk; 0 when it states none."})
|
|
# Routes the next cycle's judge and reviewers, as bundled routes the worker.
|
|
bundled_escape_and_impact: int = dataclasses.field(metadata={"description": "The highest E + I the agent states for a todo.md item it took into this chunk; 0 when it states none."})
|
|
# Routes the next cycle's worker one rung up: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
|
|
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished and the agent's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of an earlier transcript passage showing the trigger fired after any earlier such request, such as a review round's commit title or the agent's report of the finding or failing test. Never the request itself."})
|
|
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
|
|
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
|
|
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
|
|
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
|
|
|
|
|
|
REPLY_TYPES = typing.get_type_hints(Reply)
|
|
JSON_TYPES = {bool: "boolean", int: "integer", str: "string"}
|
|
HIGHEST_L = LEVELS["L"]
|
|
JUDGE_SCHEMA = {
|
|
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
|
"required": list(REPLY_TYPES),
|
|
"type": "object",
|
|
}
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Rejected(Failure):
|
|
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json."""
|
|
reply: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Interrupt:
|
|
evidence: str
|
|
question: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class QuotedAnswer:
|
|
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
|
|
evidence: str
|
|
question: str
|
|
answer: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Finished:
|
|
evidence: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Unfinished:
|
|
evidence: str
|
|
# The bundled L the judge saw, 0 for none.
|
|
bundled: int = 0
|
|
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
|
escalation: str = ""
|
|
# The bundled E + I the judge saw, 0 for none.
|
|
bundled_escape_and_impact: int = 0
|
|
|
|
|
|
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
|
|
|
|
|
def verdict_from(output: object) -> Verdict | Failure:
|
|
if not isinstance(output, dict):
|
|
return Failure("the judge returned no reply")
|
|
for name, kind in REPLY_TYPES.items():
|
|
# type(), not isinstance(): JSON true is no integer.
|
|
if type(output.get(name)) is not kind:
|
|
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
|
if output["interrupt"]:
|
|
if not output["question"].strip():
|
|
return Failure("the judge interrupted without a question")
|
|
return Interrupt(output["evidence"], output["question"])
|
|
if output["answer"].strip():
|
|
if not output["question"].strip():
|
|
return Failure("the judge quoted an answer without a question")
|
|
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
|
|
if output["finished"]:
|
|
return Finished(output["evidence"])
|
|
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
|
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0
|
|
bundled_escape_and_impact = output["bundled_escape_and_impact"] if on_its_scale(output["bundled_escape_and_impact"]) else 0
|
|
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact)
|
|
|
|
|
|
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
|
return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
|
|
|
|
|
def judge_once(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
|
"""One judge run, as judge retries it; judge-replay replays it."""
|
|
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
|
|
return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
|
|
|
|
|
|
def judge_args(rung: Rung) -> list[str]:
|
|
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
|
|
# No tools, so the verdict rests on the transcript grounded() checks it against.
|
|
return [
|
|
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
|
*rung.flags(),
|
|
"--tools", "",
|
|
]
|
|
|
|
|
|
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
|
|
"""One judge run, its three quotes each checked against what they quote:
|
|
- evidence, against shown, its fragments in order: a misquote is a Failure, which judge retries;
|
|
- a quoted answer, against quotable, word for word: a misquote puts the question to the human;
|
|
- an escalation, against shown, word for word: a misquote drops it, so the worker's rung holds.
|
|
A misquoted answer or escalation is no Failure, which would otherwise exit an unattended loop. Neither may be elided, since stitched fragments can say what the records or the transcript do not.
|
|
"""
|
|
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
|
|
if isinstance(reply, Failure | Limited):
|
|
return reply
|
|
verdict = verdict_from(structured_output(reply))
|
|
replied = json.dumps(reply, ensure_ascii=False)
|
|
if isinstance(verdict, Failure):
|
|
return Rejected(verdict.reason, replied)
|
|
if not grounded(verdict.evidence, 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)
|
|
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
|
|
return Interrupt(verdict.evidence, verdict.question)
|
|
if isinstance(verdict, Unfinished) and verdict.escalation and not verbatim(verdict.escalation, shown):
|
|
return dataclasses.replace(verdict, escalation="")
|
|
return verdict
|
|
|
|
|
|
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]:
|
|
"""The prompt, and the part of the transcript it shows, which the judge's evidence must quote."""
|
|
head = (
|
|
f"From README.md:\n{premises}\n\n"
|
|
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{records or 'none'}\n\n"
|
|
f"The task an agent was given:\n{task}\n\n"
|
|
"What the agent did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
|
|
)
|
|
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
|
|
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
|
shown = rendered_transcript[max(0, len(rendered_transcript) - room):]
|
|
return f"{head}{shown}\n\n{JUDGE_RULES}", shown
|
|
|
|
|
|
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
|
# The judge joins passages with an ellipsis though told to quote one.
|
|
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
|
|
transcript = plain(rendered_transcript)
|
|
at = 0
|
|
for fragment in fragments:
|
|
found = transcript.find(fragment, at)
|
|
if found < 0:
|
|
return False
|
|
at = found + len(fragment)
|
|
return fragments != []
|
|
|
|
|
|
def verbatim(quote: str, text: str) -> bool:
|
|
quoted = plain(quote)
|
|
return quoted != "" and quoted in plain(text)
|
|
|
|
|
|
def plain(text: str) -> str:
|
|
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
|
return " ".join(text.replace("*", "").replace("_", "").split())
|