Answer architecture round 1: 0 🔴, 36 🟡 (0 misread); chunk_driver holds what both drivers share, and Jira and review-state reads have one home each
CI / tests (pull_request) Successful in 5m11s
CI / tests (pull_request) Successful in 5m11s
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""One cycle of a headless claude worker and the judge of its transcript, for every entry point that drives such cycles: loop-claude today, do-epic next (docs/decisions.md → `do-epic: drives one Jira epic …`).
|
||||
"""One cycle of a headless claude worker and the judge of its transcript, for every entry point that drives such cycles: loop-claude and do-epic (docs/decisions.md → `do-epic: drives one Jira epic …`).
|
||||
|
||||
run.py runs a cycle through the states in states.py: worker.py runs the worker, judge.py rules on its transcript, interrupt.py puts a question to the human in the tmux window tmux.py names, and routing.py picks the rung the worker runs on next. An entry point hands the cycle what is its own: its prompts and file names (worker_prompts.py) and how it reads the plan items a worker took in (run.py's Cycle.taken_in). No module here imports an entry point's package: loop_claude imports this one, so bin/repo_checks/test_package_cycles.py fails on such an import. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
|
||||
run.py runs a cycle through the states in states.py: worker.py runs the worker, judge.py rules on its transcript, interrupt.py puts a question to the human in the tmux window tmux.py names, and routing.py picks the rung the worker runs on next. An entry point hands the cycle what is its own: its prompts and file names (worker_prompts.py) and how it reads the plan items a worker took in (run.py's Cycle.taken_in). What two entry points share beyond the cycle lives in bin/chunk_driver/. No module here imports an entry point's package, and bin/repo_checks/test_package_cycles.py fails on such an import. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
|
||||
"""
|
||||
|
||||
@@ -34,7 +34,7 @@ class Cycle:
|
||||
|
||||
Each step reads the few fields it needs by name, so the fields stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows more than seven where a reader finds them by name.
|
||||
"""
|
||||
# The claude-config release and commit the cycle runs under, such as `v0.8.0 (<sha>)`, or why they are unknown: loop/main.py's setup_version.
|
||||
# The claude-config release and commit the cycle runs under, such as `v0.8.0 (<sha>)`, or why they are unknown: chunk_driver/cycle_start.py's setup_version.
|
||||
config: str
|
||||
effects: Effects
|
||||
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_effects.test_doubles import assistant, FakeEffects, human, NOW, STAMP, Streamed
|
||||
from failure import Failure
|
||||
from agent_cycle import interrupt
|
||||
from chunk_driver.drivers import LOOP_CLAUDE
|
||||
from machine_load import memory
|
||||
from loop_state import paths
|
||||
from model_routing.ladder import Rung
|
||||
from agent_cycle.stop import Stop
|
||||
from agent_cycle import tmux
|
||||
from text_files.utc_stamp import utc
|
||||
from agent_cycle.test_tmux import WINDOW
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
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"), 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."""
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, LOOP_CLAUDE, effects or fake.effects())
|
||||
self.bells = said.getvalue().count(tmux.BELL)
|
||||
return answer, said.getvalue().replace(tmux.BELL, "")
|
||||
|
||||
def typed_there(self, args):
|
||||
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
|
||||
with open(self.transcript, "a") as handle:
|
||||
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"))
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self):
|
||||
for on_terminal in (True, False):
|
||||
with self.subTest(on_terminal=on_terminal):
|
||||
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"])
|
||||
|
||||
def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self):
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
answer, said = self.put(fake)
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertEqual(self.bells, 1)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]])
|
||||
|
||||
def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]])
|
||||
|
||||
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
seen = []
|
||||
effects = dataclasses.replace(fake.effects(), dm=lambda text, directory: seen.append(list(fake.calls)))
|
||||
self.assertEqual(self.put(fake, effects=effects)[0], "Use B.")
|
||||
self.assertEqual(seen, [[("discard_typed", None)]])
|
||||
|
||||
def test_says_why_a_dm_failed_and_still_takes_the_answer(self):
|
||||
fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")])
|
||||
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n"))
|
||||
|
||||
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
|
||||
fake = FakeEffects(inputs=[" Use B. "])
|
||||
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n"))
|
||||
self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")])
|
||||
|
||||
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there])
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked())
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
def test_stops_on_an_empty_answer_or_the_inputs_end(self):
|
||||
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
|
||||
with self.subTest(why=why):
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}"))
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0])
|
||||
stop, _ = self.put(fake)
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0])
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort", "CLAUDE_CODE_SANDBOXED": "1"}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,130 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_effects.test_doubles import assistant, FakeEffects, human, judged, kinds
|
||||
from failure import Failure
|
||||
from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from agent_cycle import judge
|
||||
from chunk_driver.drivers import LOOP_CLAUDE
|
||||
from chunk_driver import prompts
|
||||
from chunk_driver.project import records
|
||||
from model_routing.ladder import Rung
|
||||
from agent_cycle.judge import verdict_from
|
||||
|
||||
|
||||
class Grounded(unittest.TestCase):
|
||||
def test_every_verdict_must_quote_the_transcript(self):
|
||||
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
|
||||
self.assertFalse(judge.grounded("invented", "the transcript"))
|
||||
self.assertFalse(judge.grounded("", "the transcript"))
|
||||
self.assertFalse(judge.grounded(" ", "the transcript"))
|
||||
transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it."
|
||||
self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript))
|
||||
self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript))
|
||||
self.assertFalse(judge.grounded("**", transcript))
|
||||
|
||||
def test_an_elided_quote_holds_when_its_fragments_appear_in_order(self):
|
||||
transcript = "**Decision for you:** security, or not.\n\nI recommend one more round of each.\n\nI recommend skipping it: it costs."
|
||||
self.assertTrue(judge.grounded("**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …", transcript))
|
||||
self.assertFalse(judge.grounded("I recommend skipping it ... Decision for you", transcript))
|
||||
self.assertFalse(judge.grounded("Decision for you ... invented", transcript))
|
||||
self.assertFalse(judge.grounded("... …", transcript))
|
||||
self.assertTrue(judge.grounded("a ... b ... c", "x a b a c"))
|
||||
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "reversed": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
def test_carries_the_earlier_answer_an_interrupt_names(self):
|
||||
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?", "reversed": ""}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more"))
|
||||
self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
|
||||
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_interrupt(self):
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
|
||||
shown = "The agent: round 2: 🔴. Which one?"
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q"))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
|
||||
|
||||
def test_turns_an_interrupt_that_re_asks_a_human_answer_into_that_answer_quoted_back(self):
|
||||
answer = "Grant one more round; ask again if a 🔴 survives it."
|
||||
shown = f"[loop] Asked.\n\n[human] {answer}\n\n[step] Round 2: a 🔴 survived."
|
||||
grounds = judge.Grounds(shown, shown, "")
|
||||
asking = "Grant a third round? Your answer left open: a 🔴 survives it"
|
||||
kept = Interrupt("[step] Round 2", asking, answered_before=answer, left_open="a 🔴 survives it")
|
||||
self.assertEqual(judge.quotes_checked(kept, grounds), kept)
|
||||
re_asked = Interrupt("[step] Round 2", "Grant a third round?", "Round 2: a 🔴", answered_before=answer, left_open="a 🔴 survives it")
|
||||
self.assertEqual(judge.quotes_checked(re_asked, grounds), Unfinished(answer, "Round 2: a 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open=""), grounds), Unfinished(answer))
|
||||
self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open="a 🔴 survived"), grounds), Unfinished(answer))
|
||||
invented = dataclasses.replace(re_asked, answered_before="Grant two more rounds.")
|
||||
self.assertEqual(judge.quotes_checked(invented, grounds), invented)
|
||||
unnamed = Interrupt("[step] Round 2", "Grant a third round?")
|
||||
self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed)
|
||||
|
||||
def test_takes_an_escalation_quote_on_a_quoted_answer(self):
|
||||
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
|
||||
shown = "The agent: round 2: 🔴. Which one?"
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.", "round 2: 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A."))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴"), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴"))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("s", "q"))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("s", "q", "the records"))
|
||||
|
||||
def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})]
|
||||
def judged_on(mark, escalation):
|
||||
return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), mark, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects())
|
||||
self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", "round 2: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", "round 3: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
|
||||
def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})]
|
||||
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects())
|
||||
self.assertEqual(verdict, Unfinished("working", entries_read=4))
|
||||
|
||||
def test_takes_evidence_from_before_the_workers_last_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})]
|
||||
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
|
||||
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,51 @@
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from loop_effects.test_doubles import FakeEffects, NOW, STAMP
|
||||
from claude_code.reply import Limited
|
||||
from agent_cycle import retry
|
||||
from agent_cycle.stop import Stop
|
||||
|
||||
|
||||
class Retried(unittest.TestCase):
|
||||
def test_retries_a_minute_apart_and_stops_on_the_third_failure(self):
|
||||
fake = FakeEffects()
|
||||
results = [Failure("one"), "done"]
|
||||
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done")
|
||||
self.assertEqual(fake.calls, [("sleep", 60)])
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
|
||||
|
||||
def test_hands_each_failure_to_the_keeper_and_stops_where_it_stops(self):
|
||||
kept = []
|
||||
def keep(failure):
|
||||
kept.append(failure)
|
||||
return Stop(1, "no room") if len(kept) == 2 else None
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects(), keep), Stop(1, "no room"))
|
||||
self.assertEqual(kept, [Failure("no")] * 2)
|
||||
self.assertEqual(fake.calls, [("sleep", 60)])
|
||||
|
||||
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
|
||||
fake = FakeEffects()
|
||||
results = [Failure("one"), Failure("two"), Limited(NOW + 3600, "limit"), Failure("three"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("four"), Failure("five"), Failure("six")]
|
||||
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: six"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600), ("sleep", 60), ("sleep", 60)])
|
||||
|
||||
def test_says_what_claude_said_and_when_the_next_try_is_due(self):
|
||||
results = [Limited(NOW + 3600, "You've hit your session limit"), "done"]
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
retry.retried("judge", lambda: results.pop(0), FakeEffects().effects())
|
||||
self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,90 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code import entries
|
||||
from loop_effects.test_doubles import FakeEffects, judged, ran
|
||||
from agent_cycle import judge, spend
|
||||
from agent_cycle.verdicts import Judged, Unfinished
|
||||
from transcript_archive import outcomes
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
|
||||
|
||||
def turn(message_id, model, at, **usage):
|
||||
return entries.AssistantTurn(message_id=message_id, model=model, timestamp=at, usage=usage)
|
||||
|
||||
|
||||
class Spend(unittest.TestCase):
|
||||
def test_reads_the_cache_writes_by_lifetime_and_counts_one_without_the_split_as_five_minutes(self):
|
||||
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}), Tokens(1, 2, 3, 4, 5))
|
||||
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)})
|
||||
|
||||
def test_sums_two_subagents_of_one_name_on_one_model(self):
|
||||
helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])]
|
||||
self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)})
|
||||
|
||||
def test_counts_each_message_once_by_its_id_and_only_after_since(self):
|
||||
thread = [
|
||||
turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7),
|
||||
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
|
||||
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
|
||||
turn("m3", "b", "2026-11-01T10:00:03Z", cache_read_input_tokens=5),
|
||||
]
|
||||
self.assertEqual(spend.thread_spend(thread, "2026-11-01T10:00:01Z"), {"a": Tokens(1, 0, 0, 0, 2), "b": Tokens(0, 0, 0, 5, 0)})
|
||||
self.assertEqual(spend.thread_spend(thread, ""), {"a": Tokens(1, 0, 0, 0, 9), "b": Tokens(0, 0, 0, 5, 0)})
|
||||
|
||||
def test_names_each_spender_and_leaves_out_one_that_spent_nothing(self):
|
||||
worker = [turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7)]
|
||||
helper = spend.Subagent('Explore "Search"', [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)])
|
||||
self.assertEqual(spend.spent("", worker, [helper], "j", Tokens()), {("worker", "a"): Tokens(output=7), ('Explore "Search"', "b"): Tokens(input=3)})
|
||||
self.assertEqual(spend.spent("", [], [], "j", Tokens(input=1)), {("judge", "j"): Tokens(input=1)})
|
||||
|
||||
def test_names_a_subagent_by_its_agent_type_and_description(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = pathlib.Path(root, "s", "subagents")
|
||||
folder.mkdir(parents=True)
|
||||
for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]:
|
||||
(folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n")
|
||||
if meta:
|
||||
(folder / f"{name}.meta.json").write_text(json.dumps(meta))
|
||||
found = spend.subagents(str(pathlib.Path(root, "s.jsonl")))
|
||||
self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"])
|
||||
self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)})
|
||||
self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), [])
|
||||
|
||||
def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self):
|
||||
found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)}
|
||||
self.assertEqual(outcomes.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- worker, claude-opus-5-5: 1, 2, 3, 4, 5
|
||||
- judge, unpriced: 6, 0, 0, 0, 0
|
||||
|
||||
List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- claude-opus-5-5: 4, 5, 8, 0.2, 20""")
|
||||
self.assertEqual(outcomes.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0")
|
||||
self.assertEqual(outcomes.spent_block("", {}), "")
|
||||
|
||||
def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self):
|
||||
shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name"
|
||||
typed = ("Use A.", "No, keep the old name. Use X.")
|
||||
for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]:
|
||||
with self.subTest(quoted=quoted):
|
||||
answer = json.loads(judged("unfinished", reversed=quoted).stdout)
|
||||
fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from model_routing.route import Route
|
||||
from agent_cycle import routing
|
||||
from model_routing.ladder import Rung
|
||||
from agent_cycle import states
|
||||
|
||||
|
||||
TYPED = states.TypedAnswer("Which one?", "Use B.")
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
def test_each_state_moves_on_its_events_and_only_on_them(self):
|
||||
answered = states.Ruled(QuotedAnswer("e", "Which one?", "A."))
|
||||
legal = (
|
||||
(states.Working(), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
(states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)),
|
||||
(states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)),
|
||||
(states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)),
|
||||
(states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)),
|
||||
(states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))),
|
||||
(states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))),
|
||||
)
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
|
||||
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):
|
||||
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), 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):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,7 +6,7 @@ import pathlib
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from loop_claude.test_loop_claude import FakeEffects, NOW, ran, Streamed
|
||||
from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed
|
||||
from model_routing.ladder import Rung
|
||||
from loop_effects.child_shells import Shell
|
||||
from agent_cycle import stuck_workers, worker
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from loop_effects.test_doubles import FakeEffects
|
||||
from chunk_driver.drivers import LOOP_CLAUDE
|
||||
from agent_cycle import tmux
|
||||
|
||||
|
||||
WINDOW = tmux.Window("loop-proj", "item-7", "%4")
|
||||
|
||||
|
||||
class TmuxCommands(unittest.TestCase):
|
||||
def test_refuses_a_tmux_older_than_needed_naming_both_versions(self):
|
||||
for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None),
|
||||
("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"),
|
||||
("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"),
|
||||
("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")):
|
||||
with self.subTest(found=found):
|
||||
fake = FakeEffects(tmux_version=found)
|
||||
self.assertEqual(tmux.unusable(fake.tmux, LOOP_CLAUDE), reason)
|
||||
self.assertEqual(fake.tmux_calls, [["-V"]])
|
||||
|
||||
def test_names_the_session_for_the_project(self):
|
||||
self.assertEqual(tmux.session_name(tmux.LOOP, "claude-config"), "loop-claude-config")
|
||||
# tmux reads `.` and `:` in a target as separators.
|
||||
self.assertEqual(tmux.session_name(tmux.LOOP, "my.site:2 x"), "loop-my-site-2-x")
|
||||
self.assertEqual(tmux.session_name(tmux.LOOP, "Acme/Billing"), "loop-Acme-Billing")
|
||||
|
||||
def test_lists_the_windows_without_the_waiting_mark(self):
|
||||
fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n")
|
||||
self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False, asks=True), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)])
|
||||
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
|
||||
self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), [])
|
||||
failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server")
|
||||
self.assertEqual(tmux.listed("loop-proj", failed), [])
|
||||
|
||||
def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self):
|
||||
fake = FakeEffects()
|
||||
window = tmux.Window("loop-proj", "item-7", "")
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, True, fake.tmux))
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, True, fake.tmux))
|
||||
self.assertEqual(fake.tmux_calls, [
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"],
|
||||
["set-option", "-t", "=loop-proj:", "@loop-root", "/r"],
|
||||
["set-option", "-w", "-t", "@9", "@chunk-root", "/r"],
|
||||
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
|
||||
["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"],
|
||||
["set-option", "-w", "-t", "@9", "@chunk-root", "/r"],
|
||||
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
|
||||
])
|
||||
|
||||
def test_says_why_tmux_started_no_window(self):
|
||||
failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n")
|
||||
silent = lambda args: subprocess.CompletedProcess(args, 2, "", "")
|
||||
window = tmux.Window("loop-proj", "item-7", "")
|
||||
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj"))
|
||||
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2"))
|
||||
|
||||
def test_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self):
|
||||
def answering(failing: str):
|
||||
def run(args):
|
||||
fails = args[:1] == ["set-option"] and failing in args
|
||||
return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "")
|
||||
return run
|
||||
window = tmux.Window("loop-proj", "item-7", "")
|
||||
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session"))
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, True, answering("remain-on-exit")))
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, True, answering(tmux.OWNER)))
|
||||
|
||||
def test_reads_the_checkout_the_session_names(self):
|
||||
fake = FakeEffects(owner="/c/proj")
|
||||
self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj")
|
||||
self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj:", "@loop-root"]])
|
||||
|
||||
def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self):
|
||||
fake = FakeEffects()
|
||||
tmux.mark(WINDOW, True, fake.tmux)
|
||||
tmux.mark(WINDOW, False, fake.tmux)
|
||||
tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]])
|
||||
self.assertEqual(WINDOW.target, "loop-proj:item-7")
|
||||
|
||||
def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self):
|
||||
self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"])
|
||||
self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,135 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code import entries
|
||||
from failure import Failure
|
||||
from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed
|
||||
from agent_cycle import judge, lingering_workers, worker
|
||||
from claude_code.reply import Limited
|
||||
from machine_load import memory
|
||||
from model_routing.ladder import Rung
|
||||
from loop_effects.child_shells import Shell
|
||||
from text_files.utc_stamp import utc
|
||||
|
||||
|
||||
class Limits(unittest.TestCase):
|
||||
def test_the_worker_reports_the_latest_reset_its_stream_names(self):
|
||||
rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)]
|
||||
allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}}
|
||||
limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"}
|
||||
fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)])
|
||||
self.assertEqual(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects()), Limited(NOW + 600, "You've hit your session limit"))
|
||||
|
||||
def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self):
|
||||
def limited(**said):
|
||||
return {"type": "result", "api_error_status": 429, **said}
|
||||
self.assertEqual(worker.worker_outcome(-9, limited(result="limit\n resets 7pm"), []), Limited(None, "limit resets 7pm"))
|
||||
self.assertEqual(worker.worker_outcome(1, limited(result=" \n"), [NOW]), Limited(NOW, "claude gave no message"))
|
||||
self.assertEqual(worker.worker_outcome(0, limited(), []), Limited(None, "claude gave no message"))
|
||||
self.assertEqual(worker.worker_outcome(0, None, [NOW]), Failure("claude exited 0 without a result event"))
|
||||
self.assertIsNone(worker.worker_outcome(0, {"type": "result"}, [NOW]))
|
||||
|
||||
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
|
||||
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
|
||||
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds("", "", ""), fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
|
||||
|
||||
def test_reads_only_a_rejecting_events_whole_seconds(self):
|
||||
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
|
||||
with self.subTest(info=info):
|
||||
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want)
|
||||
|
||||
|
||||
class LingeringWorkers(unittest.TestCase):
|
||||
RESULT = {"type": "result"}
|
||||
|
||||
def worker_with(self, *events, held=()):
|
||||
"""Runs a worker whose claude prints events and holds shells `held`; returns the claude, what loop-claude said and the record's text."""
|
||||
clock = [NOW]
|
||||
streamed = Streamed(0, *events, clock=clock, held=held)
|
||||
fake = FakeEffects(streams=[streamed])
|
||||
effects = dataclasses.replace(fake.effects(), now=lambda: clock[0])
|
||||
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
# The archive folder of a project's first stop doesn't exist yet.
|
||||
archive = pathlib.Path(folder, "transcripts", "project")
|
||||
worker.run_worker("/r", [], {}, archive, Rung("m"), effects)
|
||||
record = archive / lingering_workers.RECORD
|
||||
return streamed, said.getvalue(), record.read_text() if record.exists() else ""
|
||||
|
||||
def shell(self, written=NOW - 1000, runs_busy_tool=False, holds_slot=False):
|
||||
return Shell(pid=7, started=NOW - 1000, command="until false; do sleep 15; done", written=written, runs_busy_tool=runs_busy_tool, holds_slot=holds_slot)
|
||||
|
||||
def test_a_worker_that_lingers_after_its_result_loses_its_quiet_shell_and_the_stop_is_said_and_recorded_in_utc(self):
|
||||
shell = self.shell()
|
||||
streamed, said, record = self.worker_with(self.RESULT, None, held=[shell])
|
||||
self.assertEqual(streamed.stopped, [shell])
|
||||
line = f"stopped shell 7, which held a worker after its final result; it had run 1300 s and written nothing for 1300 s: {shell.command}"
|
||||
self.assertEqual(said, f"<{NOW + 300}> {line}\n")
|
||||
self.assertEqual(record, f"- {utc(NOW + 300)} {line}\n")
|
||||
|
||||
def test_a_worker_keeps_its_shells_where_it_printed_after_its_result_or_printed_none_or_no_check_came_due(self):
|
||||
for events in ((self.RESULT, {"type": "assistant", "message": {"content": []}}, None), (self.RESULT,), (None,), ({"type": "assistant", "message": {"content": []}}, None)):
|
||||
with self.subTest(events=events):
|
||||
streamed, said, record = self.worker_with(*events, held=[self.shell()])
|
||||
self.assertEqual((streamed.stopped, said, record), ([], "", ""))
|
||||
|
||||
def test_a_worker_keeps_every_shell_while_one_of_them_writes_output_runs_a_busy_tool_or_holds_a_heavy_slot(self):
|
||||
for busy in (self.shell(written=NOW + 200), self.shell(runs_busy_tool=True), self.shell(holds_slot=True)):
|
||||
with self.subTest(busy=busy):
|
||||
streamed, _, _ = self.worker_with(self.RESULT, None, held=[self.shell(), busy])
|
||||
self.assertEqual(streamed.stopped, [])
|
||||
|
||||
def test_a_worker_keeps_a_shell_that_wrote_within_the_quiet_time_and_stops_one_that_wrote_before_it(self):
|
||||
# The check comes 300 s after the result, so a shell written at NOW + 300 - QUIET is the latest that is still kept.
|
||||
kept = self.shell(written=NOW + 300 - lingering_workers.QUIET)
|
||||
stopped = self.shell(written=NOW + 300 - lingering_workers.QUIET - 1)
|
||||
self.assertEqual(self.worker_with(self.RESULT, None, held=[kept])[0].stopped, [])
|
||||
self.assertEqual(self.worker_with(self.RESULT, None, held=[stopped])[0].stopped, [stopped])
|
||||
|
||||
def test_a_worker_reads_on_past_a_check_that_found_it_still_working(self):
|
||||
clock = [NOW]
|
||||
effects = dataclasses.replace(FakeEffects(streams=[Streamed(0, None, self.RESULT, clock=clock)]).effects(), now=lambda: clock[0])
|
||||
self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), effects))
|
||||
|
||||
def test_a_stop_that_cannot_be_recorded_is_said_on_stderr_and_every_shell_is_still_stopped(self):
|
||||
clock = [NOW]
|
||||
held = [self.shell(), self.shell()]
|
||||
streamed = Streamed(0, self.RESULT, None, clock=clock, held=held)
|
||||
effects = dataclasses.replace(FakeEffects(streams=[streamed]).effects(), now=lambda: clock[0])
|
||||
with tempfile.NamedTemporaryFile() as blocker, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as failed:
|
||||
worker.run_worker("/r", [], {}, pathlib.Path(blocker.name), Rung("m"), effects)
|
||||
self.assertEqual(streamed.stopped, held)
|
||||
self.assertIn("could not record the stop", failed.getvalue())
|
||||
|
||||
def test_every_stop_of_a_check_is_recorded_though_the_archive_folder_exists_after_the_first(self):
|
||||
held = [self.shell(), self.shell()]
|
||||
_, said, record = self.worker_with(self.RESULT, None, held=held)
|
||||
self.assertEqual(record.count("stopped shell 7"), 2)
|
||||
|
||||
|
||||
class MemoryWait(unittest.TestCase):
|
||||
def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self):
|
||||
fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects()))
|
||||
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"])
|
||||
self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2)
|
||||
self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue())
|
||||
|
||||
def test_a_worker_starts_at_once_where_memory_cannot_be_read(self):
|
||||
fake = FakeEffects(free_memory=[None], streams=[Streamed(0)])
|
||||
self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects()))
|
||||
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The verdicts cycle.judge.verdict_from builds from the judge's reply; cycle.run.rule then stamps every verdict but Finished with the items the chunk takes. They sit outside cycle/, since routing reads them and cycle imports routing."""
|
||||
"""The verdicts judge.verdict_from builds from the judge's reply; run.rule then stamps every verdict but Finished with the items the chunk takes. They sit in a module of their own, since routing.py reads them and run.py imports routing.py."""
|
||||
import dataclasses
|
||||
|
||||
from transcript_archive.judge_run import JudgeRun
|
||||
@@ -7,7 +7,7 @@ from claude_code.tokens import Tokens
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TakenIn:
|
||||
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
|
||||
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as the entry point reads them (run.py's Cycle.taken_in). The item the chunk was routed on counts only where the worker names it."""
|
||||
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
|
||||
highest_likelihood: int = 0
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
|
||||
|
||||
Reference in New Issue
Block a user