Move loop-claude's cycle, judge, interrupt, tmux and routing into agent_cycle
CI / tests (pull_request) Failing after 3m50s

This commit is contained in:
2026-11-18 16:21:35 +01:00
parent 2c5406ab38
commit 54fc339fb0
45 changed files with 348 additions and 237 deletions
+65 -61
View File
@@ -11,6 +11,7 @@ import stat
import subprocess
import sys
import tempfile
import types
import unittest
import unittest.mock
import uuid
@@ -28,9 +29,11 @@ from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from loop_effects.effects import Effects, PYTHON_TIMEOUT
from claude_code import entries, reply, session
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
from git_cli.git_repo import git
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
from agent_cycle import interrupt, judge, retry, run, spend, states, worker, worker_prompts
import loop_claude.routed_item
from loop_claude.cycle import prompts
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from machine_load import memory
@@ -42,13 +45,13 @@ from transcript_archive.location import project_archive
from model_routing.ladder import ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from loop_claude.stop import Stop
from loop_claude import tmux
from agent_cycle import routing
from agent_cycle.stop import Stop
from agent_cycle import tmux
from claude_code.tokens import Tokens, tokens_of
from touch_predictions.test_touch_predictions import plan as touch_plan
from text_files.utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
from agent_cycle.judge import verdict_from
# How the archive records a worker that runs off the ladder.
LADDER = read_ladder(SHIPPED)
@@ -277,8 +280,9 @@ class Transitions(unittest.TestCase):
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
cycle = types.SimpleNamespace(prompts=prompts.WORKER)
self.assertEqual(run.question_for(cycle, Interrupt("e", "Which one?")), "Which one?")
self.assertEqual(run.question_for(cycle, QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
class Cycles(unittest.TestCase):
@@ -291,7 +295,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", prompts=prompts.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan_of("")), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
"""Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them."""
@@ -619,7 +623,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
typed = resumed[resumed.index("-p") + 1]
self.assertEqual(prompts.typed_answer(typed).answer, "Use B.")
self.assertEqual(worker_prompts.typed_answer(typed).answer, "Use B.")
self.assertIn("Which one?", typed)
self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed)
judge_prompts = [stdin for args, stdin in fake.made("claude")]
@@ -1007,8 +1011,8 @@ class ModelPrompt(unittest.TestCase):
# A plan read with no release cut yet.
NO_CUT = LastCut(None, "", 0, [])
def routed_item(todo, cut):
"""routing.routed_item for the plan a todo.md's text holds."""
return routing.routed_item(plan_of(todo), cut)
"""loop_claude.routed_item.routed_item for the plan a todo.md's text holds."""
return loop_claude.routed_item.routed_item(plan_of(todo), cut)
TODO = """# todo
@@ -1710,13 +1714,13 @@ class TypedAnswers(unittest.TestCase):
def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self):
route = Route(Rung("worker-model"))
marked = "The human answered your question at loop-claude's terminal:\nB"
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False))
typed = worker_prompts.typed_answer(prompts.WORKER.typed("Which one?", "Use B.", route, None, False))
self.assertEqual(typed.answer, "Use B.")
self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task."))
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.")
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False)))
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None)))
self.assertEqual(worker_prompts.typed_answer(prompts.WORKER.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.")
self.assertEqual(worker_prompts.typed_answer(prompts.WORKER.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.")
self.assertIsNone(worker_prompts.typed_answer(prompts.WORKER.answered("Which one?", marked, route, None, False)))
self.assertIsNone(worker_prompts.typed_answer(prompts.resumed(marked, route, None)))
class WorkerArgs(unittest.TestCase):
@@ -1918,7 +1922,7 @@ class Records(unittest.TestCase):
class JudgePrompt(unittest.TestCase):
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 0))
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 0))
self.assertTrue(grounds.shown.endswith("\n\nnew"))
self.assertNotIn("old", grounds.shown)
self.assertIn(grounds.shown, prompt)
@@ -1927,32 +1931,32 @@ class JudgePrompt(unittest.TestCase):
self.assertEqual(grounds.quotable, "## Goals\n\n")
def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self):
prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(assistant({"type": "text", "text": "done"})), 1))
prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(assistant({"type": "text", "text": "done"})), 1))
self.assertNotRegex(prompt + json.dumps(judge.JUDGE_SCHEMA), r"\b[Aa]gent")
def test_the_judge_prompt_names_every_rule_the_judge_reads_from_the_human(self):
self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.JUDGE_RULES], [])
self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.judge_rules(prompts.ANSWER_DESTINATIONS)], [])
def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})]
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 1))
self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n")
self.assertEqual(grounds.after_mark, "round 3: 🔴")
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 0))
prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 0))
self.assertNotIn("stepped the worker up", prompt)
self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴")
self.assertEqual(grounds.after_mark, "round 2: 🔴\n\nround 3: 🔴")
def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 1))
self.assertEqual(judge.quotes_checked(Unfinished("e", "old x", entries_read=3), grounds), Unfinished("e", entries_read=3))
self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3))
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
typed = prompts.WORKER.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 1))
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
@@ -2179,7 +2183,7 @@ class Verdict(unittest.TestCase):
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", "", kinds(*entries), mark), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects())
return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), mark), 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))
@@ -2188,12 +2192,12 @@ class Verdict(unittest.TestCase):
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", "", kinds(*entries), 1), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects())
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 1), 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", "", kinds(*entries), 1), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", prompts.ANSWER_DESTINATIONS, kinds(*entries), 1), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
@@ -2462,41 +2466,41 @@ class ExitContract(unittest.TestCase):
unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
clauses = [
("cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
("cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
("cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("cycle/run.py", "rule", "1", "entries.reason", read),
("cycle/run.py", "rule", "1", "annotation.reason", read),
("cycle/run.py", "rule", "1", "failure.reason", read),
("cycle/run.py", "keep_rejection", "1", "unkept.reason", read),
("cycle/run.py", "close", "1", "annotation.reason", read),
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
("loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
("loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
("loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
("loop/main.py", "next_cycle", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
("loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"),
("project/checkout.py", "checkout_root", "1", "found.reason", git),
("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
("agent_cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
("agent_cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
("agent_cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
("agent_cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
("agent_cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("agent_cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("agent_cycle/run.py", "rule", "1", "entries.reason", read),
("agent_cycle/run.py", "rule", "1", "annotation.reason", read),
("agent_cycle/run.py", "rule", "1", "failure.reason", read),
("agent_cycle/run.py", "keep_rejection", "1", "unkept.reason", read),
("agent_cycle/run.py", "close", "1", "annotation.reason", read),
("agent_cycle/run.py", "close", "1", "failure.reason", read),
("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop_claude/loop/close.py", "closed_cycle", "1", "failure.reason", read),
("loop_claude/loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("loop_claude/loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
("loop_claude/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("loop_claude/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
("loop_claude/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
("loop_claude/loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop_claude/loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop_claude/loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
("loop_claude/loop/main.py", "next_cycle", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
("loop_claude/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
("loop_claude/loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop_claude/loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
("loop_claude/loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"),
("loop_claude/project/checkout.py", "checkout_root", "1", "found.reason", git),
("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
]
root = pathlib.Path(main.__file__).parents[1]
root = pathlib.Path(main.__file__).parents[2]
found = []
for path in sorted(path for path in root.rglob("*.py") if not path.name.startswith("test_")):
for path in sorted(path for package in ("agent_cycle", "loop_claude") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")):
functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)]
stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)]