Merge remote-tracking branch 'origin/main' into item-442
CI / tests (pull_request) Has been cancelled
CI / tests (pull_request) Has been cancelled
# Conflicts: # todo.md
This commit is contained in:
@@ -1,21 +1,30 @@
|
||||
import dataclasses
|
||||
import datetime
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry
|
||||
from agent_cycle.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from claude_code.reply import Limited
|
||||
from agent_cycle.stop import needs_human, needs_terminal, Stop
|
||||
from agent_cycle.worker import run_claude
|
||||
from model_routing.ladder import Rung
|
||||
from agent_cycle.direct_message import tell
|
||||
from agent_cycle import tmux
|
||||
from claude_code.tokens import tokens_of
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK, what the human types at the entry point's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
# While the human hasn't answered, the worker's session is compacted CACHE_MARGIN seconds before its hour-long prompt cache expires: compacting reads the context from the cache, while resuming after it expired writes the whole context again. Below COMPACT_FLOOR tokens of context, that write costs less than compacting. A five-minute cache expires within the margin, so a session that last wrote one isn't compacted. lilleman chose this on 2026-11-11.
|
||||
HOUR_CACHE = 3600
|
||||
CACHE_MARGIN = 600
|
||||
COMPACT_FLOOR = 60_000
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -24,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]
|
||||
@@ -57,12 +68,57 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, window:
|
||||
|
||||
def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""The human's answer, as interrupt returns it."""
|
||||
answer = typed_answer(effects) if answer_here else TALK
|
||||
answer = waited_answer(session, effects) if answer_here else TALK
|
||||
if answer != TALK:
|
||||
return answer
|
||||
return human_typed(session.transcript_path, lambda: claude_open(session, effects)) or Talked()
|
||||
|
||||
|
||||
def waited_answer(session: WorkerSession, effects: Effects) -> str | Stop:
|
||||
"""typed_answer, compacting the worker's session where no answer has come by CACHE_MARGIN seconds before its prompt cache expires. /talk needs no compaction: the claude it opens compacts an idle session itself."""
|
||||
entries = read_transcript(session.transcript_path)
|
||||
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, now + delay + CACHE_MARGIN, effects))
|
||||
try:
|
||||
return typed_answer(effects)
|
||||
finally:
|
||||
# Waits for a compaction under way, so the worker doesn't resume the session while it is compacted.
|
||||
stop_timer()
|
||||
|
||||
|
||||
def compaction_delay(entries: list[Entry], now: float) -> float | None:
|
||||
"""Seconds from now until CACHE_MARGIN before the session's prompt cache expires. None where its context is under COMPACT_FLOOR tokens, its cache lasts five minutes, or the margin has begun."""
|
||||
turns = [entry for entry in entries if isinstance(entry, AssistantTurn) and entry.usage]
|
||||
if not turns or tokens_of(turns[-1].usage).context() < COMPACT_FLOOR:
|
||||
return None
|
||||
# A read refreshes the cache for the lifetime it was written with.
|
||||
written = next((tokens for turn in reversed(turns) if (tokens := tokens_of(turn.usage)).write_5m or tokens.write_1h), None)
|
||||
if written is None or not written.write_1h:
|
||||
return None
|
||||
try:
|
||||
last_read = datetime.datetime.fromisoformat(turns[-1].timestamp).timestamp()
|
||||
except ValueError:
|
||||
return None
|
||||
delay = last_read + HOUR_CACHE - CACHE_MARGIN - now
|
||||
return delay if delay > 0 else None
|
||||
|
||||
|
||||
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("\ncompacted the worker's claude session", effects)
|
||||
else:
|
||||
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:
|
||||
"""The line typed at the entry point's terminal, stripped. A Stop where they type no answer, or the input ends."""
|
||||
try:
|
||||
|
||||
+10
-10
@@ -75,8 +75,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")
|
||||
@@ -110,8 +110,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 _:
|
||||
@@ -133,8 +133,8 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW), BASH_CEILING: str(BASH_CEILING_CHARACTERS)}
|
||||
|
||||
|
||||
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]:
|
||||
@@ -175,7 +175,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:
|
||||
@@ -204,10 +204,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(cycle, ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.window, cycle.prompts.driver, cycle.effects)
|
||||
answer = interrupt(question_for(cycle, ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path, stepped_from), cycle.window, cycle.prompts.driver, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
|
||||
+12
-11
@@ -1,7 +1,8 @@
|
||||
import dataclasses
|
||||
|
||||
from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
from agent_cycle.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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -13,6 +13,10 @@ class Tokens:
|
||||
read: int = 0
|
||||
output: int = 0
|
||||
|
||||
def context(self) -> int:
|
||||
"""The tokens of the prompt the message answered: its context."""
|
||||
return self.input + self.write_5m + self.write_1h + self.read
|
||||
|
||||
def plus(self, other: "Tokens") -> "Tokens":
|
||||
return Tokens(*(mine + theirs for mine, theirs in zip(dataclasses.astuple(self), dataclasses.astuple(other))))
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
@@ -342,7 +342,7 @@ class JudgeArchivedRuns(unittest.TestCase):
|
||||
cwds.append(cwd)
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
grounds = grounds_of(prompt, self.ENTRIES)
|
||||
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, DRIVER, effects)), cwds
|
||||
|
||||
|
||||
@@ -64,7 +64,10 @@ config sets notifier, loop-claude also sends the human each question, naming its
|
||||
<session>:<window>, each release ready to cut and each stop as a DM, as bin/notify sends it. Four
|
||||
stops are left out: Ctrl-C, printing this help, the loop-claude that started the windows once it
|
||||
attaches or prints how to, and a loop whose chunk finished once it started the next chunks. A DM
|
||||
that fails is said on stderr, and the loop goes on.
|
||||
that fails is said on stderr, and the loop goes on. Where no answer has come 10 minutes before the
|
||||
worker's hour-long prompt cache expires, and the worker's context holds at least 60k tokens,
|
||||
loop-claude compacts the worker's session with `claude -p /compact` and keeps waiting, so the resume
|
||||
doesn't write the whole context again.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree, adding
|
||||
--item <ID> in a window named for an item, and quotes what it prints in the first prompt
|
||||
|
||||
@@ -117,8 +117,11 @@ class FakeEffects:
|
||||
self.free_memory = list(free_memory)
|
||||
self.terminal = on_terminal
|
||||
self.worker_environments = []
|
||||
self.worker_folders = []
|
||||
self.terminal_environments = []
|
||||
self.terminal_folders = []
|
||||
# Each timer started, as its delay and action, which a test runs where the timer fires.
|
||||
self.timers = []
|
||||
|
||||
def effects(self):
|
||||
return Effects(
|
||||
@@ -136,10 +139,15 @@ class FakeEffects:
|
||||
python=lambda args, cwd: self.answer("python", (args, cwd)),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=self.stream,
|
||||
timer=self.timer,
|
||||
tmux=self.tmux,
|
||||
tmux_on_terminal=lambda args: self.tmux(args).returncode,
|
||||
)
|
||||
|
||||
def timer(self, delay, action):
|
||||
self.timers.append((delay, action))
|
||||
return lambda: self.calls.append(("stop_timer", delay))
|
||||
|
||||
def tmux(self, args):
|
||||
self.tmux_calls.append(args)
|
||||
if args[0] == "list-windows":
|
||||
@@ -162,6 +170,7 @@ class FakeEffects:
|
||||
|
||||
def stream(self, args, cwd, env):
|
||||
self.worker_environments.append(env)
|
||||
self.worker_folders.append(cwd)
|
||||
return self.answer("stream_claude", args)
|
||||
|
||||
def answer(self, seam, what):
|
||||
@@ -194,13 +203,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"
|
||||
@@ -214,6 +225,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)
|
||||
|
||||
@@ -268,14 +281,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):
|
||||
@@ -648,6 +662,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."])
|
||||
@@ -793,7 +824,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."""
|
||||
@@ -808,6 +839,121 @@ class Interrupts(unittest.TestCase):
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
return 0
|
||||
|
||||
def worked(self, minutes_ago, written_1h=5000, read=70000, written_5m=0):
|
||||
"""Appends the worker's last message, sent minutes_ago before NOW, whose usage wrote written_1h tokens to the hour-long cache, written_5m to the five-minute one, and read read tokens from the cache."""
|
||||
said = assistant({"type": "text", "text": "Which one?"})
|
||||
said["timestamp"] = utc(NOW - minutes_ago * 60)
|
||||
said["message"] |= {"id": "msg-1", "model": "m", "usage": {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": written_5m, "ephemeral_1h_input_tokens": written_1h}, "cache_read_input_tokens": read, "output_tokens": 100}}
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(said) + "\n")
|
||||
|
||||
def fired(self, fake, answer):
|
||||
"""An input that first fires every timer started, then returns answer as the line the human typed."""
|
||||
def typed(prompt):
|
||||
for _, action in fake.timers:
|
||||
action()
|
||||
return answer
|
||||
return typed
|
||||
|
||||
def test_compacts_the_workers_session_ten_minutes_before_its_hour_long_prompt_cache_expires_and_keeps_waiting(self):
|
||||
self.worked(minutes_ago=10)
|
||||
fake = FakeEffects(streams=[Streamed(0)])
|
||||
fake.scripts["input"] = [self.fired(fake, "Use B.")]
|
||||
answer, said = self.put(fake)
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertEqual([delay for delay, _ in fake.timers], [40 * 60])
|
||||
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"\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_doesnt_compact_anything(self):
|
||||
self.worked(minutes_ago=10)
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
self.assertEqual(self.put(fake)[0], "Use B.")
|
||||
self.assertEqual([call for call in fake.calls if call[0] in ("stop_timer", "stream_claude")], [("stop_timer", 40 * 60)])
|
||||
|
||||
def test_stops_the_timer_before_talk_opens_the_workers_session(self):
|
||||
self.worked(minutes_ago=10)
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[self.typed_there])
|
||||
self.assertEqual(self.put(fake)[0], interrupt.Talked())
|
||||
self.assertEqual([call[0] for call in fake.calls if call[0] in ("stop_timer", "claude_on_terminal")], ["stop_timer", "claude_on_terminal"])
|
||||
|
||||
def test_starts_no_timer_under_60k_tokens_of_context_past_the_margin_on_a_five_minute_cache_or_where_claude_opens_at_once(self):
|
||||
for name, minutes_ago, written_1h, written_5m, read, answer_here in (("small", 10, 5000, 0, 54997, True), ("margin begun", 50, 5000, 0, 70000, True), ("five minutes", 1, 0, 5000, 70000, True), ("nothing written", 1, 0, 0, 70000, True), ("opens at once", 10, 5000, 0, 70000, False)):
|
||||
with self.subTest(name):
|
||||
self.transcript.write_text(json.dumps(human("a")) + "\n")
|
||||
self.worked(minutes_ago, written_1h, read, written_5m)
|
||||
fake = FakeEffects(inputs=["Use B."], on_terminal_claude=[self.typed_there])
|
||||
self.put(fake, answer_here=answer_here)
|
||||
self.assertEqual(fake.timers, [])
|
||||
|
||||
def test_starts_the_timer_at_60k_tokens_of_context(self):
|
||||
self.worked(minutes_ago=10, read=54998)
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
self.put(fake)
|
||||
self.assertEqual([delay for delay, _ in fake.timers], [40 * 60])
|
||||
|
||||
def test_starts_no_timer_where_the_transcript_cannot_be_read_and_still_asks(self):
|
||||
self.transcript.unlink()
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
self.assertEqual(self.put(fake)[0], "Use B.")
|
||||
self.assertEqual(fake.timers, [])
|
||||
|
||||
def test_a_compaction_that_hits_a_usage_limit_says_the_limits_message_and_keeps_waiting(self):
|
||||
self.worked(minutes_ago=10)
|
||||
fake = FakeEffects(streams=[Streamed(0, {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"})])
|
||||
fake.scripts["input"] = [self.fired(fake, "Use B.")]
|
||||
answer, said = self.put(fake)
|
||||
self.assertEqual(answer, "Use B.")
|
||||
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)
|
||||
fake = FakeEffects(streams=[Streamed(1)])
|
||||
fake.scripts["input"] = [self.fired(fake, "Use B.")]
|
||||
answer, said = self.put(fake)
|
||||
self.assertEqual(answer, "Use B.")
|
||||
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)
|
||||
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n"))
|
||||
@@ -2006,6 +2152,9 @@ class Spend(unittest.TestCase):
|
||||
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0))
|
||||
self.assertEqual(tokens_of(None), Tokens())
|
||||
|
||||
def test_counts_a_messages_context_as_every_prompt_token_and_no_output(self):
|
||||
self.assertEqual(Tokens(1, 2, 3, 4, 5).context(), 10)
|
||||
|
||||
def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self):
|
||||
thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)]
|
||||
self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)})
|
||||
|
||||
@@ -9,6 +9,7 @@ import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import threading
|
||||
import time
|
||||
import typing
|
||||
|
||||
@@ -51,6 +52,8 @@ class Effects:
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming]
|
||||
# Starts a timer, as start_timer does.
|
||||
timer: typing.Callable[[float, typing.Callable[[], None]], typing.Callable[[], None]]
|
||||
# Runs tmux with these arguments, as run_tmux does.
|
||||
tmux: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
# Runs tmux on the terminal, as to attach a session, and returns its exit code once the human detaches.
|
||||
@@ -86,6 +89,7 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
timer=start_timer,
|
||||
tmux=run_tmux,
|
||||
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode,
|
||||
)
|
||||
@@ -112,6 +116,19 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def start_timer(delay: float, action: typing.Callable[[], None]) -> typing.Callable[[], None]:
|
||||
"""Runs action on a thread of its own once delay seconds have passed, and returns what stops the timer: it cancels an action not yet started, and waits for one that has started to end."""
|
||||
timer = threading.Timer(delay, action)
|
||||
# A timer still running doesn't keep the process alive once the loop exits.
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
|
||||
def stop() -> None:
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
return stop
|
||||
|
||||
|
||||
def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
|
||||
command = ["tmux", *args]
|
||||
|
||||
@@ -6,13 +6,14 @@ import pathlib
|
||||
import signal
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_effects.effects import run_python, say, system_effects
|
||||
from loop_effects.effects import run_python, say, start_timer, system_effects
|
||||
|
||||
NOW = 1790000000
|
||||
# How a line said at NOW opens, with clocked's local_time.
|
||||
@@ -134,3 +135,35 @@ class PythonEffect(unittest.TestCase):
|
||||
done = run_python(["-c", "pass"], gone, 60)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn(gone, done.stderr)
|
||||
|
||||
|
||||
class Timer(unittest.TestCase):
|
||||
def test_runs_the_action_beside_the_caller_once_the_delay_has_passed(self):
|
||||
ran = threading.Event()
|
||||
start_timer(0.05, ran.set)
|
||||
self.assertTrue(ran.wait(10))
|
||||
|
||||
def test_the_systems_timer_runs_on_a_daemon_thread_so_a_loop_that_exits_while_it_waits_does_not_wait_for_it(self):
|
||||
self.assertIs(system_effects().timer, start_timer)
|
||||
before = set(threading.enumerate())
|
||||
stop = start_timer(60, lambda: None)
|
||||
self.addCleanup(stop)
|
||||
self.assertEqual([thread.daemon for thread in set(threading.enumerate()) - before], [True])
|
||||
|
||||
def test_a_timer_stopped_before_its_delay_has_passed_never_runs_the_action(self):
|
||||
ran = threading.Event()
|
||||
# stop returns once the timer's thread has ended, so the action cannot run later.
|
||||
start_timer(0.2, ran.set)()
|
||||
self.assertFalse(ran.is_set())
|
||||
|
||||
def test_stopping_a_timer_whose_action_runs_waits_for_the_action_to_end(self):
|
||||
started, ended = threading.Event(), threading.Event()
|
||||
|
||||
def action():
|
||||
started.set()
|
||||
time.sleep(0.2)
|
||||
ended.set()
|
||||
stop = start_timer(0, action)
|
||||
self.assertTrue(started.wait(10))
|
||||
stop()
|
||||
self.assertTrue(ended.is_set())
|
||||
|
||||
@@ -270,7 +270,7 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, env, self.home, effects)
|
||||
|
||||
Reference in New Issue
Block a user