List every running loop in loop-inbox, with the ID and tagline of each item its chunk takes

This commit is contained in:
2026-10-29 19:57:11 +01:00
parent 8bddfdc282
commit 9bcfaebb83
16 changed files with 389 additions and 50 deletions
+7 -4
View File
@@ -67,6 +67,8 @@ class Reply:
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Lists the chunk's items in loop-inbox: running_loops.py. A string, since the schema's types are JSON_TYPES.
items_taken_in: str = dataclasses.field(metadata={"description": "The IDs of the todo.md items the worker states this chunk takes, the one it was routed on included, separated by commas, such as `12, 14`; empty when it states none."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
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 worker's question; else what shows the chunk finished or the work remaining."})
@@ -112,18 +114,19 @@ def verdict_from(output: object) -> Verdict | Failure:
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
# An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
items = tuple(dict.fromkeys(item for item in map(int, re.findall(r"[0-9]+", output["items_taken_in"])) if item))
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"])
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"], items_taken_in=items)
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood)
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, items_taken_in=items)
if output["finished"]:
return Finished(output["evidence"])
escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact)
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact, items_taken_in=items)
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
@@ -164,7 +167,7 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in, items_taken_in=verdict.items_taken_in)
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
+18 -2
View File
@@ -42,13 +42,18 @@ class Cycle:
project: Rung | None
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
# The IDs of the items the judge has found the chunk takes, as LoopRun.taken_in.
taken_in: tuple[int, ...]
# Lists taken_in in loop-inbox, as it grows.
show: typing.Callable[[tuple[int, ...]], None]
@dataclasses.dataclass(frozen=True)
class Concluded:
"""How a cycle ended: its verdict, and the route it ended on, which an interrupt's or a quoted answer's escalation may have stepped up from the route it began on."""
"""How a cycle ended: its verdict, the route it ended on, which an interrupt's or a quoted answer's escalation may have stepped up from the route it began on, and the items the judge has found the chunk takes."""
verdict: Finished | Unfinished
route: Route
taken_in: tuple[int, ...] = ()
def run_cycle(cycle: Cycle) -> Stop | Concluded:
@@ -61,10 +66,21 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
if isinstance(event, Ruled) and event.step_up:
cycle = dataclasses.replace(cycle, route=event.step_up.after)
if isinstance(event, Ruled) and not isinstance(event.verdict, Finished):
cycle = taken_in(cycle, event.verdict.items_taken_in)
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
return Concluded(state.verdict, cycle.route)
return Concluded(state.verdict, cycle.route, cycle.taken_in)
def taken_in(cycle: Cycle, items: tuple[int, ...]) -> Cycle:
"""cycle with items among those the chunk takes, shown in loop-inbox where any is new."""
grown = tuple(dict.fromkeys(cycle.taken_in + items))
if grown == cycle.taken_in:
return cycle
cycle.show(grown)
return dataclasses.replace(cycle, taken_in=grown)
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
+29 -5
View File
@@ -33,6 +33,9 @@ A release ready to cut opens that session on the terminal at once, since only th
loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked
trusted in ~/.claude.json. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes:
the item it was routed on, then those the judge finds the worker took in.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A
@@ -130,6 +133,7 @@ from transcript_archive.location import archive_root, project_archive
from loop_claude.cycle.run import archived_stop, Concluded, Cycle, run_cycle
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.running_loops import chunk_items, Show, shown_running, Taken
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from chunk_pick import default_plan, DefaultPlan
from git_repo import default_ref
@@ -137,7 +141,7 @@ from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.verdicts import Finished, Unfinished
from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item
from todo_table import Item, items
from transcript_archive.read import latest_worker
from loop_claude.stop import needs_human, Stop
from transcript_archive import outcomes
@@ -175,6 +179,12 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
archive_folder = project_archive(loop_run.root, paths.home, env)
# "A " is the human's cue in the session picker that the session is the loop's.
session = session_named(f"A {key} loop-claude", paths.claude_code_transcripts)
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as show:
return cycles(loop_run, env, paths, launcher, baseline, key, archive_folder, session, show, effects)
def cycles(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, baseline: str, key: str, archive_folder: pathlib.Path, session: Session, show: Show, effects: Effects) -> Stop:
"""Runs cycles until one stops the loop, listing in loop-inbox, through show, the items each chunk takes."""
while True:
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
return stop
@@ -193,7 +203,9 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
show_taken = shown_items(show, loop_run.root, route.item)
show_taken(loop_run.taken_in)
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, show=show_taken, taken_in=loop_run.taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
@@ -204,6 +216,18 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
return stop
def shown_items(show: Show, root: str, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
"""What lists in loop-inbox the items a chunk takes: routed, the item it was routed on, 0 for none, then those taken in, each with its tagline."""
return lambda taken_in: show(taken_items(fetched_plan(root), chunk_items(routed, taken_in)))
def taken_items(plan: DefaultPlan | Failure, ids: tuple[int, ...]) -> tuple[Taken, ...]:
"""Each item of ids with its tagline on the default branch, as last fetched; empty where that todo.md cannot be read or doesn't hold the item."""
found = items(plan.todo) if isinstance(plan, DefaultPlan) and isinstance(plan.todo, str) else []
taglines = {item.id: item.tagline.removeprefix("**").removesuffix("**") for item in found} if isinstance(found, list) else {}
return tuple(Taken(id_, taglines.get(id_, "")) for id_ in ids)
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung, and model the project's model.
@@ -234,12 +258,12 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict, and counts the verdict."""
"""The loop run the next cycle starts from. A finished chunk drops its route, its run of unfinished verdicts and the items it took in. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict and the items its cycle ended with, and counts the verdict."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0, taken_in=())
route = stepped_route(project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1, taken_in=concluded.taken_in)
def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
+7 -1
View File
@@ -26,6 +26,8 @@ class LoopRun:
route: Route | None = None
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
# The IDs of the items the judge has found the chunk takes, beside the one it was routed on; loop-inbox lists them. A finished chunk empties it.
taken_in: tuple[int, ...] = ()
def decode_handed(handed: str, kind: type[T]) -> T | None:
@@ -43,7 +45,7 @@ RETIRED = object()
def decoded_as(value: object, kind: typing.Any) -> typing.Any:
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, a tuple of one type from a list, else a value of exactly kind."""
if isinstance(kind, types.UnionType):
found = [decoded_as(value, option) for option in typing.get_args(kind)]
fits = [each for each in found if each is not REJECTED and each is not RETIRED]
@@ -64,6 +66,10 @@ def decoded_as(value: object, kind: typing.Any) -> typing.Any:
if any(field in (REJECTED, RETIRED) for field in fields.values()) or not getattr(kind, "fits", lambda _: True)(fields):
return REJECTED
return kind(**fields)
if typing.get_origin(kind) is tuple:
element = typing.get_args(kind)[0]
found = [decoded_as(each, element) for each in value] if isinstance(value, list) else [REJECTED]
return REJECTED if REJECTED in found or RETIRED in found else tuple(found)
return value if type(value) is kind else REJECTED
+115
View File
@@ -0,0 +1,115 @@
"""The files by which a loop-claude shows loop-inbox that it runs, and the todo.md items its chunk takes.
A running loop holds <session>.running.lock in Paths.waiting for its whole run, and keeps <session>.running beside it:
its checkout, and the ID and tagline of each item its chunk takes. loop-inbox lists a loop only while its lock is held,
so a killed loop drops off the list though its file stays. The file is replaced whole on each change, which gives it a
new inode, so the lock is a file of its own.
"""
import contextlib
import dataclasses
import json
import pathlib
import typing
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.session_lock import held, taken
from file_writes import replace_json
# How many times, 0.1 s apart, a loop tries to take its lock: loop-inbox takes it for a moment each time it looks whether the loop runs.
LOCK_TRIES = 10
@dataclasses.dataclass(frozen=True)
class Taken:
"""A todo.md item a chunk takes."""
id: int
# The item's tagline without its bold marks; empty where the default branch's todo.md holds no such item.
tagline: str
@dataclasses.dataclass(frozen=True)
class RunningLoop:
session: str
# The checkout the loop runs in.
root: str
# The routed item first; empty before the chunk names one.
items: tuple[Taken, ...]
Show = typing.Callable[[tuple[Taken, ...]], None]
def running_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.running"
def running_lock(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.running.lock"
@contextlib.contextmanager
def shown_running(folder: pathlib.Path, session: str, root: str, effects: Effects) -> typing.Iterator[Show]:
"""Lists the loop in loop-inbox as running while the with block runs, at first with no item, and yields what lists the items its chunk takes. A failure only warns, and the loop runs unlisted."""
with contextlib.ExitStack() as stack:
if unlocked := locked_soon(stack, folder, running_lock(folder, session), effects):
say(f"loop-inbox cannot list this loop as running: {unlocked.reason}", effects)
yield lambda items: None
return
def show(items: tuple[Taken, ...]) -> None:
if unshown := replace_json(running_file(folder, session), {"root": root, "items": [dataclasses.asdict(item) for item in items]}):
say(f"loop-inbox cannot list this loop's items: {unshown.reason}", effects)
show(())
try:
yield show
finally:
# A file this fails to remove stays, and loop-inbox leaves it out once the lock is let go.
with contextlib.suppress(OSError):
running_file(folder, session).unlink(missing_ok=True)
def locked_soon(stack: contextlib.ExitStack, folder: pathlib.Path, path: pathlib.Path, effects: Effects) -> Failure | None:
"""Holds the lock at path until stack closes, trying LOCK_TRIES times; the last failure where every try failed."""
for _ in range(LOCK_TRIES):
attempt = contextlib.ExitStack()
unlocked = attempt.enter_context(held(folder, path))
if not unlocked:
stack.enter_context(attempt)
return None
attempt.close()
effects.sleep(0.1)
return unlocked
def running_loops(folder: pathlib.Path) -> list[RunningLoop]:
"""The loops that hold their lock, by checkout. A file that cannot be read or parsed is left out."""
try:
paths = list(folder.glob("*.running"))
except OSError:
return []
loops = [loop for path in paths if (loop := read_running(path)) and taken(running_lock(folder, loop.session))]
return sorted(loops, key=lambda loop: loop.root)
def read_running(path: pathlib.Path) -> RunningLoop | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
match data:
case {"root": str(root), "items": list(items)} if all(is_item(item) for item in items):
return RunningLoop(path.name.removesuffix(".running"), root, tuple(Taken(item["id"], item["tagline"]) for item in items))
return None
def is_item(item: object) -> bool:
match item:
# type(), not isinstance(): JSON true is no ID.
case {"id": id_, "tagline": str()} if type(id_) is int:
return True
return False
def chunk_items(routed: int, taken_in: tuple[int, ...]) -> tuple[int, ...]:
"""The IDs of the items a chunk takes: routed, the item it was routed on, 0 for none, then those the judge found it took in, once each."""
return tuple(dict.fromkeys(([routed] if routed else []) + list(taken_in)))
+17 -5
View File
@@ -1,7 +1,8 @@
"""The lock a loop-claude holds on its worker's session while loop-inbox lists the session's question. loop-inbox reads a held lock as a loop that still runs.
"""The locks by which loop-inbox tells that a loop-claude still runs.
The lock is <session>.lock, held with flock, which the kernel frees however the loop ends, killed included. The lock
file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why.
A loop holds <session>.lock while loop-inbox lists the session's question, and <session>.running.lock for its whole run
(running_loops.py). Each is held with flock, which the kernel frees however the loop ends, killed included. A lock file
stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why.
"""
import contextlib
import fcntl
@@ -19,12 +20,18 @@ def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
@contextlib.contextmanager
def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]:
"""Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox's drop_ended takes the lock for a moment on each ask still on disk, so a loop may find it held."""
with held(folder, lock_file(folder, session)) as unlocked:
yield unlocked
@contextlib.contextmanager
def held(folder: pathlib.Path, path: pathlib.Path) -> typing.Iterator[Failure | None]:
"""Holds the lock at path, a file in folder, while the with block runs, or yields a Failure where it cannot."""
try:
make_private(folder)
except OSError as failure:
yield Failure(f"cannot make {folder}: {failure.strerror}")
return
path = lock_file(folder, session)
try:
handle = open(path, "a")
except OSError as failure:
@@ -44,8 +51,13 @@ def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None
def running(folder: pathlib.Path, session: str) -> bool:
"""Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked."""
return taken(lock_file(folder, session))
def taken(path: pathlib.Path) -> bool:
"""Whether a process holds the lock at path; False also where it cannot be opened or locked."""
try:
with open(lock_file(folder, session)) as handle:
with open(path) as handle:
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
return True
+2 -2
View File
@@ -144,7 +144,7 @@ def worker(**step):
def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
verdict = {"items_taken_in": "", "answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
return {"role": "judge", "verdict": verdict, **step}
@@ -939,7 +939,7 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle} for cycle in (2, 3, 4)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "taken_in": []} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+61 -19
View File
@@ -37,6 +37,7 @@ from transcript_archive import outcomes, write
from transcript_archive.location import project_archive
from model_routing.route import Route, route_from, WorkerLine
from loop_claude.stop import Stop
from loop_claude.running_loops import Taken
from utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
@@ -144,8 +145,8 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False):
reply = {"answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, items_taken_in=""):
reply = {"items_taken_in": items_taken_in, "answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
return ran(json.dumps({"structured_output": reply}))
@@ -251,7 +252,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(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, 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.", unfinished_evidence=unfinished_evidence)
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show=lambda taken_in: None, taken_in=(), task="Do it.", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -262,6 +263,20 @@ class Cycles(unittest.TestCase):
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_shows_the_items_each_ruling_finds_the_chunk_takes_and_concludes_with_them(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker], claude=[judged("unfinished", items_taken_in="14, 3")])
shown = []
concluded = run.run_cycle(dataclasses.replace(self.cycle(fake), show=shown.append, taken_in=(3,)))
self.assertEqual((shown, concluded.taken_in), ([(3, 14)], (3, 14)))
def test_shows_nothing_for_a_ruling_that_finds_no_item_the_chunk_did_not_already_take(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker], claude=[judged("unfinished", items_taken_in="3")])
shown = []
concluded = run.run_cycle(dataclasses.replace(self.cycle(fake), show=shown.append, taken_in=(3,)))
self.assertEqual((shown, concluded.taken_in), ([], (3,)))
def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")])
@@ -1186,6 +1201,11 @@ class Steps(unittest.TestCase):
self.assertEqual(main.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_an_unfinished_chunk_keeps_the_items_its_cycle_took_in_and_a_finished_one_drops_them(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS), taken_in=(3,))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), run_with.route, (3, 12))).taken_in, (3, 12))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route, (3, 12))).taken_in, ())
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
raised = Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=5)
@@ -1239,6 +1259,11 @@ class Steps(unittest.TestCase):
class ChunkFacts(unittest.TestCase):
def test_names_each_item_a_chunk_takes_by_its_tagline_on_the_default_branch(self):
self.assertEqual(main.taken_items(DefaultPlan(TODO, NO_CUT), (3, 99)), (Taken(3, "Do the next thing."), Taken(99, "")))
self.assertEqual(main.taken_items(DefaultPlan(Failure("no todo.md"), NO_CUT), (3,)), (Taken(3, ""),))
self.assertEqual(main.taken_items(Failure("no origin"), (3,)), (Taken(3, ""),))
PREFLIGHT = pathlib.Path("/b/chunk-preflight")
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
@@ -1602,21 +1627,21 @@ class Grounded(unittest.TestCase):
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "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({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"items_taken_in": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
def test_takes_the_highest_l_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
reply = {"items_taken_in": "", "answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Unfinished("e", 4))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": True}), Failure("the judge's reply has no highest_likelihood_taken_in of type integer"))
for highest_likelihood_taken_in in (5, 13, -1):
@@ -1625,7 +1650,7 @@ class Verdict(unittest.TestCase):
def test_takes_the_highest_e_plus_i_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
reply = {"items_taken_in": "", "answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", 0, highest_escape_and_impact_taken_in=6))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", 0, highest_escape_and_impact_taken_in=2))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": False}), Failure("the judge's reply has no highest_escape_and_impact_taken_in of type integer"))
@@ -1633,14 +1658,23 @@ class Verdict(unittest.TestCase):
with self.subTest(escape_and_impact=escape_and_impact):
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": escape_and_impact}), Unfinished("e", 0))
def test_takes_the_items_taken_in_as_their_ids_once_each_on_every_verdict_but_finished(self):
reply = {"items_taken_in": "", "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "items_taken_in": "12, 14, 12"}), Unfinished("e", items_taken_in=(12, 14)))
self.assertEqual(verdict_from({**reply, "items_taken_in": "items 7 and 0"}), Unfinished("e", items_taken_in=(7,)))
self.assertEqual(verdict_from({**reply, "items_taken_in": "3", "interrupt": True, "question": "Which one?"}), Interrupt("e", "Which one?", items_taken_in=(3,)))
self.assertEqual(verdict_from({**reply, "items_taken_in": "3", "answer": "A.", "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.", items_taken_in=(3,)))
self.assertEqual(verdict_from({**reply, "items_taken_in": "3", "finished": True}), Finished("e"))
self.assertEqual(verdict_from({**reply, "items_taken_in": 3}), Failure("the judge's reply has no items_taken_in of type string"))
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
reply = {"items_taken_in": "", "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Unfinished("e", 0, "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": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
reply = {"items_taken_in": "", "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
@@ -1652,7 +1686,7 @@ class Verdict(unittest.TestCase):
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
def test_takes_an_escalation_quote_and_the_highest_l_taken_in_on_a_quoted_answer(self):
reply = {"answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
reply = {"items_taken_in": "", "answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
@@ -1662,6 +1696,7 @@ class Verdict(unittest.TestCase):
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", items_taken_in=(3,)), judge.Grounds("shown", "shown", "A.")), Interrupt("e", "q", items_taken_in=(3,)))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", 4), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", 4))
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
@@ -1734,6 +1769,13 @@ class LoopRuns(unittest.TestCase):
def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self):
self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""}), main.LoopRun), main.LoopRun(3, "/r", "do it", ""))
def test_decodes_the_items_taken_in_as_a_tuple_of_ids(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", taken_in=(12, 14))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state)), main.LoopRun), state)
for taken_in in ([12, "14"], [True], "12", {"12": 1}):
with self.subTest(taken_in=taken_in):
self.assertIsNone(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"taken_in": taken_in}), main.LoopRun))
def test_stops_when_the_reload_cannot_start_python(self):
with tempfile.TemporaryDirectory() as root:
launcher = pathlib.Path(root, "loop-claude")
+5
View File
@@ -11,6 +11,8 @@ class Interrupt:
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
highest_likelihood_taken_in: int = 0
release_ready: bool = False
# The IDs of the todo.md items the judge saw the chunk take, the routed one included; loop-inbox lists them.
items_taken_in: tuple[int, ...] = ()
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read: int | None = None
@@ -24,6 +26,7 @@ class QuotedAnswer:
# As on Interrupt.
escalation: str = ""
highest_likelihood_taken_in: int = 0
items_taken_in: tuple[int, ...] = ()
entries_read: int | None = None
@@ -42,6 +45,8 @@ class Unfinished:
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
highest_escape_and_impact_taken_in: int = 0
# As on Interrupt.
items_taken_in: tuple[int, ...] = ()
# As on Interrupt.
entries_read: int | None = None