113 lines
5.4 KiB
Python
113 lines
5.4 KiB
Python
import dataclasses
|
|
import json
|
|
import typing
|
|
|
|
from loop_claude.claude_code.entries import structured_output
|
|
from loop_claude.cycle.retry import retried
|
|
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
|
|
from loop_claude.effects import Effects
|
|
from loop_claude.failure import Failure
|
|
from loop_claude.stop import Stop
|
|
|
|
JUDGED_TRANSCRIPT_TAIL = 40000
|
|
|
|
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\n"
|
|
"- it carried on under an assumption that decides the deliverable and that the human could "
|
|
"reasonably reject; 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 release "
|
|
"ready to cut, a choice outside the repo\n"
|
|
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
|
|
"- it chose between alternatives the README text does not discriminate between - it does not "
|
|
"rule 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. 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"
|
|
"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"
|
|
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
|
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
|
|
"not yet run, CI not yet reported."
|
|
)
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Reply:
|
|
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."})
|
|
finished: bool
|
|
interrupt: bool
|
|
question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."})
|
|
|
|
|
|
REPLY_TYPES = typing.get_type_hints(Reply)
|
|
JSON_TYPES = {bool: "boolean", str: "string"}
|
|
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",
|
|
}
|
|
|
|
|
|
def judge(root: str, task: str, premises: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
|
|
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
|
args = [
|
|
"-p",
|
|
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
|
"--model", model,
|
|
"--no-session-persistence",
|
|
"--output-format", "json",
|
|
"--permission-mode", "bypassPermissions",
|
|
"--tools", "",
|
|
]
|
|
prompt = judge_prompt(task, premises, rendered_transcript)
|
|
return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects)
|
|
|
|
|
|
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure:
|
|
try:
|
|
proc = effects.claude(args, root, prompt)
|
|
except OSError as failure:
|
|
return Failure(f"could not start claude: {failure.strerror}")
|
|
if proc.returncode != 0:
|
|
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
|
verdict = verdict_from(structured_output(proc.stdout))
|
|
if isinstance(verdict, Failure):
|
|
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
|
|
if not grounded(verdict.evidence, rendered_transcript):
|
|
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) else ""))
|
|
return verdict
|
|
|
|
|
|
def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str:
|
|
return (
|
|
f"From README.md:\n{premises}\n\n"
|
|
f"The task an agent was given:\n{task}\n\n"
|
|
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
|
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{rendered_transcript[-JUDGED_TRANSCRIPT_TAIL:]}\n\n"
|
|
f"{JUDGE_RULES}"
|
|
)
|
|
|
|
|
|
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 isinstance(output.get(name), kind):
|
|
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
|
# An interrupt outranks finished: the human answers before the chunk can close.
|
|
if output["interrupt"]:
|
|
if not output["question"].strip():
|
|
return Failure("the judge interrupted without a question")
|
|
return Interrupt(output["evidence"], output["question"])
|
|
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
|
|
|
|
|
|
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
|
quoted = plain(evidence)
|
|
return quoted != "" and quoted in plain(rendered_transcript)
|
|
|
|
|
|
def plain(text: str) -> str:
|
|
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
|
return " ".join(text.replace("*", "").replace("_", "").split())
|