diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 33281be5..f2db7e23 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -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: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index e5cfed01..6e8f2ea3 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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 diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 78a7e328..cf24478f 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -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) diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 2ca284fd..6613a4e0 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -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: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 934da642..8124a097 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -195,13 +195,15 @@ def judged(verdict, evidence="working", answer="", escalation="", release_ready= class Worker: """A worker claude: writes a line to the session's transcript, then streams a result.""" - def __init__(self, home, prompted=False, text="working", usage=None): + def __init__(self, home, prompted=False, text="working", usage=None, sent=None): self.home = home # Whether it records its -p prompt in the transcript first, as claude does. self.prompted = prompted self.text = text # The usage its message records, twice as Claude Code writes a message of two blocks; none where None. self.usage = usage + # The time its message records, as utc() writes it; none where None. + self.sent = sent def __call__(self, args): flag = "--session-id" if "--session-id" in args else "--resume" @@ -215,6 +217,8 @@ class Worker: said = assistant({"type": "text", "text": self.text}) if self.usage is not None: said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage} + if self.sent is not None: + said["timestamp"] = self.sent handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2)) return Streamed(0) @@ -269,14 +273,15 @@ class Transitions(unittest.TestCase): states.transition(state, event) def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self): - stepped_to = Route(Rung("claude-fable-5-2", "low"), escalated_at=3) + ran_on = Rung("claude-opus-5-5", "xhigh") + stepped = routing.StepUp(Route(ran_on), Route(Rung("claude-fable-5-2", "low"), escalated_at=3)) interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴") for state, event, after in ( - (states.Judging("/t"), states.Ruled(quoted, stepped_to), states.Working(quoted, 1, True)), - (states.Judging("/t", 3), states.Ruled(quoted, stepped_to), states.Interrupting("/t", quoted, 3, True)), - (states.Judging("/t"), states.Ruled(interrupt, stepped_to), states.Interrupting("/t", interrupt, 0, True)), - (states.Interrupting("/t", interrupt, 0, True), states.HumanTyped(TYPED), states.Working(TYPED, 0, True)), - (states.Interrupting("/t", interrupt, 0, True), states.HumanTalked(), states.Judging("/t")), + (states.Judging("/t"), states.Ruled(quoted, stepped), states.Working(quoted, 1, True)), + (states.Judging("/t", 3), states.Ruled(quoted, stepped), states.Interrupting("/t", quoted, 3, ran_on)), + (states.Judging("/t"), states.Ruled(interrupt, stepped), states.Interrupting("/t", interrupt, 0, ran_on)), + (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTyped(TYPED), states.Working(TYPED, 0, True)), + (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTalked(), states.Judging("/t")), (states.Working(TYPED, 0, True), states.WorkerRan("/t"), states.Judging("/t")), ): with self.subTest(state=state, event=event): @@ -647,6 +652,23 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 179's E + I of 5 picks.", typed) self.assertNotIn("went through", first[first.index("-p") + 1]) + def test_an_interrupt_that_steps_the_worker_up_compacts_its_session_on_the_rung_it_ran_on(self): + usage = {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 5000}, "cache_read_input_tokens": 70000, "output_tokens": 100} + worker = Worker(self.paths.claude_code_transcripts.parent, usage=usage, sent=utc(NOW - 600)) + fake = FakeEffects(streams=[worker, Streamed(0), worker], claude=[judged("interrupt", escalation="working"), judged("finished")]) + + def typed(prompt): + for _, action in fake.timers: + action() + return "Use B." + fake.scripts["input"] = [typed] + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) + with contextlib.redirect_stderr(io.StringIO()): + run.run_cycle(cycle) + _, compaction, resumed = fake.made("stream_claude") + self.assertEqual(compaction[compaction.index("-p") + 1], "/compact") + self.assertEqual([(args[args.index("--model") + 1], args[args.index("--effort") + 1]) for args in (compaction, resumed)], [("claude-sonnet-5-5", "high"), ("claude-opus-5-5", "medium")]) + def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self): worker = Worker(self.paths.claude_code_transcripts.parent) fake = FakeEffects(streams=[worker] * 5, claude=[judged("quoted", answer="Use A.")] * 4 + [judged("finished")], inputs=["Use B."]) @@ -792,7 +814,7 @@ class Interrupts(unittest.TestCase): self.paths = paths.paths_from(self.home) self.transcript = self.home / "t.jsonl" self.transcript.write_text(json.dumps(human("a")) + "\n") - self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) + self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) def put(self, fake, answer_here=True, effects=None, question="Which one?"): """interrupt's answer and what it said, without the bell it rang, which self.bells counts.""" @@ -833,7 +855,45 @@ class Interrupts(unittest.TestCase): self.assertEqual([what for seam, what in fake.calls if seam == "stream_claude"], [["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "-p", "/compact", "--resume", str(self.session.id), "--output-format", "stream-json", "--verbose"]]) self.assertEqual(fake.worker_environments, [self.session.env]) self.assertEqual(fake.worker_folders, [self.session.root]) - self.assertIn(f"{STAMP} compacted the worker's claude session before its prompt cache expires; still waiting for an answer\n", said) + self.assertIn(f"\n{STAMP} compacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends\n\n{STAMP} compacted the worker's claude session\n", said) + self.assertNotIn("still waiting", said) + + def test_compacts_on_the_rung_the_worker_ran_on_where_a_ruling_stepped_it_up_and_talk_opens_claude_on_the_new_rung(self): + self.worked(minutes_ago=10) + self.session = dataclasses.replace(self.session, rung=Rung("n", "medium")) + fake = FakeEffects(streams=[Streamed(0)], on_terminal_claude=[self.typed_there]) + fake.scripts["input"] = [self.fired(fake, "/talk")] + self.assertEqual(self.put(fake)[0], interrupt.Talked()) + (compaction,), (opened,) = fake.made("stream_claude"), fake.made("claude_on_terminal") + self.assertEqual(compaction[:4], ["--model", "m", "--effort", "high"]) + self.assertEqual(opened[:4], ["--model", "n", "--effort", "medium"]) + + def test_compacts_until_the_prompt_cache_expires_and_not_from_then_on(self): + for name, late, compactions in (("a second before", 50 * 60 - 1, 1), ("as it expires", 50 * 60, 0)): + with self.subTest(name): + self.transcript.write_text(json.dumps(human("a")) + "\n") + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0)]) + clock = [NOW] + + def typed(prompt): + clock[0] = NOW + late + for _, action in fake.timers: + action() + return "Use B." + fake.scripts["input"] = [typed] + answer, said = self.put(fake, effects=dataclasses.replace(fake.effects(), now=lambda: clock[0])) + self.assertEqual(answer, "Use B.") + self.assertEqual(len(fake.made("stream_claude")), compactions) + self.assertEqual(said.count("compact"), 2 * compactions, said) + + def test_a_compaction_doesnt_wait_for_memory(self): + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0)], free_memory=[memory.Memory(available=3, total=16)]) + fake.scripts["input"] = [self.fired(fake, "Use B.")] + said = self.put(fake)[1] + self.assertEqual([seam for seam, _ in fake.calls if seam in ("memory", "sleep", "stream_claude")], ["stream_claude"]) + self.assertNotIn("waiting to start the worker", said) def test_an_answer_before_the_timer_fires_stops_it_and_compacts_nothing(self): self.worked(minutes_ago=10) @@ -874,7 +934,7 @@ class Interrupts(unittest.TestCase): fake.scripts["input"] = [self.fired(fake, "Use B.")] answer, said = self.put(fake) self.assertEqual(answer, "Use B.") - self.assertIn(f"{STAMP} could not compact the worker's claude session: You've hit your session limit; still waiting for an answer\n", said) + self.assertIn(f"\n{STAMP} could not compact the worker's claude session: You've hit your session limit\n", said) def test_a_compaction_that_fails_says_why_and_keeps_waiting(self): self.worked(minutes_ago=10) @@ -882,7 +942,7 @@ class Interrupts(unittest.TestCase): fake.scripts["input"] = [self.fired(fake, "Use B.")] answer, said = self.put(fake) self.assertEqual(answer, "Use B.") - self.assertIn(f"{STAMP} could not compact the worker's claude session: claude exited 1; still waiting for an answer\n", said) + self.assertIn(f"\n{STAMP} could not compact the worker's claude session: claude exited 1\n", said) def test_stops_off_a_terminal_before_asking(self): fake = FakeEffects(on_terminal=False)