diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 14881d83..b40f34a8 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -12,8 +12,6 @@ from loop_claude.cycle.retry import Limited, retried from loop_claude.stop import Stop from todo_table import TOP_SCORE -# Routes the next cycle's worker; loop-claude never steps it down, so the item the chunk was routed on may count too. -BUNDLED = "The highest R + C the agent states for a todo.md item it took into this chunk; 0 when it states none." # At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03. JUDGE_PROMPT_CHARS = 400000 JUDGE_RULES = ( @@ -45,15 +43,15 @@ JUDGE_RULES = ( f"where README.md or the records above hold it, {', '.join(HUMAN_RULE_NAMES)} included. It also counts where " f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into " f"{either(HUMAN_RULE_NAMES)} does not count. finished=false when work remains that a further run can " - "continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded.\n" - f"bundled: {BUNDLED}" + "continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded." ) @dataclasses.dataclass(frozen=True) class Reply: answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."}) - bundled: int = dataclasses.field(metadata={"description": BUNDLED}) + # Routes the next cycle's worker; loop-claude never steps it down, so the item the chunk was routed on may count too. + bundled: int = dataclasses.field(metadata={"description": "The highest R + C the agent states for a todo.md item it took into this chunk; 0 when it states none."}) evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."}) finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."}) interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."}) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index e025ac25..507ad473 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -48,9 +48,9 @@ model's cheapest rung. The worker's first prompt names the rung and the item, an each other item the chunk takes in, with its R + C. The judge reports the highest R + C it sees the worker state, and the next cycle steps up to the rung that picks, never down. Every second unfinished verdict on a chunk steps it up one rung. A rung an edit took off the ladder counts as -the model's cheapest. Each verdict and each stop archived names the worker's rung, with the item -and R + C that routed the chunk; a rerun resumes an open chunk on the latest rung named there, while -that is at or above the model's cheapest. A todo.md that cannot be read or parsed is said on stderr, +the model's cheapest. Each verdict, stop and step up archived names the worker's rung, with the +item and R + C that routed the chunk; a rerun resumes an open chunk on the latest rung named there, +while that is at or above the model's cheapest, and counts its unfinished verdicts afresh. A todo.md that cannot be read or parsed is said on stderr, and the chunk runs on the model's cheapest rung. A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once @@ -93,6 +93,7 @@ import pathlib import sys import typing +from transcript_archive.write import archive from loop_claude.project.checkout import checkout_root from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG @@ -103,6 +104,7 @@ from loop_claude.routing import first_route, kept, Route, route_from, routed_ite from loop_claude.project.model_choice import get_or_ask_models from todo_table import Item from transcript_archive.read import latest_worker +from transcript_archive import outcomes from loop_claude.paths import Paths from transcript_archive.location import project_archive from project_key import project_key @@ -153,7 +155,9 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc verdict = run_cycle(Cycle(effects=effects, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) if isinstance(verdict, Stop): return verdict - loop_run = after_verdict(loop_run, anchor, verdict) + before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict) + if stop := archive_step(archive, session, loop_run, before, effects): + return stop def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun: @@ -172,6 +176,15 @@ def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Un return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence) +def archive_step(project_archive: pathlib.Path, session: Session, loop_run: LoopRun, before: Route | None, effects: Effects) -> Stop | None: + """Archives the rung an unfinished verdict stepped the chunk up to; the verdict itself names the rung its cycle ran on.""" + if not (before and loop_run.route) or loop_run.route.rung == before.rung: + return None + path = transcript_file(session) + failure = archive(project_archive, path, loop_run.task, outcomes.stepped_up(str(loop_run.route)), effects.now()) if path else None + return Stop(1, failure.reason) if failure else None + + def archived_route(archive: pathlib.Path, session: Session) -> Route | None: """The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged.""" transcript = transcript_file(session) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index a52d9a20..a6d487ff 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -392,7 +392,7 @@ class Cycles(unittest.TestCase): self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)}) self.assertIn("loop-claude runs you on claude-opus-5-5 at high effort, the rung item 4's R + C of 11 picks. When the chunk takes in another todo.md item, say so, naming that item and its R + C.", argument(workers[0], "-p")) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) - self.assertIn(" Verdict: unfinished\n\nEvidence:\n> three\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n", outcomes) + self.assertIn(" Verdict: unfinished\n\nEvidence:\n> three\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n\n Stepped up\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes) self.assertIn(" Verdict: finished\n\nEvidence:\n> four\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes) def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self): @@ -486,7 +486,7 @@ class Cycles(unittest.TestCase): self.assertIn("LATE", run.calls[1]["stdin"]) self.assertEqual(len(run.calls[1]["stdin"]), 400000) self.assertLess(run.calls[1]["stdin"].count("early"), 80000) - self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("0 when it states none.")) + self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("CI not yet reported, an answer not yet recorded.")) def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 635f0537..c79f2e98 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -405,6 +405,9 @@ class Routing(unittest.TestCase): self.assertEqual(routing.routed_item(TODO).id, 3) self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"))) self.assertIsNone(routing.routed_item("# todo\n")) + self.assertIsNone(routing.routed_item(TODO[:TODO.index("| 7 |")])) + without_c = TODO.replace(" C |", "").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 9 | 1 | 9 |", "| 9 | 1 |").replace("| 5 | 3 | 6 |", "| 5 | 3 |").replace("| 1 | 1 | 1 |", "| 1 | 1 |") + self.assertIsNone(routing.routed_item(without_c)) self.assertEqual(routing.routed_item(TODO.replace("| 5 | 3 |", "| x | 3 |")), Failure("item 3's R 'x' is not a whole number from 1 to 10")) def test_starts_a_chunk_on_the_rung_its_items_r_plus_c_picks_never_below_the_projects(self): @@ -426,6 +429,7 @@ class Routing(unittest.TestCase): def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 0).rung, self.OPUS) + self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 2).rung, self.OPUS) def test_archives_the_route_in_a_line_it_reads_back(self): route = routing.Route(self.HIGH, 3, 11) @@ -487,7 +491,39 @@ class RouteSources(unittest.TestCase): self.assertTrue(stderr.getvalue().startswith("routing the chunk afresh: could not read the archive"), stderr.getvalue()) +class Steps(unittest.TestCase): + OPUS = Rung("claude-opus-5-5", "medium") + + def test_a_finished_verdict_clears_the_route_and_the_evidence(self): + run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=routing.Route(self.OPUS)) + self.assertEqual(main.after_verdict(run_with, self.OPUS, Finished("x")), dataclasses.replace(run_with, route=None, unfinished_evidence="")) + self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 13)), dataclasses.replace(run_with, route=routing.Route(Rung("claude-opus-5-5", "xhigh"), unfinished=1), unfinished_evidence="new")) + + def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) + archive = pathlib.Path(home, "archive") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + before = routing.Route(self.OPUS, 3, 9) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working"), NOW)) + after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 13)) + self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects())) + self.assertEqual(main.archived_route(archive, opened), routing.Route(Rung("claude-opus-5-5", "xhigh"), 3, 9)) + self.assertIsNone(main.archive_step(archive, opened, after, after.route, FakeEffects().effects())) + self.assertIsNone(main.archive_step(archive, opened, after, None, FakeEffects().effects())) + + class WorkerArgs(unittest.TestCase): + def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): + routed = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("m", "high"), 3, 11)) + self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, the rung item 3's R + C of 11 picks. When the chunk takes in another todo.md item, say so, naming that item and its R + C.\n\nThe chunk's", routed) + unrouted = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("m"))) + self.assertIn("before creating a new one.\n\nThe chunk's", unrouted) + self.assertNotIn("loop-claude runs you on", unrouted) + def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", routing.Route(Rung("m"))), resume=False) @@ -658,6 +694,7 @@ class ExitContract(unittest.TestCase): ("cycle/run.py", "ask", "1", "failure.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/main.py", "archive_step", "1", "failure.reason", read), ("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "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"), diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index 2a6746e1..8e0bfe11 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -7,7 +7,7 @@ FINISHED = "Verdict: finished" FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE) # An outcome opens with its UTC stamp; a verdict that closes a cycle, or a stop, ends with the worker line. OUTCOME_AT = re.compile(rf"^({STAMPED}) ", re.MULTILINE) -CLOSES_A_CYCLE = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ") +CLOSES_A_CYCLE = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ", "Stepped up\n") WORKER = "Worker: " @@ -27,6 +27,11 @@ def answered(question: str, sources: str, answer: str, evidence: str) -> str: return f"Verdict: quoted answer\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}" +def stepped_up(worker: str) -> str: + """The rung the next cycle steps up to, archived as it steps, so a rerun after any exit resumes on it.""" + return f"Stepped up\n\n{WORKER}{worker}" + + def stopped(worker: str, why: str) -> str: return f"Stopped: {why}\n\n{WORKER}{worker}" diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 1d3385b2..abeefc2a 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -56,6 +56,11 @@ class Outcomes(unittest.TestCase): ])) self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")]) + def test_reads_no_worker_from_an_outcome_written_before_the_worker_line(self): + kept = f"Task: Do it.\n\n{utc(NOW)} Stopped: Ctrl-C\n\n{utc(NOW)} Verdict: unfinished\n\nEvidence:\n> Worker: no\n" + self.assertEqual(outcomes.workers(kept), []) + self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.stepped_up('w')}\n"), [(utc(NOW), "w")]) + def test_takes_the_outcome_written_last_within_one_second(self): with tempfile.TemporaryDirectory() as root: kept = pathlib.Path(root, "archive")