Answer architecture round 1: Failure and the file modules get truthful homes, the interrupt question is a pure function, the judge grounds on what it saw

This commit is contained in:
2026-10-03 18:06:56 +02:00
parent ae7c332ba3
commit d3613f45d4
31 changed files with 217 additions and 85 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ import pathlib
import shutil
import uuid
from file_io.failure import Failure
from failure import Failure
from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
+1 -1
View File
@@ -1,7 +1,7 @@
import json
from loop_claude.claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
from file_io.failure import Failure
from failure import Failure
JUDGED_TOOL_INPUT = 400
+2 -2
View File
@@ -2,8 +2,8 @@ import json
import pathlib
import sys
from file_io.failure import Failure
from file_io.writes import replace_json
from failure import Failure
from files.writes import replace_json
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
+4 -3
View File
@@ -3,9 +3,9 @@ import os
import pathlib
import sys
from file_io.failure import Failure
from failure import Failure
from loop_claude.claude_code.transcript import first_timestamped_line
from file_io.writes import make_private, replace_file
from files.writes import make_private, replace_file
from loop_claude.paths import Paths
from loop_claude.claude_code.session import session_files
@@ -24,7 +24,8 @@ def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths)
return unkept
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
outcomes = copy.with_suffix(".outcomes.md")
if copy.exists():
# A copy whose outcomes file is missing is written afresh, outcomes first.
if copy.exists() and outcomes.exists():
return add_outcome(outcomes, outcome)
# The copy lands last, so a copy on disk always has its outcomes and its session's files beside it.
for dest, data in ((outcomes, f"Task: {task}\n\n{outcome}\n".encode()), (copy, raw)):
+1 -1
View File
@@ -2,7 +2,7 @@ import sys
import uuid
from loop_claude.effects import Effects
from file_io.failure import Failure
from failure import Failure
from loop_claude.claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
+10 -9
View File
@@ -2,11 +2,10 @@ import json
import re
from loop_claude.effects import Effects
from file_io.failure import Failure
from failure import Failure
from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from loop_claude.cycle.verdicts import Interrupt, JUDGE_RULES, JUDGE_SCHEMA, QuotedAnswer, Verdict, verdict_from
from loop_claude.cycle.limited import Limited
from loop_claude.cycle.retry import retried
from loop_claude.cycle.retry import Limited, retried
from loop_claude.stop import Stop
# 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.
@@ -25,11 +24,11 @@ def judge(root: str, task: str, premises: str, records: str, rendered_transcript
"--permission-mode", "bypassPermissions",
"--tools", "",
]
prompt = judge_prompt(task, premises, records, rendered_transcript)
return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, f"{premises}\n\n{records}", effects), effects)
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
return retried("judge", lambda: run_judge(root, args, prompt, shown, f"{premises}\n\n{records}", effects), effects)
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
try:
proc = effects.claude(args, root, prompt)
except OSError as failure:
@@ -43,7 +42,7 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str,
verdict = verdict_from(structured_output(reply))
if isinstance(verdict, Failure):
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
if not grounded(verdict.evidence, rendered_transcript):
if not grounded(verdict.evidence, 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 ""))
# Not a Failure: a misquote would otherwise exit an unattended loop. Never elided: stitched fragments can say what the records do not.
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
@@ -51,7 +50,8 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str,
return verdict
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> str:
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 project's records, its working rules and decisions:\n{records or 'none'}\n\n"
@@ -60,7 +60,8 @@ def judge_prompt(task: str, premises: str, records: str, rendered_transcript: st
)
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.
return f"{head}{rendered_transcript[max(0, len(rendered_transcript) - room):]}\n\n{JUDGE_RULES}"
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:
-8
View File
@@ -1,8 +0,0 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
+13 -4
View File
@@ -1,17 +1,26 @@
import dataclasses
import sys
import typing
from loop_claude.effects import Effects
from file_io.failure import Failure
from loop_claude.cycle.limited import Limited
from failure import Failure
from loop_claude.stop import Stop
T = typing.TypeVar("T")
FAILURES_RUNNING = 3
PAST_RESET = 120
RETRY_DELAY = 60
UNKNOWN_RESET_POLL = 600
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
failures = 0
while True:
@@ -27,10 +36,10 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
if not isinstance(result, Failure):
return result
failures += 1
if failures == 3:
if failures == FAILURES_RUNNING:
return Stop(1, f"the {who} failed three times running: {result.reason}")
print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr)
effects.sleep(60)
effects.sleep(RETRY_DELAY)
def limit_wait(limited: Limited, now: float) -> float:
+12 -6
View File
@@ -1,11 +1,11 @@
import dataclasses
import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, Ruled, State, transition, WorkerRan, Working
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
from loop_claude.cycle.archive import archive
from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
from file_io.failure import Failure
from failure import Failure
from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle.interrupt import interrupt
from loop_claude.cycle.judge import judge
@@ -57,8 +57,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
return work(cycle, answered)
case Judging(transcript_path, _):
return rule(cycle, transcript_path)
case Interrupting(transcript_path, ruling, quoted_answers):
return ask(cycle, transcript_path, ruling, 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 _:
@@ -83,14 +83,20 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> HumanAnswered | Stop:
question = ruling.question if isinstance(ruling, Interrupt) else f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {quoted_answers} questions this cycle, the most allowed, so this one comes to you."
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | 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.
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}", cycle.paths):
return Stop(1, failure.reason)
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered()
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
if isinstance(ruling, Interrupt):
return ruling.question
return f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {QUOTED_ANSWERS_PER_CYCLE} questions this cycle, the most allowed, so this one comes to you."
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
finished = isinstance(verdict, Finished)
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}", cycle.paths):
+1 -1
View File
@@ -15,7 +15,7 @@ class Working:
@dataclasses.dataclass(frozen=True)
class Judging:
"""The judge rules; quoted_answers counts the questions README.md or the records answered this cycle."""
"""The judge rules; quoted_answers counts the questions README.md or the records answered this cycle, and an interrupt does not reset it."""
transcript_path: str
quoted_answers: int = 0
+5 -5
View File
@@ -1,9 +1,8 @@
import dataclasses
import typing
from file_io.failure import Failure
from failure import Failure
# The one statement of when the judge interrupts, quotes an answer or finds the chunk finished; Reply's field descriptions say only what each field holds.
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 "
@@ -25,7 +24,8 @@ JUDGE_RULES = (
"wording; never construct another from facts it stated.\n"
"Where README.md or the project's records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the answer; the agent is "
"then given that passage in place of the human's reply.\n"
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished.\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 "
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
@@ -37,8 +37,8 @@ JUDGE_RULES = (
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the project's records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
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. Read only when interrupt is false and answer is empty."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted. True outranks answer and finished."})
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."})
+2 -2
View File
@@ -1,7 +1,7 @@
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from loop_claude.effects import Effects
from file_io.failure import Failure
from loop_claude.cycle.limited import Limited
from failure import Failure
from loop_claude.cycle.retry import Limited
from loop_claude.claude_code.transcript import part_line
from loop_claude.project.records import QUOTE_SOURCES
from loop_claude.cycle.verdicts import QuotedAnswer
+2 -2
View File
@@ -33,8 +33,8 @@ Every claude loop-claude starts runs the project's model, saved per <key> in
run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL
for the worker and the interrupt; with both set, nothing is asked.
A change to bin/loop-claude, bin/file_io/**/*.py or bin/loop_claude/**/*.py takes effect at the next
cycle boundary, once loop-claude --help succeeds: the loop reloads into the edited script.
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
loop-claude --help succeeds: the loop reloads into the edited script.
Exit 1, saying why, when:
- no task is given
+1 -2
View File
@@ -8,7 +8,6 @@ import typing
from loop_claude.effects import Effects
from loop_claude.stop import Stop
PACKAGES = ("file_io", "loop_claude")
RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T")
@@ -37,7 +36,7 @@ def decode_handed(handed: str, kind: type[T]) -> T | None:
def fingerprint(launcher: pathlib.Path) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted(path for package in PACKAGES for path in (launcher.parent / package).rglob("*.py"))]:
for path in [launcher, *sorted(launcher.parent.rglob("*.py"))]:
try:
content = path.read_bytes()
except OSError as failure:
+2 -2
View File
@@ -6,10 +6,10 @@ import typing
from loop_claude.claude_code.model_catalog import catalog_models
from loop_claude.effects import Effects
from file_io.failure import Failure
from failure import Failure
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from file_io.writes import replace_json
from files.writes import replace_json
@dataclasses.dataclass(frozen=True)
+1 -1
View File
@@ -1,5 +1,5 @@
from loop_claude.project.checkout import read_checkout_file
from file_io.markdown import sections
from files.markdown import sections
from loop_claude.stop import Stop