238 lines
15 KiB
Python
238 lines
15 KiB
Python
import dataclasses
|
|
import json
|
|
import re
|
|
import typing
|
|
|
|
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
|
|
from claude_code.reply import claude_reply, Limited
|
|
from loop_claude.effects import Effects
|
|
from loop_claude import escalation_mark
|
|
from failure import Failure
|
|
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished, Verdict
|
|
from todo_table import LEVELS
|
|
from model_routing.route import on_its_scale
|
|
from claude_code.transcript import plain, verbatim
|
|
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
|
|
INTERRUPT_RULES = (
|
|
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
|
"- the worker 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\n"
|
|
"interrupt=false otherwise. Bookkeeping the worker 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.\n\n"
|
|
"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.\n\n"
|
|
"Where the worker asked or flagged something itself, the question is that one, in the worker's own "
|
|
"wording; never construct another from facts it stated."
|
|
)
|
|
QUOTE_RULES = (
|
|
"Where README.md or the records answer the worker's own question and no [loop] line has "
|
|
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the worker is "
|
|
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
|
|
"outranks finished."
|
|
)
|
|
FINISHED_RULES = (
|
|
"The chunk is the piece of work the worker is on, shipped as one pull request.\n\n"
|
|
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
|
|
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}.\n\n"
|
|
"An answer counts as recorded where README.md or the records above already hold it, the human's rules "
|
|
"(~/.claude/CLAUDE.md, ~/.claude/rules/, ~/.claude/skills/larv-review/standards/) included. "
|
|
f"It also counts where the transcript shows the worker writing it into {ANSWER_DESTINATIONS}, "
|
|
"but not into one of the human's rules.\n\n"
|
|
"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."
|
|
)
|
|
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
|
|
|
|
|
|
@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 worker'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.
|
|
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker 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 highest_likelihood_taken_in routes the worker.
|
|
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
|
# Lists the chunk's items in loop-inbox: running_loops.py.
|
|
items_taken_in: list[int] = dataclasses.field(metadata={"description": "The IDs of the todo.md items the worker states this chunk takes, the item the chunk was routed on included, never an item it only filed in todo.md for later; empty when it states none."})
|
|
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
|
|
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and 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 worker'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 worker's question that the answer field answers. Empty otherwise."})
|
|
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
|
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
|
|
|
|
|
REPLY_TYPES = typing.get_type_hints(Reply)
|
|
JSON_TYPES: dict[object, dict[str, typing.Any]] = {bool: {"type": "boolean"}, int: {"type": "integer"}, str: {"type": "string"}, list[int]: {"type": "array", "items": {"type": "integer"}}}
|
|
HIGHEST_L = LEVELS["L"]
|
|
JUDGE_SCHEMA = {
|
|
"properties": {field.name: {**field.metadata, **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, and cost is what the run cost in dollars, 0 where its reply records none."""
|
|
reply: str
|
|
cost: float = 0.0
|
|
|
|
|
|
class Grounds(typing.NamedTuple):
|
|
"""The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order."""
|
|
# The transcript as the judge saw it.
|
|
shown: str
|
|
# 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.
|
|
quotable: str
|
|
|
|
|
|
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():
|
|
if not fits(output.get(name), kind):
|
|
return Failure(f"the judge's reply has no {name} of type {type_name(JSON_TYPES[kind])}")
|
|
taken_in = taken_in_from(output)
|
|
if output["interrupt"]:
|
|
if not output["question"].strip():
|
|
return Failure("the judge interrupted without a question")
|
|
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], taken_in=taken_in, release_ready=output["release_ready"])
|
|
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"], escalation=output["escalation"], taken_in=taken_in)
|
|
if output["finished"]:
|
|
return Finished(output["evidence"])
|
|
return Unfinished(output["evidence"], escalation=output["escalation"], taken_in=taken_in)
|
|
|
|
|
|
def type_name(schema: dict[str, typing.Any]) -> str:
|
|
return f"array of {schema['items']['type']}s" if schema["type"] == "array" else schema["type"]
|
|
|
|
|
|
def fits(value: object, kind: object) -> bool:
|
|
"""Whether value, read from the judge's JSON, is of kind. type(), not isinstance(): JSON true is no integer."""
|
|
if typing.get_origin(kind) is list:
|
|
return type(value) is list and all(fits(each, typing.get_args(kind)[0]) for each in value)
|
|
return type(value) is kind
|
|
|
|
|
|
def taken_in_from(output: dict) -> TakenIn:
|
|
"""The reply's readings of the items taken in. An ID below 1 is left out, and an L or E + I off its scale counts as 0. Neither fails the reply: three failures would stop an unattended loop, and holding the rung is safe."""
|
|
likelihood = output["highest_likelihood_taken_in"]
|
|
escape_and_impact = output["highest_escape_and_impact_taken_in"]
|
|
return TakenIn(
|
|
tuple(item for item in output["items_taken_in"] if item > 0),
|
|
likelihood if 0 <= likelihood <= HIGHEST_L else 0,
|
|
escape_and_impact if on_its_scale(escape_and_impact) else 0,
|
|
)
|
|
|
|
|
|
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
|
return retried("judge", lambda: judge_once(root, task, premises, records, entries, escalated_at, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
|
|
|
|
|
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
|
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark, as loop_claude/escalation_mark.py says."""
|
|
prompt, grounds = judge_prompt(task, premises, records, entries, escalated_at)
|
|
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
|
|
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(entries))
|
|
|
|
|
|
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, grounds: Grounds, effects: Effects) -> Verdict | Failure | Limited:
|
|
"""One judge run, each quote in its verdict checked against grounds as Grounds says."""
|
|
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)
|
|
cost = cost_of(reply)
|
|
if isinstance(verdict, Failure):
|
|
return Rejected(verdict.reason, replied, 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:
|
|
"""What the run behind claude's json reply cost in dollars; 0 where the reply records none."""
|
|
cost = reply.get("total_cost_usd")
|
|
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 | Failure:
|
|
"""The verdict with each of its quotes checked against the text it must appear in, as written:
|
|
|
|
| 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. A Failure for either of the other two would exit an unattended loop, so each changes the verdict instead.
|
|
"""
|
|
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)
|
|
|
|
|
|
def judge_prompt(task: str, premises: str, records: str, entries: list[dict], escalated_at: int) -> tuple[str, Grounds]:
|
|
"""The prompt, and what the judge's quotes are checked against."""
|
|
transcript = escalation_mark.transcript(entries, escalated_at, typed_answer)
|
|
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 the worker was given:\n{task}\n\n"
|
|
"What the worker 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 = transcript[max(0, len(transcript) - room):]
|
|
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, escalation_mark.since_step(entries, escalated_at), f"{premises}\n\n{records}")
|
|
|
|
|
|
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 != []
|