Answer stability round 1: 0 🔴, 2 🟡 (1 misread); compact on the worker's rung, announce the compaction and skip it once the cache expired

This commit is contained in:
2026-11-19 04:42:14 +01:00
parent 30595cfdf4
commit 78dd557057
5 changed files with 113 additions and 40 deletions
+15 -8
View File
@@ -11,7 +11,7 @@ from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from claude_code.reply import Limited
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.cycle.worker import run_worker
from loop_claude.cycle.worker import run_claude
from model_routing.ladder import Rung
from loop_claude.direct_message import tell
from loop_claude import tmux
@@ -33,6 +33,8 @@ class WorkerSession:
root: str
id: uuid.UUID
rung: Rung
# The rung the worker last ran on: below rung where the ruling that interrupts stepped the worker up.
ran_on: Rung
transcript_path: str
# Added to the environment of the worker's claude, and of the claude /talk opens.
env: dict[str, str]
@@ -75,10 +77,11 @@ def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str
def waited_answer(session: WorkerSession, effects: Effects) -> str | Stop:
"""typed_answer, compacting the worker's session where no answer has come shortly before its prompt cache expires. The claude TALK opens compacts an idle session itself."""
entries = read_transcript(session.transcript_path)
delay = None if isinstance(entries, Failure) else compaction_delay(entries, effects.now())
now = effects.now()
delay = None if isinstance(entries, Failure) else compaction_delay(entries, now)
if delay is None:
return typed_answer(effects)
stop_timer = effects.timer(delay, lambda: compact(session, effects))
stop_timer = effects.timer(delay, lambda: compact(session, now + delay + CACHE_MARGIN, effects))
try:
return typed_answer(effects)
finally:
@@ -103,13 +106,17 @@ def compaction_delay(entries: list[Entry], now: float) -> float | None:
return delay if delay > 0 else None
def compact(session: WorkerSession, effects: Effects) -> None:
"""Compacts the worker's session with `claude -p /compact`, saying how that went."""
outcome = run_worker(session.root, claude_args(session.rung, ["-p", "/compact", "--resume", str(session.id), "--output-format", "stream-json", "--verbose"]), session.env, effects)
def compact(session: WorkerSession, expires: float, effects: Effects) -> None:
"""Compacts the worker's session with `claude -p /compact`, saying that it starts and how it went. Each line opens on a line of its own, below the open ASK_ANSWER. From expires on, when the prompt cache has expired, it doesn't do anything: a timer fires late where the machine was suspended."""
if effects.now() >= expires:
return
say("\ncompacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends", effects)
# On the rung the worker ran on, not the one a ruling stepped it up to: the prompt cache is kept per model, and another effort may miss it too, so another rung would read the whole context at full price. Without run_worker's wait for memory, which could outlast the cache.
outcome = run_claude(session.root, claude_args(session.ran_on, ["-p", "/compact", "--resume", str(session.id), "--output-format", "stream-json", "--verbose"]), session.env, effects)
if outcome is None:
say("compacted the worker's claude session before its prompt cache expires; still waiting for an answer", effects)
say("\ncompacted the worker's claude session", effects)
else:
say(f"could not compact the worker's claude session: {outcome.said if isinstance(outcome, Limited) else outcome.reason}; still waiting for an answer", effects)
say(f"\ncould not compact the worker's claude session: {outcome.said if isinstance(outcome, Limited) else outcome.reason}", effects)
def typed_answer(effects: Effects) -> str | Stop:
+10 -10
View File
@@ -74,8 +74,8 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
if isinstance(event, Stop):
return stopped(cycle, event, event.reason)
# Only a ruling's step-up changes the route within a cycle, here, once rule has archived the ruling on the route before it. No transition reads the current route, so Cycle holds it, not the states.
if isinstance(event, Ruled) and event.stepped_to:
cycle = dataclasses.replace(cycle, route=event.stepped_to)
if isinstance(event, Ruled) and event.stepped:
cycle = dataclasses.replace(cycle, route=event.stepped.after)
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
@@ -109,8 +109,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
return work(cycle, answered, stepped)
case Judging(transcript_path, quoted_answers):
return rule(cycle, transcript_path, quoted_answers)
case Interrupting(transcript_path, ruling, _, _):
return ask(cycle, transcript_path, ruling)
case Interrupting(transcript_path, ruling, _, stepped_from):
return ask(cycle, transcript_path, ruling, stepped_from)
case Closing(transcript_path, verdict):
return close(cycle, transcript_path, verdict)
case _:
@@ -132,8 +132,8 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle))
def worker_session(cycle: Cycle, transcript_path: str, stepped_from: Rung | None) -> WorkerSession:
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, stepped_from or cycle.route.rung, transcript_path, worker_environment(cycle))
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
@@ -164,7 +164,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
stepped = ruling_step_up(cycle, verdict)
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped, verdict.judged.run):
return Stop(1, failure.reason)
return Ruled(verdict, stepped.after if stepped else None)
return Ruled(verdict, stepped)
def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: Judged) -> outcomes.Annotation | Failure:
@@ -193,10 +193,10 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
return None
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, stepped_from: Rung | None) -> HumanTyped | HumanTalked | Stop:
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript. stepped_from is the rung the worker ran on, where the ruling stepped it up."""
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.window, cycle.effects)
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path, stepped_from), cycle.window, cycle.effects)
match answer:
case Stop():
return answer
+12 -11
View File
@@ -1,7 +1,8 @@
import dataclasses
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from model_routing.route import Route
from model_routing.ladder import Rung
from loop_claude.routing import StepUp
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from the premises or the records.
QUOTED_ANSWERS_PER_CYCLE = 3
@@ -36,8 +37,8 @@ class Interrupting:
transcript_path: str
ruling: Interrupt | QuotedAnswer
quoted_answers: int = 0
# Whether the ruling stepped the worker up a rung. It holds through the answer the human types, and drops on /talk.
stepped: bool = False
# The rung the worker ran on, where the ruling stepped it up from there; None where the rung holds. It holds through the answer the human types, and drops on /talk.
stepped_from: Rung | None = None
@dataclasses.dataclass(frozen=True)
@@ -63,8 +64,8 @@ class WorkerRan:
@dataclasses.dataclass(frozen=True)
class Ruled:
verdict: Verdict
# The route an interrupt's or a quoted answer's escalation stepped the worker up to, which the cycle runs on from here; None where the route holds, and always for a finished or unfinished verdict.
stepped_to: Route | None = None
# The step-up an interrupt's or a quoted answer's escalation made, whose `after` the cycle runs on from here; None where the route holds, and always for a finished or unfinished verdict.
stepped: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -94,14 +95,14 @@ def transition(state: State, event: Event) -> State:
match state, event:
case Working(_, quoted_answers), WorkerRan(transcript_path):
return Judging(transcript_path, quoted_answers)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling, stepped_to) if to_the_human(ruling, quoted_answers):
return Interrupting(transcript_path, ruling, quoted_answers, stepped_to is not None)
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, stepped_to):
return Working(answered, quoted_answers + 1, stepped_to is not None)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling, stepped) if to_the_human(ruling, quoted_answers):
return Interrupting(transcript_path, ruling, quoted_answers, stepped.before.rung if stepped else None)
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, stepped):
return Working(answered, quoted_answers + 1, stepped is not None)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
case Interrupting(_, _, quoted_answers, stepped), HumanTyped(typed):
return Working(typed, quoted_answers, stepped)
case Interrupting(_, _, quoted_answers, stepped_from), HumanTyped(typed):
return Working(typed, quoted_answers, stepped_from is not None)
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
case Interrupting(transcript_path, _, quoted_answers), HumanTalked():
return Judging(transcript_path, quoted_answers)
+5
View File
@@ -17,6 +17,11 @@ COMPACT_WINDOW = 200_000
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
wait_for_memory(effects)
return run_claude(root, args, env, effects)
def run_claude(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
"""Runs a headless claude at once, printing what it says, and returns how it failed, or None."""
try:
proc = effects.stream_claude(args, root, env)
except OSError as failure: