Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only
CI / tests (pull_request) Successful in 2m18s

This commit is contained in:
2026-11-13 23:22:49 +01:00
parent 0e0b17cd92
commit c1924e51ef
44 changed files with 123 additions and 1961 deletions
+1 -5
View File
@@ -51,17 +51,13 @@
!bin/larv_review/
!bin/larv_review/*.py
!bin/loop-claude
!bin/loop-inbox
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/loop_effects/
!bin/loop_effects/*.py
!bin/loop_inbox/
!bin/loop_inbox/*.py
!bin/loop_state/
!bin/loop_state/**/
!bin/loop_state/**/*.py
!bin/loop_state/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/mattermost-dm
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `loop-inbox` is gone: loop-claude asks each interrupt on its own terminal only, where a line typed answers it and `/talk` opens the worker's session, and the Mattermost DM still tells you a loop waits. Remove your `~/.local/bin/loop-inbox` link, and the folder `~/.local/state/loop-claude/`, which nothing reads any more.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token.
+1 -1
View File
@@ -125,7 +125,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`, which `~/.claude/bin/project-config goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder.
- **interrupt** — `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it. A release ready to cut opens that session at once, on loop-claude's terminal. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
+4 -5
View File
@@ -71,7 +71,7 @@ git config filter.settings.clean bin/settings_filter.py
Then pick a model with `/model`.
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` to the project's config, as Install → "Set up a project" describes. Without that setting, loop-claude sends no DM for the project; `~/.claude/.env` is no longer read.
@@ -132,7 +132,7 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
## Tools
Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
@@ -141,7 +141,6 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; the project's `env-file` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
@@ -168,8 +167,8 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, loop-inbox, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too, and `hand_over.py`, which opens claude on the terminal for `/talk`.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
+1 -1
View File
@@ -126,7 +126,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_inbox import main
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
+1 -1
View File
@@ -1,4 +1,4 @@
"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/usage.py's help).
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, and project/ reads a checkout's files. The files it shares with loop-inbox live in bin/loop_state/, and its effects in bin/loop_effects/. Each module at this level is imported by more than one package, or by a module at this level that is. 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.
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, and project/ reads a checkout's files. Its paths and the way it opens claude for the human live in bin/loop_state/, and its effects in bin/loop_effects/. Each module at this level is imported by more than one package, or by a module at this level that is. 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.
"""
+1 -1
View File
@@ -22,7 +22,7 @@ def taken_in(entries: list[Entry], todo: str | Failure) -> TakenIn:
ids = named(entries)
found = items(todo) if isinstance(todo, str) else todo
scored = [item for item in found if item.id in ids] if isinstance(found, list) else []
return TakenIn(ids, max((item.likelihood for item in scored), default=0), max((item.escape_and_impact for item in scored), default=0))
return TakenIn(max((item.likelihood for item in scored), default=0), max((item.escape_and_impact for item in scored), default=0))
def named(entries: list[Entry]) -> tuple[int, ...]:
+17 -45
View File
@@ -1,29 +1,26 @@
import dataclasses
import pathlib
import sys
import typing
import uuid
from loop_state.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, POLL_SECONDS, say
from loop_effects.effects import Effects, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from loop_state.waiting.listing import listed, shown
from loop_state.waiting.talk import make_way, TALK
from loop_claude.stop import needs_human, needs_terminal, Stop
from model_routing.ladder import Rung
from loop_claude.direct_message import tell
ANSWER_QUESTION = "answer the question above"
# What the human types at loop-claude's terminal to open claude for the question; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
TALK = "/talk"
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
@dataclasses.dataclass(frozen=True)
class WorkerSession:
"""The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox."""
"""The worker's claude session, which /talk opens on loop-claude's terminal."""
root: str
id: uuid.UUID
rung: Rung
@@ -40,8 +37,8 @@ class Talked:
"""The human typed in the worker's claude session."""
def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
def interrupt(question: str, answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
say(f"\n{question}", effects)
on_terminal = effects.on_terminal()
if on_terminal:
@@ -51,51 +48,26 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, question
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
return stop
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
with listed(questions, ask, effects):
answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal()
if isinstance(answer, OpenOnTerminal | OpenInInbox):
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, questions, effects)) or Talked()
answer = typed_answer(effects) if answer_here else TALK
if answer != TALK:
return answer
return human_typed(session.transcript_path, lambda: claude_open(session, effects)) or Talked()
def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type no answer, or the input ends."""
def typed_answer(effects: Effects) -> str | Stop:
"""The line typed at loop-claude's terminal, stripped. A Stop where they type no answer, or the input ends."""
try:
# Annotated since mypy infers input_or's T as object from the lambda.
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, ask))
text = effects.input(ASK_ANSWER).strip()
except EOFError:
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
return needs_human(ANSWER_QUESTION, "the input ended")
match answer:
case ClaudeOpening(pid):
return OpenInInbox(pid)
case Typed(text):
say(f"Answered in loop-inbox: {text}", effects)
case str(text):
pass
case _:
typing.assert_never(answer)
text = text.strip()
if not text:
return needs_human(ANSWER_QUESTION, "nothing was typed")
return OpenOnTerminal() if text == TALK else text
return text or needs_human(ANSWER_QUESTION, "nothing was typed")
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> Stop | None:
"""Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened."""
match where:
case OpenOnTerminal():
shown(questions, dataclasses.replace(ask, state=where), effects)
if unstarted := hand_over(session.claude_command(), effects):
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
case OpenInInbox(pid):
make_way(questions, ask, pid, effects)
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
while not claude_ended(questions, ask) and effects.alive(pid):
effects.sleep(POLL_SECONDS)
case _:
typing.assert_never(where)
def claude_open(session: WorkerSession, effects: Effects) -> Stop | None:
"""Opens the worker's claude session on the terminal, and returns once it has ended."""
if unstarted := hand_over(session.claude_command(), effects):
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
return None
+1 -7
View File
@@ -42,14 +42,10 @@ class Cycle:
# The project's rung; None for a model off the ladder.
project: Rung | None
project_archive: pathlib.Path
# Where the loop keeps its questions for loop-inbox: running_loops.Listed.folder.
questions: pathlib.Path
records: str
root: str
route: Route
session: Session
# Lists in loop-inbox the items the chunk takes, given the IDs on the worker's latest `Chunk items:` line.
show_taken_in: typing.Callable[[tuple[int, ...]], None]
task: str
# todo.md on the default branch as the cycle starts, which scores the items the worker names.
todo: str | Failure
@@ -74,8 +70,6 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
# Only a ruling's step-up changes the route within a cycle, here, once rule has archived the ruling on the route before it. No transition reads the current route, so Cycle holds it, not the states.
if isinstance(event, Ruled) and event.stepped_to:
cycle = dataclasses.replace(cycle, route=event.stepped_to)
if isinstance(event, Ruled) and not isinstance(event.verdict, Finished):
cycle.show_taken_in(event.verdict.taken_in.items)
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
@@ -201,7 +195,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.questions, cycle.effects)
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.effects)
match answer:
case Stop():
return answer
+1 -1
View File
@@ -9,7 +9,7 @@ QUOTED_ANSWERS_PER_CYCLE = 3
@dataclasses.dataclass(frozen=True)
class TypedAnswer:
"""The human's answer to an interrupt, typed at loop-claude's terminal or in loop-inbox."""
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
question: str
answer: str
+2 -8
View File
@@ -1,4 +1,4 @@
"""How a cycle starts: the route it runs on, from the archive or the plan, the facts chunk-preflight finds for a fresh chunk, and the items loop-inbox lists."""
"""How a cycle starts: the route it runs on, from the archive or the plan, and the facts chunk-preflight finds for a fresh chunk."""
import pathlib
import typing
@@ -15,19 +15,13 @@ from loop_claude.cycle import prompts
from model_routing.route import Route, route_from
from model_routing.ladder import Rung
from claude_code.session import session_open, transcript_file
from loop_state.running_loops import taken_items
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
ORIGIN_TIMEOUT = 60
def shown_items(loop: Loop, todo: str | Failure, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
"""A function that lists in loop-inbox the items a chunk takes, given the IDs the worker names, with their taglines in todo, as fetched_todo read it as the cycle started. routed is the item the chunk was routed on, 0 for none."""
return lambda taken_in: loop.listed.show(taken_items(todo, routed, taken_in))
def fetched_todo(loop: Loop) -> str | Failure:
"""The plan, which lists and scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which listing and scoring the items don't need. Where it can't be read or scored, it says why."""
"""The plan, which scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which scoring the items doesn't need. Where it can't be read or scored, it says why."""
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
+3 -3
View File
@@ -39,9 +39,9 @@ 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, its run of unfinished verdicts and the items it took in. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; the evidence the judge gave for the verdict, and the items the worker names on its latest `Chunk items:` line; and counts the verdict."""
"""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 routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised, and the evidence the judge gave for the verdict; and counts the verdict."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0, items_taken_in=())
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
route = next_route(project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1, items_taken_in=verdict.taken_in.items)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
+20 -24
View File
@@ -3,7 +3,7 @@ import pathlib
import typing
from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed, shown_items
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.loop.close import closed_cycle
@@ -21,7 +21,6 @@ from model_routing.ladder import project_rung
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from claude_code.session import session_named
from loop_state.running_loops import shown_running
from loop_claude.stop import Stop
from loop_claude.direct_message import tell
@@ -49,25 +48,24 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
baseline = fingerprint(launcher)
# "A " is the human's cue in the session picker that the session is the loop's.
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed:
loop = Loop(root=loop_run.root, session=session, listed=listed, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := exec_if_edited(loop, baseline, loop_run):
return stop
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
cycle = next_cycle(loop_run, loop)
if isinstance(cycle, Stop):
return cycle
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
if isinstance(closed, Stop):
return closed
loop_run = closed
# Off the ladder the worker runs on the project's model itself, which its route names.
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
return stop
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := exec_if_edited(loop, baseline, loop_run):
return stop
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
cycle = next_cycle(loop_run, loop)
if isinstance(cycle, Stop):
return cycle
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
if isinstance(closed, Stop):
return closed
loop_run = closed
# Off the ladder the worker runs on the project's model itself, which its route names.
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
return stop
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
@@ -88,9 +86,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
todo = fetched_todo(loop)
show_taken_in = shown_items(loop, todo, route.item)
show_taken_in(loop_run.items_taken_in)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
+4 -9
View File
@@ -25,8 +25,6 @@ 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 last unfinished verdict found the chunk takes, which loop-inbox lists until the next ruling.
items_taken_in: tuple[int, ...] = ()
class Unreadable(Exception):
@@ -39,6 +37,9 @@ def decode_handed(handed: str) -> LoopRun | None:
fields = json.loads(handed)
except ValueError:
return None
# A loop started before 0.11.0 hands the items loop-inbox listed; dropping them keeps it running across its reload.
if isinstance(fields, dict):
fields.pop("items_taken_in", None)
try:
return LoopRun(**decoded_fields(fields, LOOP_RUN_FIELDS, "cycle_number", "root", "task", "unfinished_evidence"))
except Unreadable:
@@ -61,12 +62,6 @@ def exactly(kind: type) -> typing.Callable[[typing.Any], typing.Any]:
return decode
def decoded_ids(value: object) -> tuple[int, ...]:
if not isinstance(value, list):
raise Unreadable
return tuple(exactly(int)(each) for each in value)
def decoded_route(value: object) -> Route | None:
"""The Route the JSON holds; None for null. dataclasses.asdict wrote it as a worker line's fields, with the rung nested and the unfinished count added. route_of reads it once the rung's model and effort are lifted to the top and the count is set aside."""
if value is None:
@@ -80,7 +75,7 @@ def decoded_route(value: object) -> Route | None:
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "items_taken_in": decoded_ids}
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int)}
def fingerprint(launcher: pathlib.Path) -> str:
+2 -6
View File
@@ -2,12 +2,10 @@
import pathlib
from routing_figures import archive
from loop_state.waiting.ask import Ask, OpenOnTerminal
from routing_figures.calls import Call, calls, totals
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, say
from failure import Failure
from loop_state.waiting.listing import listed
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
from routing_figures.render import render
@@ -51,7 +49,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
bullets = "".join(f"- {call.sentence()}\n" for call in new)
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
say(f"\n{question}", loop.effects)
@@ -60,9 +58,7 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) ->
say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects)
return None
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
ask = Ask(loop.effects.new_id(), str(loop.session.id), loop.root, question, loop.effects.now(), OpenOnTerminal())
with listed(loop.listed.folder, ask, loop.effects):
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
if unstarted:
return Stop(1, f"could not start claude for the routing calls in {loop.paths.config_clone}, the setup's development clone: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through docs/decisions.md → "Working rules", so it is not asked twice.
+1 -3
View File
@@ -3,7 +3,6 @@ import pathlib
import typing
from loop_effects.effects import Effects
from loop_state.running_loops import Listed
from loop_state.paths import Paths
from claude_code.session import Session
@@ -13,9 +12,8 @@ class Loop:
"""What stays the same through one run of loop-claude; run_loop builds it once per process, so a reload builds it afresh."""
# The checkout the loop runs in. LoopRun.root names it too, since a reload hands it on there.
root: str
# The worker's session, under whose id loop-inbox lists the loop and its questions.
# The worker's session.
session: Session
listed: Listed
paths: Paths
env: typing.Mapping[str, str]
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
+10 -14
View File
@@ -25,22 +25,18 @@ judge quoted as the work remaining. The next chunk starts a fresh session. Cycle
exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
interrupts of every loop on the machine. The first answer counts, from either place:
loop-claude prints the question on its terminal, where the human answers it:
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
chunk stays unfinished until the answer is recorded.
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
- /talk: opens the worker's session with `claude --resume` on the terminal, to read the diff or
discuss first. Once that claude exits, the judge rules on what was typed there.
- Enter alone, on loop-claude's terminal: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
- Enter alone: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it.
While claude is open, Ctrl-C reaches it alone, and the loop goes on.
Where the project's config sets env-file, loop-claude also sends the human each question, each
release ready to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
as bin/loop_state/running_loops.py describes.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
@@ -64,9 +60,9 @@ compacts its context at about 170k tokens.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
the session /talk opens and the judge on another rung, a model at an effort. A project without an
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
the worker and the session /talk opens; with both set, nothing is asked.
entry, as on its first run, is asked for one on the terminal. LOOP_CLAUDE_JUDGE_MODEL overrides
the model for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with
both set, nothing is asked.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
@@ -87,7 +83,7 @@ loop to close one measures every finished chunk there, with no model run, and wr
routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a
routing change, unless raised before, is an interrupt: claude, on the project's model, on the
terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to the
human; loop-inbox lists it too. Once that claude ends, the calls are listed in
human. Once that claude ends, the calls are listed in
routing-calls-raised.md beside the figures, kept in routing-state.json, and not raised again. Off a
terminal, the calls are said on stderr, the loop goes on, and they are raised again at the next
measurement.
@@ -123,7 +119,7 @@ Exit 2, when the human is needed to go on:
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
- the input ends while a model is picked
- an interrupt's answer is empty, or the input ends before one is typed
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends without
- the claude opened for /talk, or for a release ready to cut, ends without
anything typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning resumes any open session."""
+1 -44
View File
@@ -18,9 +18,6 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
from loop_state.waiting.answers import send, Typed
from loop_state import session_lock
from loop_state.waiting.listing import waiting
from project_config.test_project_config import write_config
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -41,8 +38,6 @@ role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "in
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
steps = json.loads(scenario.read_text())
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN, "sandboxed": os.environ.get("CLAUDE_CODE_SANDBOXED")}}
# The items each loop lists in loop-inbox as this claude starts.
call["running"] = [json.loads(path.read_text())["items"] for path in sorted((pathlib.Path.home() / ".local" / "state" / "loop-claude").glob("*.running"))]
if role == "judge":
call["stdin"] = sys.stdin.read()
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
@@ -496,16 +491,6 @@ class Cycles(unittest.TestCase):
self.assertIn("item 6, L 4, E + I 5", prompt)
self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir())
def test_lists_itself_in_loop_inbox_with_its_routed_item_then_those_the_worker_names_on_its_chunk_items_line_until_the_chunk_finishes(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(TODO)
run = checkout.run([worker(say="working\nChunk items: 7, 4"), judge(), worker(), judge(finished=True), worker()])
self.assertEqual(run.code, 130)
routed, taken_in = {"id": 4, "tagline": "Do it."}, {"id": 7, "tagline": ""}
self.assertEqual([call["running"] for call in run.calls], [[[routed]], [[routed]], [[routed, taken_in]], [[routed, taken_in]], [[routed]], [[routed]]])
self.assertEqual(list((checkout.home / ".local" / "state" / "loop-claude").glob("*.running")), [])
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
@@ -784,34 +769,6 @@ class Interrupt(unittest.TestCase):
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
self.assertNotIn("stray", run.calls[3]["stdin"])
def test_resumes_the_worker_headless_with_the_answer_typed_in_loop_inbox(self):
checkout = Checkout(self)
folder = checkout.home / ".local" / "state" / "loop-claude"
def answered_in_inbox():
[ask] = waiting(folder)
send(folder, ask, Typed("B"))
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
self.assertIn("Answer (/talk opens claude, Enter stops the loop): \nAnswered in loop-inbox: B\n", run.stderr)
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
self.assertEqual([path for path in folder.iterdir() if path.suffix != ".lock"], [])
def test_a_second_loop_on_the_session_runs_unlisted_and_keeps_its_question_out_of_the_first_loops_folder(self):
checkout = Checkout(self)
folder = checkout.home / ".local" / "state" / "loop-claude"
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
session = argument(checkout.run(asked).calls[0], "--session-id")
# The first loop on the session, still running.
self.enterContext(session_lock.held(folder, session))
asks = []
run = checkout.run(asked, terminal_input="\n", before_typing=("Answer (", lambda: asks.extend(folder.glob("*.json"))))
self.assertEqual(run.code, 2)
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(folder, session)}", run.stderr)
self.assertEqual((asks, run.calls[0]["running"]), ([], []))
self.assertFalse((folder / "unlisted").exists() and any((folder / "unlisted").iterdir()))
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
checkout = Checkout(self)
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
@@ -960,7 +917,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, "items_taken_in": []} 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} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+17 -176
View File
@@ -18,36 +18,31 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive, state
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from routing_figures.calls import Call
from loop_claude.project import checkout, model_choice, records
from loop_claude.cycle import chunk_items
from loop_claude.loop import chunk_start, close
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed
from project_config.test_project_config import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from loop_effects.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT
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 git_cli.git_repo import git
from loop_state import hand_over, paths, running_loops, session_lock
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
from model_routing.ladder import LADDER, Rung
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from loop_state.waiting.talk import make_way
from machine_load import memory
from transcript_archive import outcomes, write
from loop_state import paths
from transcript_archive.location import project_archive
from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from loop_claude.stop import Stop
from loop_state.running_loops import Taken
from claude_code.tokens import Tokens, tokens_of
from text_files.utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
from loop_state.waiting.listing import waiting
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
@@ -64,10 +59,6 @@ NOW = 1790000000
STAMP = f"<{NOW}>"
# How git answers in a project's checkout it cannot read, such as one that is gone.
UNREAD = Failure("not a git repository")
# The id FakeEffects gives each new ask, and its pid for loop-claude's process.
ASK_ID, PID = "ask-1", 4242
# The pid of a loop-inbox that opens claude for an ask.
INBOX = 4343
def assistant(*parts):
@@ -82,15 +73,10 @@ def human(content):
return {"type": "user", "message": {"content": content}}
def asks_and_answers(folder):
"""folder's files but the session's lock file, which stays once the loop lets go of the lock."""
return [path for path in sorted(folder.iterdir()) if path.suffix != ".lock"]
def a_loop(effects, **fields):
"""A loop in /r on effects, with fields in place of its defaults."""
home = pathlib.Path("/h")
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "listed": running_loops.Listed(home / "waiting", lambda items: None), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
return this_loop.Loop(**{**defaults, **fields}, effects=effects)
@@ -112,7 +98,6 @@ class FakeEffects:
def effects(self):
return Effects(
alive=lambda pid: True,
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
claude_on_terminal=self.on_terminal_claude,
discard_typed=lambda: self.calls.append(("discard_typed", None)),
@@ -120,13 +105,10 @@ class FakeEffects:
execv=self.execv,
git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)),
input=lambda prompt: self.answer("input", prompt),
input_or=self.input_or,
local_time=lambda seconds: f"<{seconds}>",
memory=self.memory,
new_id=lambda: ASK_ID,
now=lambda: NOW,
on_terminal=lambda: self.terminal,
pid=lambda: PID,
python=lambda args, cwd: self.answer("python", (args, cwd)),
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
stream_claude=self.stream,
@@ -140,14 +122,6 @@ class FakeEffects:
self.calls.append(("memory", None))
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
def input_or(self, prompt, other):
"""Answers from the input script as input does; a callable in the script gets other, the source of loop-inbox's answer."""
self.calls.append(("input", prompt))
answer = self.scripts["input"].pop(0)
if isinstance(answer, BaseException):
raise answer
return answer(other) if callable(answer) else answer
def on_terminal_claude(self, args, cwd, env):
self.terminal_environments.append(env)
self.terminal_folders.append(cwd)
@@ -288,7 +262,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, effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="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.", todo="", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -328,20 +302,6 @@ Judge: judge-model
Worker: {OFF_LADDER}
"""])
def test_shows_the_items_each_ruling_finds_the_worker_names_on_its_chunk_items_line(self):
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 14 (L 2, E + I 3), 3 (L 1, E + I 2)")
fake = FakeEffects(streams=[worker], claude=[judged("unfinished")])
shown = []
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
self.assertEqual(shown, [(14, 3)])
def test_shows_no_items_for_a_finished_chunk(self):
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 3")
fake = FakeEffects(streams=[worker], claude=[judged("finished")])
shown = []
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
self.assertEqual(shown, [])
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")])
@@ -770,25 +730,11 @@ class Interrupts(unittest.TestCase):
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), 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, run while the session's lock is held, as a running loop holds it."""
with contextlib.redirect_stderr(io.StringIO()) as said, session_lock.held(self.paths.waiting, str(self.session.id)):
answer = interrupt.interrupt(question, answer_here, self.session, self.paths.waiting, effects or fake.effects())
"""interrupt's answer and what it said."""
with contextlib.redirect_stderr(io.StringIO()) as said:
answer = interrupt.interrupt(question, answer_here, self.session, effects or fake.effects())
return answer, said.getvalue()
def asked(self):
return waiting(self.paths.waiting)
def ask(self, question="Which one?", state=None):
"""The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
return Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or Asking(resumed))
def opening(self, other):
"""loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer."""
[ask] = self.asked()
send(self.paths.waiting, ask, ClaudeOpening(INBOX))
return other()
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:
@@ -835,86 +781,6 @@ class Interrupts(unittest.TestCase):
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}"))
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
def typed(_):
self.assertEqual(self.asked(), [self.ask()])
return "Use B."
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self):
def answered(_, other):
[ask] = self.asked()
send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), Typed("Use A."))
self.assertIsNone(other())
send(self.paths.waiting, ask, Typed(" Use C. "))
return other()
fake = FakeEffects()
effects = dataclasses.replace(fake.effects(), input_or=answered)
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_takes_the_answer_typed_on_its_terminal_where_loop_inbox_cannot_list_the_question(self):
self.paths.waiting.parent.mkdir(parents=True)
self.paths.waiting.write_text("")
answer, said = self.put(FakeEffects(inputs=["Use B."]))
self.assertEqual(answer, "Use B.")
self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said)
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0]))
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"))
def test_makes_way_only_warns_where_loop_inbox_cannot_list_the_open_claude(self):
self.paths.waiting.parent.mkdir(parents=True)
self.paths.waiting.write_text("")
with contextlib.redirect_stderr(io.StringIO()) as said:
make_way(self.paths.waiting, self.ask(), INBOX, FakeEffects().effects())
self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said.getvalue())
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
def claude_ran(_):
# loop-inbox opens claude only once the loop lists it as open there.
self.assertEqual(self.asked(), [self.ask(state=OpenInInbox(INBOX))])
with open(self.transcript, "a") as handle:
handle.write(json.dumps(human("cut it")) + "\n")
send(self.paths.waiting, self.ask(), ClaudeEnded())
fake = FakeEffects(inputs=[self.opening])
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
self.assertEqual((fake.made("claude_on_terminal"), asks_and_answers(self.paths.waiting)), ([], []))
def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self):
looked, slept = [], []
def alive(pid):
looked.append(pid)
return pid == INBOX
def ended(seconds):
slept.append(seconds)
send(self.paths.waiting, self.ask(), ClaudeEnded())
fake = FakeEffects(inputs=[self.opening])
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended))
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX], [POLL_SECONDS]))
def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self):
looked = []
def alive(pid):
looked.append(pid)
# loop-inbox's process ends while the loop waits for its claude.
return pid == INBOX and len(looked) == 1
fake = FakeEffects(inputs=[self.opening])
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive))
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX, INBOX], [POLL_SECONDS]))
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
for typed, answer_here in (([" /talk "], True), ([], False)):
with self.subTest(typed=typed):
def ran(args):
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", OpenOnTerminal())])
return 0
fake = FakeEffects(inputs=typed, on_terminal_claude=[ran])
self.put(fake, answer_here, question="Cut 0.4.0?")
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_stops_when_nothing_was_typed_in_the_session(self):
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0])
@@ -937,8 +803,8 @@ class RoutingCheck(unittest.TestCase):
self.session = session.session_named("A log loop-claude", self.paths.claude_code_transcripts)
def loop(self, fake):
"""The loop in /code/log, whose questions loop-inbox lists."""
return a_loop(fake.effects(), root="/code/log", session=self.session, listed=running_loops.Listed(self.paths.waiting, lambda items: None), paths=self.paths)
"""The loop in /code/log."""
return a_loop(fake.effects(), root="/code/log", session=self.session, paths=self.paths)
def chunks(self, count, verdicts, project="log"):
"""count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches."""
@@ -957,19 +823,9 @@ class RoutingCheck(unittest.TestCase):
def check(self, fake):
"""What check_routing returns and says for a loop in /code/log."""
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
self.enterContext(session_lock.held(self.paths.waiting, str(self.session.id)))
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.loop(fake))
return stop, said.getvalue()
def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self):
self.chunks(5, 4)
question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}"
def ran(args):
self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, str(self.session.id), "/code/log", question, NOW, OpenOnTerminal())])
return 0
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD] * 2))
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
self.chunks(5, 3)
self.assertEqual(self.check(FakeEffects()), (None, ""))
@@ -1034,7 +890,6 @@ class RoutingCheck(unittest.TestCase):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD] * 2))
self.assertEqual(stop, Stop(1, f"could not start claude for the routing calls in {self.home / 'code' / 'claude-config'}, the setup's development clone: No such file or directory"))
self.assertEqual(asks_and_answers(self.paths.waiting), [])
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
def test_says_a_figure_it_cannot_write_and_goes_on(self):
@@ -1342,11 +1197,6 @@ class Steps(unittest.TestCase):
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_an_unfinished_chunk_keeps_the_items_its_verdict_found_taken_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), items_taken_in=(3,))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn((3, 12))), run_with.route)).items_taken_in, (3, 12))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)).items_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-fable-5-2", "low"), 3, 3, 4, escalated_at=5)
@@ -1402,12 +1252,6 @@ class Steps(unittest.TestCase):
class ChunkFacts(unittest.TestCase):
def test_names_the_routed_item_then_each_taken_in_once_by_its_tagline_on_the_default_branch(self):
self.assertEqual(running_loops.taken_items(TODO, 3, (99, 3, 99)), (Taken(3, "Do the next thing."), Taken(99, "")))
self.assertEqual(running_loops.taken_items(TODO, 0, (3,)), (Taken(3, "Do the next thing."),))
self.assertEqual(running_loops.taken_items(Failure("no todo.md"), 3, ()), (Taken(3, ""),))
self.assertEqual(running_loops.taken_items(TODO, 0, ()), ())
# The launcher beside which chunk_start finds /b/chunk-preflight.
LAUNCHER = pathlib.Path("/b/loop-claude")
@@ -1822,13 +1666,13 @@ class ChunkItems(unittest.TestCase):
self.assertEqual(chunk_items.named([prompt, written, mentioned]), ())
def test_takes_the_highest_l_and_e_plus_i_todo_md_scores_among_the_named_items(self):
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297 (L 1, E + I 2), 298, 400")], SCORED), TakenIn((297, 298, 400), 4, 7))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 400")], SCORED), TakenIn((400,)))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297 (L 1, E + I 2), 298, 400")], SCORED), TakenIn(4, 7))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 400")], SCORED), TakenIn())
self.assertEqual(chunk_items.taken_in([], SCORED), TakenIn())
def test_names_the_items_at_no_level_where_todo_md_cannot_be_read(self):
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], Failure("no todo.md")), TakenIn((297,)))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], "no items table"), TakenIn((297,)))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], Failure("no todo.md")), TakenIn())
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], "no items table"), TakenIn())
class Verdict(unittest.TestCase):
@@ -1927,7 +1771,7 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
def test_decodes_every_field_of_the_state_and_its_route(self):
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2)
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)})
@@ -1987,12 +1831,9 @@ 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(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="", items_taken_in=(12, 14))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), 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) | {"items_taken_in": taken_in})))
def test_drops_the_items_taken_in_that_a_loop_started_before_0_11_0_hands_on(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state)
def test_stops_when_the_reload_cannot_start_python(self):
with tempfile.TemporaryDirectory() as root:
+1 -3
View File
@@ -6,9 +6,7 @@ from claude_code.tokens import Tokens
@dataclasses.dataclass(frozen=True)
class TakenIn:
"""The todo.md 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."""
# Their IDs; loop-inbox lists them.
items: tuple[int, ...] = ()
"""The levels of the todo.md 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 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.
-44
View File
@@ -5,32 +5,22 @@ A change here, such as to how input reads a line, changes every tool that runs o
import dataclasses
import os
import pathlib
import select
import signal
import subprocess
import sys
import termios
import time
import typing
import uuid
from mattermost_dm.dm import dm, http_json
from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
# Seconds between a loop's looks for an answer from loop-inbox while it reads its terminal, and for the end of the claude loop-inbox opened.
POLL_SECONDS = 0.5
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
class InputOr(typing.Protocol):
"""Prints a prompt, then returns the line typed at the terminal, or the first answer that other returns, called every POLL_SECONDS. Raises EOFError where the input ends."""
def __call__[T](self, prompt: str, other: typing.Callable[[], T | None]) -> str | T: ...
class Streaming(typing.Protocol):
"""A started claude whose stream-json lines arrive as it works."""
@@ -41,8 +31,6 @@ class Streaming(typing.Protocol):
@dataclasses.dataclass(frozen=True)
class Effects:
# Whether the process with this pid still runs.
alive: typing.Callable[[int], bool]
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
# Drops what was typed on the terminal and not yet read.
@@ -52,15 +40,12 @@ class Effects:
execv: typing.Callable[[str, list[str]], None]
git: git_repo.Git
input: typing.Callable[[str], str]
input_or: InputOr
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
local_time: typing.Callable[[float], str]
# The machine's memory; None where it cannot be read.
memory: typing.Callable[[], Memory | None]
new_id: typing.Callable[[], str]
now: typing.Callable[[], float]
on_terminal: typing.Callable[[], bool]
pid: typing.Callable[[], int]
# Runs a Python script in a directory, as run_python does.
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
sleep: typing.Callable[[float], None]
@@ -81,7 +66,6 @@ class StreamingClaude:
def system_effects() -> Effects:
return Effects(
alive=alive,
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
claude_on_terminal=claude_on_terminal,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
@@ -89,13 +73,10 @@ def system_effects() -> Effects:
execv=os.execv,
git=git_repo.git,
input=input,
input_or=input_or,
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
memory=read_memory,
new_id=lambda: str(uuid.uuid4()),
now=time.time,
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
pid=os.getpid,
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
sleep=time.sleep,
stream_claude=StreamingClaude,
@@ -112,16 +93,6 @@ def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
signal.signal(signal.SIGINT, previous)
def alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]:
"""Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr."""
command = [sys.executable, *args]
@@ -133,21 +104,6 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
# On stderr, where input prints its prompt on a terminal.
print(prompt, end="", file=sys.stderr, flush=True)
while True:
if select.select([sys.stdin], [], [], POLL_SECONDS)[0]:
# On a terminal, one read returns at most one line, so nothing typed after it is buffered here, out of discard_typed's reach.
line = os.read(sys.stdin.fileno(), 65536)
if not line:
raise EOFError
return line.decode("utf-8", "replace").removesuffix("\n")
if (got := other()) is not None:
print(file=sys.stderr, flush=True) # Ends the prompt's line.
return got
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
body = text.lstrip("\n")
-10
View File
@@ -4,7 +4,6 @@ import io
import os
import pathlib
import signal
import subprocess
import sys
import tempfile
import time
@@ -70,15 +69,6 @@ class LocalTime(unittest.TestCase):
class Alive(unittest.TestCase):
def test_a_process_that_runs_is_alive_and_one_that_ended_is_not(self):
ended = subprocess.Popen([sys.executable, "-c", "pass"])
ended.wait()
# Unless this process runs as root, it may not signal pid 1, which still runs.
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
class ClaudeOnTerminal(unittest.TestCase):
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
caught = []
View File
-179
View File
@@ -1,179 +0,0 @@
"""What loop-inbox shows, and what each key does there: the core that main.py's curses screen runs.
How it shows the loops and a question was picked on 2026-10-28 by a bench of three readers seated as the README's
audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it: a block per
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone doesn't stop the loop.
A second bench, on 2026-10-29, picked the running loops' section: below the waiting loops, a line per loop with its
checkout and its number in the list above where it waits for an answer, then a line per item its chunk takes, with its ID and tagline.
"""
import dataclasses
import textwrap
import typing
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_state.running_loops import RunningLoop, Taken
from loop_state.waiting.talk import TALK
ENTER = "enter"
BACKSPACE = "backspace"
ESCAPE = "escape"
# Lines of a question the list shows; the answer screen shows as much as fits.
SHOWN_LINES = 2
QUIT = "q"
ANSWER_PROMPT = f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting):"
INDENT = " "
ELLIPSIS = "…"
NARROWEST = 20
@dataclasses.dataclass(frozen=True)
class Listing:
"""The waiting and running loops as they were when the human began typing a number, so a loop's number doesn't change while they type it."""
shown: tuple[Ask, ...] = ()
typed: str = ""
note: str = ""
running: tuple[RunningLoop, ...] = ()
@dataclasses.dataclass(frozen=True)
class Answering:
ask: Ask
typed: str = ""
Screen = Listing | Answering
@dataclasses.dataclass(frozen=True)
class Send:
ask: Ask
text: str
@dataclasses.dataclass(frozen=True)
class Open:
"""Opens the worker's claude session for /talk."""
ask: Ask
@dataclasses.dataclass(frozen=True)
class Quit:
pass
def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit:
"""What follows key, which is ENTER, BACKSPACE, ESCAPE or one character typed."""
match screen:
case Listing(shown, typed):
if key == QUIT and not typed:
return Quit()
if key == ENTER:
return picked(shown, typed)
if key == BACKSPACE:
return dataclasses.replace(screen, typed=typed[:-1], note="")
# isdigit would also take "²", which int() rejects.
return dataclasses.replace(screen, typed=typed + key, note="") if key.isdecimal() else screen
case Answering(ask, typed):
if key == ESCAPE or (key == ENTER and not typed.strip()):
return Listing()
if key == ENTER:
return Open(ask) if typed.strip() == TALK else Send(ask, typed.strip())
if key == BACKSPACE:
return Answering(ask, typed[:-1])
return Answering(ask, typed + key) if len(key) == 1 and key.isprintable() else screen
case _:
typing.assert_never(screen)
def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
if not typed:
return Listing()
number = int(typed)
if not 1 <= number <= len(shown):
return Listing(note=f"No loop has the number {number}.")
ask = shown[number - 1]
if not isinstance(ask.state, Asking):
return Listing(note=f"{ask.root}: claude is open {where_open(ask.state)}; answer there.")
return Answering(ask)
def where_open(state: OpenOnTerminal | OpenInInbox) -> str:
return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal"
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
"""The list, in lines of at most width characters, and its foot: the note, what the keys do, and the prompt for a number."""
count = len(screen.shown)
head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first."
lines = [*wrapped(head, width), ""]
for number, ask in enumerate(screen.shown, 1):
state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}"
lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width)
lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES)
lines.append("")
lines += running_lines(screen.running, screen.shown, width)
ask_for = "Type a number and Enter to answer that loop; " if count else ""
return lines, [*wrapped(screen.note, width), *wrapped(f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", width), *typed_after(">", screen.typed, width)]
def running_lines(running: tuple[RunningLoop, ...], shown: tuple[Ask, ...], width: int) -> list[str]:
"""Each running loop's checkout, with its number in the waiting list where it waits for an answer, and a line per item its chunk takes."""
if not running:
return ["No loop runs."]
numbers = {ask.session: number for number, ask in enumerate(shown, 1)}
lines = wrapped(f"Running: {len(running)} loop{'s' if len(running) > 1 else ''}", width)
for loop in running:
waits_as = f", waiting as [{numbers[loop.session]}]" if loop.session in numbers else ""
lines += wrapped(f"- {loop.root}{waits_as}", width)
for item in loop.items or (None,):
lines += cut(wrapped(item_line(item), width - len(INDENT) - len(ELLIPSIS)), 1)
return lines
def item_line(item: Taken | None) -> str:
if item is None:
return "no todo.md item yet"
return f"item {item.id}: {item.tagline}" if item.tagline else f"item {item.id}"
def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
"""The question, in lines of at most width characters, and its foot, the prompt for the answer."""
ask = screen.ask
head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):"
return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width)
def fitted(lines: list[str], foot: list[str], height: int) -> list[str]:
"""lines, then foot, cut to height: lines lose their end first, and the cut is marked with an ellipsis."""
if len(lines) + len(foot) <= height:
return [*lines, *foot]
return [*lines[: max(height - len(foot) - 1, 0)], ELLIPSIS, *foot][-height:]
def wrapped(text: str, width: int) -> list[str]:
return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, NARROWEST)) or [""]]
def typed_after(prompt: str, typed: str, width: int) -> list[str]:
"""prompt wrapped to width, then what the human typed after it, cut every width characters so that each space typed shows."""
*lines, last = wrapped(prompt, width)
line = f"{last} {typed}"
step = max(width, NARROWEST)
return [*lines, *(line[start : start + step] for start in range(0, len(line), step))]
def cut(lines: list[str], count: int) -> list[str]:
"""The first count lines, indented; a cut is marked with an ellipsis."""
shown = [f"{INDENT}{line}" for line in lines[:count]]
return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown
def waited(seconds: float) -> str:
minutes = int(seconds // 60)
if minutes < 60:
return f"{minutes} min"
hours, minutes = divmod(minutes, 60)
if hours < 24:
return f"{hours} h {minutes} min"
days, hours = divmod(hours, 24)
return f"{days} d {hours} h"
-189
View File
@@ -1,189 +0,0 @@
"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here.
Below them, list every loop-claude that runs and the todo.md items its chunk takes.
usage: loop-inbox
Each loop-claude lists its interrupt here, as well as on its own terminal, until it is answered or
the loop stops. The list shows each loop's checkout, when it asked and how long it has waited, and
the question's first lines; it refreshes every second. Type a loop's number and Enter to see as much
of its question as fits; the loop's terminal shows it whole. Answer as on the loop's terminal:
- A line and Enter sends it to that loop, which goes on with it. Of a pasted answer, only the first
line is sent, and the rest is dropped; a longer answer goes through /talk.
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what
you typed; if you typed no answer, the loop stops.
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
loop-inbox running. A loop with claude open, for a release ready to cut, the routing calls or a
/talk, says where, and is answered there. A loop whose process is gone drops off the list. A loop
asking for its project's model, as on a project's first run, asks on its own terminal only. q quits
loop-inbox; the loops keep waiting.
Below the questions, loop-inbox lists each running loop: its checkout, its number in the list
above where it waits for an answer, and a line per todo.md item its chunk takes, with the item's
tagline on the default branch. A loop whose process is gone drops off this list too.
The loops' questions are files in ~/.local/state/loop-claude, read and written as
bin/loop_state/waiting/ describes; the running loops are files beside them, as
bin/loop_state/running_loops.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
import contextlib
import curses
import dataclasses
import pathlib
import sys
import typing
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_state.waiting.ask import Ask, Asking, read_ask
from loop_state.waiting.listing import ask_file, drop_ended, waiting
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_state.waiting.answers import ClaudeEnded, send, Typed
from loop_state.running_loops import drop_ended_loops, running_loops
from loop_effects.effects import Effects, system_effects
from failure import Failure
from loop_state.hand_over import hand_over
from loop_state.paths import Paths, paths_from
from loop_state.session_lock import running
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
REFRESH_MS = 1000
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
def main(argv: list[str], home: pathlib.Path) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv:
print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr)
return 2
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
return 2
# curses may hold keys it has read ahead, which only flushinp drops.
effects = dataclasses.replace(system_effects(), discard_typed=curses.flushinp)
try:
curses.wrapper(lambda window: run(window, lambda: off_screen(window), paths_from(home), effects))
except KeyboardInterrupt:
pass
return 0
def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, effects: Effects) -> None:
folder = paths.waiting
window.timeout(REFRESH_MS)
screen: Screen = Listing()
while True:
drop_ended(folder)
drop_ended_loops(folder)
screen = entered(screen, refreshed(screen, folder), effects)
draw(window, screen, effects)
try:
key = window.get_wch()
except curses.error:
continue # No key within REFRESH_MS.
after: Screen
match pressed(screen, key_name(key)):
case Quit():
return
case Send(ask, text):
after = Listing(note=sent(folder, ask, text))
case Open(ask):
after = Listing(note=opened(screen_off, paths, ask, effects))
case Listing() | Answering() as next_screen:
after = next_screen
screen = entered(screen, after, effects)
def entered(before: Screen, after: Screen, effects: Effects) -> Screen:
"""after, the screen that follows before. Leaving the answer screen drops the keys typed ahead, since on the list the rest of a pasted answer would pick a loop and answer it."""
if isinstance(before, Answering) and isinstance(after, Listing):
effects.discard_typed()
return after
def key_name(key: str | int) -> str:
"""inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow."""
return KEYS.get(key, key if isinstance(key, str) else "")
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
"""screen with the loops as they wait and run now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
match screen:
case Listing(_, "", note):
return Listing(tuple(waiting(folder)), "", note, tuple(running_loops(folder)))
case Answering(ask) if not still_waits(folder, ask):
return Listing(note=no_longer_waits(ask))
return screen
def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
height, columns = window.getmaxyx()
# The screen's last cell cannot be written without an error, so lines leave the last column empty.
width = columns - 1
now = effects.now()
lines, foot = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width)
window.erase()
for row, line in enumerate(fitted(lines, foot, height)):
# addnstr counts characters, not cells, so a line of wide characters, such as emoji, can still run into the last cell.
with contextlib.suppress(curses.error):
window.addnstr(row, 0, line, width)
window.refresh()
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether ask's loop still runs and still waits for an answer from loop-inbox."""
now = read_ask(ask_file(folder, ask.session))
return now is not None and now.id == ask.id and isinstance(now.state, Asking) and running(folder, ask.session)
def no_longer_waits(ask: Ask) -> str:
return f"{ask.root} no longer waits for that answer: it was answered elsewhere, or stopped."
def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
"""Sends text to the loop that asked ask, and says what came of it."""
if not still_waits(folder, ask):
return no_longer_waits(ask)
if unsent := send(folder, ask, Typed(text)):
return f"Could not send the answer to {ask.root}: {unsent.reason}"
return f"Sent to {ask.root}."
def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, ask: Ask, effects: Effects) -> str:
"""Opens the worker's claude session on this terminal, inside screen_off, once the loop has made way for it, and says what came of it."""
folder = paths.waiting
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
return no_longer_waits(ask)
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
if isinstance(claimed, Failure):
return f"Could not open claude for {ask.root}: {claimed.reason}"
if not claimed:
return f"Could not open claude for {ask.root}: the loop was answered elsewhere or stopped, or didn't respond within {MAKE_WAY_SECONDS:g} s. If it is still listed, pick it again."
with screen_off():
try:
unstarted = hand_over(ask.state.talk, effects)
finally:
unsent = send(folder, ask, ClaudeEnded())
# The loop goes on only where the human typed in the worker's session, as interrupt.human_typed checks.
said = f"Could not start claude for {ask.root}: {unstarted.reason}. The loop stops." if unstarted else f"claude for {ask.root} has ended; the loop goes on if you typed there, and stops if you didn't."
# The loop also stops waiting for claude once loop-inbox's process ends.
return f"{said} Could not tell the loop that claude ended: {unsent.reason}; it waits until you quit loop-inbox." if unsent else said
@contextlib.contextmanager
def off_screen(window: curses.window) -> typing.Iterator[None]:
"""Hands the terminal to another program, and draws loop-inbox again once it ends."""
curses.def_prog_mode()
curses.endwin()
try:
yield
finally:
curses.reset_prog_mode()
window.refresh()
-610
View File
@@ -1,610 +0,0 @@
import contextlib
import dataclasses
import io
import json
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_state.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask
from loop_state.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_state.hand_over import ClaudeCommand
from failure import Failure
from loop_inbox import inbox, main
from loop_state.paths import paths_from
from loop_state import running_loops, session_lock
from loop_state.running_loops import RunningLoop, Taken
from loop_effects.effects import system_effects
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
# The pid of this loop-inbox.
INBOX = 4343
ANSWERED_ON_TERMINAL = object()
def asked(session, root, question="Which one?", at=100.0, state=ASKING):
return Ask(f"ask-{session}", session, root, question, at, state)
def loops_hold(test, folder, *sessions):
"""Holds each session's lock until the test ends, as a running loop does."""
for session in sessions:
test.enterContext(session_lock.held(folder, session))
def asks_and_answers(folder):
return sorted(path.name for path in folder.iterdir() if path.suffix != ".lock")
def keyed(screen, *keys):
for key in keys:
screen = inbox.pressed(screen, key)
return screen
class OutOfKeys(Exception):
pass
class Window:
"""A curses window that records the lines drawn on it, and hands out keys in turn, running each callable among them as it comes."""
def __init__(self, keys=(), height=24, width=80):
self.keys, self.height, self.width = list(keys), height, width
self.lines = {}
def getmaxyx(self):
return self.height, self.width
def timeout(self, milliseconds):
pass
def get_wch(self):
while self.keys and callable(self.keys[0]):
self.keys.pop(0)()
if not self.keys:
raise OutOfKeys
return self.keys.pop(0)
def drop_typed(self):
"""Drops the keys not yet read, as curses.flushinp does."""
self.keys.clear()
def erase(self):
self.lines = {}
def addnstr(self, row, column, text, count):
self.lines[row] = text[:count]
def refresh(self):
pass
class Answers(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
loops_hold(self, self.folder, "s1", "s2")
def answer(self, number, text):
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
action = keyed(Listing(tuple(waiting(self.folder))), *number, ENTER, *text, ENTER)
self.assertIsInstance(action, Send)
return main.sent(self.folder, action.ask, action.text)
def test_two_waiting_loops_each_get_their_own_answer(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
for ask in (bender, log):
publish(self.folder, ask)
self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.")
self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.")
self.assertEqual((answered(self.folder, log), answered(self.folder, bender)), (Typed("Use A."), Typed("Use B.")))
def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
for ask in (log, bender):
publish(self.folder, ask)
picked = keyed(Listing(tuple(waiting(self.folder))), "1", ENTER, "A", ENTER)
# log is answered on its terminal before the answer typed here is sent; bender is now first.
withdraw(self.folder, "s1")
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
self.assertEqual(asks_and_answers(self.folder), ["s2.json"])
def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self):
log = asked("s1", "/code/log")
for ask in (log, asked("s3", "/code/bender")):
publish(self.folder, ask)
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a."))
def test_the_list_shows_the_loops_running_now(self):
self.enterContext(running_loops.shown_running(self.folder, "s9", "/code/web", system_effects()))
self.assertEqual(main.refreshed(Listing(), self.folder), Listing(running=(RunningLoop("s9", "/code/web", ()),)))
def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
typing = keyed(Listing((log, bender)), "2")
publish(self.folder, bender)
self.assertEqual(main.refreshed(typing, self.folder), typing)
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
for state, where in ((OpenOnTerminal(), "on its terminal"), (OpenInInbox(7), "in loop-inbox")):
with self.subTest(where=where):
self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
def test_an_ask_file_says_when_the_loop_asked_as_an_iso_utc_datetime(self):
ask = asked("s1", "/code/log", at=100)
publish(self.folder, ask)
self.assertEqual(json.loads(ask_file(self.folder, "s1").read_text())["asked"], "1970-01-01T00:01:40Z")
self.assertEqual(read_ask(ask_file(self.folder, "s1")), ask)
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
ask = asked("s1", "/code/log")
publish(self.folder, ask)
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
publish(self.folder, dataclasses.replace(ask, id="a later ask"))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self):
ask = asked("s3", "/code/bender")
publish(self.folder, ask)
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped."))
def claim(self, ask, loop_does):
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
tenths = [0]
def sleep(seconds):
if not tenths[0]:
loop_does()
tenths[0] += round(seconds * 10)
return claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10
def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self):
ask = asked("s1", "/code/log")
def made_way_for_the_claim():
claim = answered(self.folder, ask)
if isinstance(claim, ClaudeOpening):
publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid)))
for loop_does, claimed in (
(made_way_for_the_claim, (True, 0.1)),
(lambda: withdraw(self.folder, "s1"), (False, 0.1)),
(lambda: publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)),
(lambda: publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)),
(lambda: None, (False, MAKE_WAY_SECONDS)),
):
with self.subTest(claimed=claimed):
publish(self.folder, ask)
self.assertEqual(self.claim(ask, loop_does), claimed)
def test_a_claim_the_loop_did_not_make_way_for_in_time_is_taken_back(self):
ask = asked("s1", "/code/log")
publish(self.folder, ask)
self.claim(ask, lambda: None)
# A loop that reads it late ends its wait at once, as for a claude that has ended.
self.assertEqual((answered(self.folder, ask), claude_ended(self.folder, ask)), (None, True))
def never_opens(args, cwd, env):
raise AssertionError("claude opened")
class Opens(unittest.TestCase):
def setUp(self):
home = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, home)
self.paths = paths_from(home)
self.ask = asked("s1", "/code/log")
loops_hold(self, self.paths.waiting, "s1")
publish(self.paths.waiting, self.ask)
def open(self, claude, loop_shows=OpenInInbox(INBOX)):
"""What /talk in loop-inbox says for self.ask, whose loop shows loop_shows once claim_talk has asked it to make way; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended."""
def loop_looks(_):
publish(self.paths.waiting, dataclasses.replace(self.ask, state=loop_shows))
effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=loop_looks)
try:
with contextlib.redirect_stderr(io.StringIO()):
return main.opened(contextlib.nullcontext, self.paths, self.ask, effects)
finally:
self.ended = claude_ended(self.paths.waiting, self.ask)
def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self):
def unstarted(args, cwd, env):
raise OSError(2, "No such file or directory")
for claude, said in (
(lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't."),
(unstarted, "Could not start claude for /code/log: No such file or directory. The loop stops."),
):
with self.subTest(said=said):
publish(self.paths.waiting, self.ask)
self.assertEqual(self.open(claude), said)
self.assertTrue(self.ended)
def test_says_the_loop_waits_for_loop_inbox_to_quit_where_it_cannot_tell_it_that_claude_ended(self):
def folder_lost(args, cwd, env):
shutil.rmtree(self.paths.waiting)
self.paths.waiting.write_text("")
said = "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't. Could not tell the loop that claude ended: Not a directory; it waits until you quit loop-inbox."
self.assertEqual(self.open(folder_lost), said)
def test_opens_no_claude_for_a_loop_that_takes_talk_on_its_terminal_first(self):
said = "Could not open claude for /code/log: the loop was answered elsewhere or stopped, or didn't respond within 5 s. If it is still listed, pick it again."
self.assertEqual(self.open(never_opens, loop_shows=OpenOnTerminal()), said)
def test_opens_no_claude_and_sends_nothing_to_a_loop_that_no_longer_waits(self):
withdraw(self.paths.waiting, "s1")
self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_tells_the_loop_when_claude_is_interrupted(self):
def interrupted(args, cwd, env):
raise KeyboardInterrupt
with self.assertRaises(KeyboardInterrupt):
self.open(interrupted)
self.assertTrue(self.ended)
class Typing(unittest.TestCase):
def typed(self, *keys):
"""What the log and bender loops get once keys are typed into loop-inbox, which lists log first. ANSWERED_ON_TERMINAL among the keys stands for log being answered on its terminal. Fails where loop-inbox quits before the keys run out."""
with tempfile.TemporaryDirectory() as home:
paths = paths_from(pathlib.Path(home))
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
loops_hold(self, paths.waiting, "s1", "s2")
for ask in (log, bender):
publish(paths.waiting, ask)
def answered_on_terminal():
withdraw(paths.waiting, "s1")
window = Window(answered_on_terminal if key is ANSWERED_ON_TERMINAL else key for key in keys)
def made_way(seconds):
publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX)))
effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()):
main.run(window, contextlib.nullcontext, paths, effects)
return answered(paths.waiting, log), answered(paths.waiting, bender)
def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self):
# Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit.
for case, keys, got in (
("a pasted answer", "1\nYes.\nSee item 2.\nThen release.\n", (Typed("Yes."), None)),
("a pasted answer with a line that would quit", "1\nOk.\nquick check first\n", (Typed("Ok."), None)),
("/talk", "1\n/talk\n2\nUse B.\n", (None, None)),
("a paste that opens with an empty line", "1\n\nSee item 2.\nThen release.\n", (None, None)),
("an answer typed as log is answered on its terminal", ["1", "\n", "U", "s", "e", ANSWERED_ON_TERMINAL, *" option 1.\nThen release.\n"], (None, None)),
):
with self.subTest(case):
self.assertEqual(self.typed(*keys), got)
class Keys(unittest.TestCase):
def test_the_list_takes_a_number_and_quits_on_q(self):
ask = asked("s1", "/code/log")
for keys, after in (
(("q",), Quit()),
(("1", "q"), Listing((ask,), "1")),
(("1", "2", "3", BACKSPACE), Listing((ask,), "12")),
(("x",), Listing((ask,))),
(("²",), Listing((ask,))),
((ENTER,), Listing()),
(("2", ENTER), Listing(note="No loop has the number 2.")),
(("1", ENTER), Answering(ask)),
):
with self.subTest(keys=keys):
self.assertEqual(keyed(Listing((ask,)), *keys), after)
def test_a_number_typed_keeps_the_running_loops_shown_and_clears_the_note(self):
running = (RunningLoop("s1", "/code/log", ()),)
self.assertEqual(keyed(Listing(note="No loop has the number 7.", running=running), "1", "2", BACKSPACE), Listing((), "1", "", running))
self.assertEqual(keyed(Listing(typed="1", note="No loop has the number 7.", running=running), BACKSPACE), Listing((), "", "", running))
def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self):
ask = asked("s1", "/code/log")
for keys, after in (
((*" Use B. ", ENTER), Send(ask, "Use B.")),
((*" /talk", ENTER), Open(ask)),
(("U", "s", "e", "x", BACKSPACE), Answering(ask, "Use")),
((" ", ENTER), Listing()),
(("U", ESCAPE), Listing()),
(("\t",), Answering(ask)),
):
with self.subTest(keys=keys):
self.assertEqual(keyed(Answering(ask), *keys), after)
def test_curses_keys_get_inboxs_names(self):
for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")):
with self.subTest(key=key):
self.assertEqual(main.key_name(key), name)
class Waiting(unittest.TestCase):
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
with tempfile.TemporaryDirectory() as folder:
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal())
loops_hold(self, pathlib.Path(folder), "s1", "s2")
for ask in (late, early, stopped):
publish(pathlib.Path(folder), ask)
pathlib.Path(folder, "s4.json").write_text("{")
pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}')
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
self.assertEqual(waiting(pathlib.Path(folder)), [early, late])
def test_drops_and_removes_the_ask_a_killed_loop_left_behind(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, session_lock, listed, system_effects\nwith session_lock.held(pathlib.Path(sys.argv[1]), 's1'), listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)"
loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE)
self.addCleanup(loop.wait)
self.addCleanup(loop.kill)
loop.stdout.readline()
send(folder, asked("s1", "/a"), Typed("Use A."))
self.assertEqual(waiting(folder), [asked("s1", "/a")])
# SIGKILL runs none of the loop's cleanup.
loop.kill()
loop.wait()
self.assertEqual(waiting(folder), [])
drop_ended(folder)
self.assertEqual(asks_and_answers(folder), [])
def test_loop_inbox_removes_a_killed_loops_ask_answer_and_running_file_as_it_looks(self):
with tempfile.TemporaryDirectory() as home:
paths = paths_from(pathlib.Path(home))
ask = asked("s1", "/a")
publish(paths.waiting, ask)
send(paths.waiting, ask, Typed("Use A."))
running_loops.running_file(paths.waiting, "s1").write_text(json.dumps({"root": "/a", "items": []}))
main.run(Window("q"), contextlib.nullcontext, paths, system_effects())
self.assertEqual(asks_and_answers(paths.waiting), [])
def test_removes_only_the_asks_answers_and_running_files_whose_loop_has_ended_each_by_its_own_module(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
loops_hold(self, folder, "s1")
for ask in (asked("s1", "/a"), asked("s2", "/b")):
publish(folder, ask)
send(folder, ask, Typed("Use A."))
for session in ("s1", "s2", "s3"):
running_loops.running_file(folder, session).write_text(json.dumps({"root": "/a", "items": []}))
drop_ended(folder)
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running", "s2.running", "s3.running"])
running_loops.drop_ended_loops(folder)
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running"])
def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self):
with tempfile.TemporaryDirectory() as temp:
ask = asked("s1", "/a")
for pid in (0, -1):
with self.subTest(pid=pid):
send(pathlib.Path(temp), ask, ClaudeOpening(pid))
self.assertIsNone(answered(pathlib.Path(temp), ask))
def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self):
with tempfile.TemporaryDirectory() as temp:
path = ask_file(pathlib.Path(temp), "s1")
publish(path.parent, asked("s1", "/a"))
good = json.loads(path.read_text())
self.assertEqual(read_ask(path), asked("s1", "/a"))
for field, value in (
("id", 1),
("session", "s2"),
("root", None),
("question", 3),
("asked", "noon"),
("asked", 100.0),
("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}),
("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}),
):
with self.subTest(field=field, value=value):
path.write_text(json.dumps(good | {field: value}))
self.assertIsNone(read_ask(path))
def test_withdraw_says_what_it_cannot_remove(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp, "a file")
folder.write_text("")
self.assertEqual(withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory"))
def test_a_message_reaches_only_the_ask_it_names(self):
with tempfile.TemporaryDirectory() as temp:
folder, ask = pathlib.Path(temp), asked("s1", "/a")
another = dataclasses.replace(ask, id="another")
for message, answer, ended in ((Typed("A"), Typed("A"), False), (ClaudeOpening(7), ClaudeOpening(7), False), (ClaudeEnded(), None, True)):
with self.subTest(message=message):
send(folder, ask, message)
self.assertEqual((answered(folder, ask), claude_ended(folder, ask)), (answer, ended))
self.assertEqual((answered(folder, another), claude_ended(folder, another)), (None, False))
class RunningLoops(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
self.effects = dataclasses.replace(system_effects(), sleep=lambda seconds: None)
def test_lists_a_loop_with_the_items_it_shows_until_it_ends(self):
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as listed:
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
listed.show((Taken(255, "Have loop-inbox list every running loop."),))
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop."),))])
self.assertEqual(running_loops.running_loops(self.folder), [])
def test_lists_the_loops_by_checkout_and_leaves_out_one_that_was_killed_or_whose_file_cannot_be_read(self):
# Five, so the order the files are found in is unlikely to be the order by checkout.
for session, root in (("s1", "/code/web"), ("s2", "/code/c"), ("s7", "/code/a"), ("s8", "/code/z"), ("s9", "/code/m")):
self.enterContext(running_loops.shown_running(self.folder, session, root, self.effects))
# A killed loop leaves its file behind, and its lock free.
(self.folder / "s3.running").write_text(json.dumps({"root": "/code/old", "items": []}))
for session, content in (("s4", "{"), ("s5", json.dumps({"root": "/code/x", "items": [{"id": "1", "tagline": ""}]})), ("s6", json.dumps({"root": "/code/x"})), ("s10", json.dumps({"root": "/code/x", "items": [{"id": True, "tagline": ""}]}))):
self.enterContext(session_lock.held(self.folder, session))
(self.folder / f"{session}.running").write_text(content)
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s7", "/code/a", ()), RunningLoop("s2", "/code/c", ()), RunningLoop("s9", "/code/m", ()), RunningLoop("s1", "/code/web", ()), RunningLoop("s8", "/code/z", ())])
def test_a_second_loop_on_the_session_warns_and_leaves_the_first_listed_with_its_question(self):
ask = asked("s1", "/code/log")
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as first:
publish(first.folder, ask)
with contextlib.redirect_stderr(io.StringIO()) as said:
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as second:
second.show((Taken(1, "Do it."),))
with listed(second.folder, asked("s1", "/code/log", question="Mine?"), self.effects):
self.assertEqual(waiting(self.folder), [ask])
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(self.folder, 's1')}", said.getvalue())
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
self.assertEqual(waiting(self.folder), [ask])
self.assertEqual(list((self.folder / "unlisted").iterdir()), [])
def test_takes_the_lock_once_loop_inbox_lets_go_of_it(self):
# loop-inbox holds the lock for a moment as it checks whether the loop runs.
looking = contextlib.ExitStack()
looking.enter_context(session_lock.held(self.folder, "s1"))
with running_loops.shown_running(self.folder, "s1", "/code/log", dataclasses.replace(self.effects, sleep=lambda seconds: looking.close())):
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
class Shown(unittest.TestCase):
def drawn(self, screen, window):
"""The lines draw puts on window for screen, 3700 s after the epoch."""
main.draw(window, screen, dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: 3700))
return [window.lines[row] for row in range(len(window.lines))]
def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self):
log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0)
cut = asked("s2", "/code/c", "Cut 0.4.0?\nIts changelog is ready.", at=3600 * 25, state=OpenInInbox(INBOX))
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 50)
self.assertEqual(lines, ([
"2 loops wait for you, oldest first.",
"",
"[1] /code/log, waiting since <0> (1 d 2 h)",
" Which store should the cache use: Redis or",
" SQLite? Redis is already deployed for…",
"",
"[2] /code/c, waiting since <90000> (1 h 2 min);",
"claude is open in loop-inbox",
" Cut 0.4.0?",
" Its changelog is ready.",
"",
"No loop runs.",
], [
"Type a number and Enter to answer that loop; q",
"quits loop-inbox, and the loops keep waiting.",
"> 1",
]))
def test_the_running_loops_follow_the_waiting_ones_each_with_the_items_its_chunk_takes(self):
log = asked("s1", "/code/log", "Which one?", at=0)
running = (
RunningLoop("s2", "/code/c", (Taken(12, "Accept undefined in MetadataValue and drop such keys on output."), Taken(14, ""))),
RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop-claude on the machine."),)),
RunningLoop("s3", "/code/web", ()),
)
lines, _ = inbox.listing_lines(Listing((log,), running=running), 120, lambda seconds: f"<{seconds}>", 50)
self.assertEqual(lines, [
"1 loop waits for you.",
"",
"[1] /code/log, waiting since <0> (2 min)",
" Which one?",
"",
"Running: 3 loops",
"- /code/c",
" item 12: Accept undefined in MetadataValue…",
" item 14",
"- /code/log, waiting as [1]",
" item 255: Have loop-inbox list every running…",
"- /code/web",
" no todo.md item yet",
])
def test_the_running_section_counts_one_loop(self):
lines, _ = inbox.listing_lines(Listing(running=(RunningLoop("s1", "/code/log", ()),)), 0, str, 79)
self.assertEqual(lines, ["No loop waits for you.", "", "Running: 1 loop", "- /code/log", " no todo.md item yet"])
def test_an_empty_list_says_no_loop_waits_or_runs(self):
self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", "", "No loop runs."], ["Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "]))
def test_the_answer_screen_at_80_columns_shows_every_character_of_each_line_and_says_what_enter_alone_does(self):
# The question's first line has 80 characters, one more than a line drawn at 80 columns holds.
ask = asked("s1", "/code/log", "The changelog lists four fixes and three new tools, so the next release is 0.6.0\n\nCut it?", at=100)
self.assertEqual(self.drawn(Answering(ask, "Yes"), Window(width=80)), [
"/code/log, waiting since <100> (1 h 0 min):",
"",
"The changelog lists four fixes and three new tools, so the next release is",
"0.6.0",
"",
"Cut it?",
"",
"Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps",
"waiting): Yes",
])
def test_an_answer_longer_than_its_line_goes_on_below_it_with_every_space_typed(self):
typed = "Use B, as the cache then runs next to the sessions it serves and then cut 0.6.0."
lines = self.drawn(Answering(asked("s1", "/code/log", "A or B?", at=100), typed), Window(width=80))
self.assertEqual(lines[-2:], ["waiting): Use B, as the cache then runs next to the sessions it serves and then", " cut 0.6.0."])
def test_a_line_that_runs_into_the_screens_last_cell_leaves_the_screen_drawn(self):
class Refusing(Window):
"""Refuses the screen's last row, as curses refuses a line of wide characters, such as emoji, that runs into the last cell."""
def addnstr(self, row, column, text, count):
super().addnstr(row, column, text, count)
if row == self.height - 1:
raise main.curses.error("addnwstr() returned ERR")
self.assertEqual(self.drawn(Listing(), Refusing(height=3)), ["…", "q quits loop-inbox, and the loops keep waiting.", "> "])
def test_a_screen_too_short_keeps_the_foot_and_marks_the_cut(self):
for lines, foot, height, shown in (
(["a", "b", "c"], ["> "], 4, ["a", "b", "c", "> "]),
(["a", "b", "c"], ["> "], 3, ["a", "…", "> "]),
(["a", "b", "c"], ["n", "> "], 4, ["a", "…", "n", "> "]),
(["a", "b", "c", "d"], ["n", "h", "> "], 2, ["h", "> "]),
):
with self.subTest(lines=lines, foot=foot, height=height):
self.assertEqual(inbox.fitted(lines, foot, height), shown)
def test_a_wait_reads_in_minutes_under_an_hour_and_in_hours_under_a_day(self):
for seconds, read in ((3599, "59 min"), (3600, "1 h 0 min"), (86399, "23 h 59 min"), (86400, "1 d 0 h")):
with self.subTest(seconds=seconds):
self.assertEqual(inbox.waited(seconds), read)
class Terminal(io.StringIO):
def isatty(self):
return True
class Starts(unittest.TestCase):
def started(self, argv, stdin, stdout):
"""What main returns for argv, run with stdin and stdout, and what it writes to stderr."""
stderr = io.StringIO()
with unittest.mock.patch.object(sys, "stdin", stdin), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
code = main.main(argv, pathlib.Path("/no home"))
return code, stderr.getvalue()
def test_help_prints_the_docstring(self):
for flag in ("-h", "--help"):
with self.subTest(flag):
stdout = io.StringIO()
self.assertEqual(self.started([flag], io.StringIO(), stdout), (0, ""))
self.assertEqual(stdout.getvalue(), f"{main.__doc__.strip()}\n")
def test_exits_2_on_an_unknown_argument_or_off_a_terminal(self):
off_a_terminal = "loop-inbox: stdin or stdout is not a terminal; run it on one\n"
for case, argv, stdin, stdout, said in (
("an unknown argument", ["--x"], Terminal(), Terminal(), "loop-inbox: unknown argument --x; usage: loop-inbox\n"),
("stdout off a terminal", [], Terminal(), io.StringIO(), off_a_terminal),
("stdin off a terminal", [], io.StringIO(), Terminal(), off_a_terminal),
):
with self.subTest(case):
self.assertEqual(self.started(argv, stdin, stdout), (2, said))
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -1,4 +1,4 @@
"""The files loop-claude and loop-inbox share: a running loop lists itself (running_loops.py, session_lock.py) and its question (waiting/), and both read the same paths (paths.py) and open claude for the human the same way (hand_over.py).
"""What loop-claude and the tools that replay its runs share: where its files are (paths.py), and how it opens claude for the human on its terminal (hand_over.py).
A change here changes both tools. It doesn't import anything from loop_claude/.
It doesn't import anything from loop_claude/.
"""
+1 -1
View File
@@ -19,7 +19,7 @@ def claude_args(rung: Rung, args: list[str]) -> list[str]:
# CLAUDE_CODE_SANDBOXED, which Claude Code doesn't document, skips its trust dialog without writing ~/.claude.json:
# docs/decisions.md → `loop-claude: every claude it or loop-inbox opens on a terminal has CLAUDE_CODE_SANDBOXED set`.
# docs/decisions.md → `loop-claude: every claude it opens on a terminal has CLAUDE_CODE_SANDBOXED set`.
def hand_over(command: ClaudeCommand, effects: Effects) -> Failure | None:
"""Runs claude on the terminal as command says, with CLAUDE_CODE_SANDBOXED=1 added to its environment; the failure is why claude could not start."""
try:
-3
View File
@@ -11,8 +11,6 @@ class Paths:
home: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
# Where a loop shows its interrupt to loop-inbox (bin/loop_state/waiting/).
waiting: pathlib.Path
def paths_from(home: pathlib.Path) -> Paths:
@@ -24,5 +22,4 @@ def paths_from(home: pathlib.Path) -> Paths:
home=home,
model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json",
waiting=home / ".local" / "state" / "loop-claude",
)
-137
View File
@@ -1,137 +0,0 @@
"""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 its session's lock (session_lock.py) in Paths.waiting for its whole run. Beside the lock it keeps
<session>.running, which holds the loop's checkout and each item its chunk takes, by ID and by its tagline on the default
branch as last fetched. The items are the one the chunk was routed on, then those the worker names on its latest
`Chunk items:` line, each listed once. loop-inbox lists a loop, and its question (waiting/), only while the loop holds its
lock. So a killed loop drops off the list, though its files stay until loop-inbox removes them: <session>.running
through drop_ended_loops here, and the question through waiting.listing.drop_ended.
"""
import contextlib
import dataclasses
import json
import pathlib
import shutil
import typing
from loop_effects.effects import Effects, say
from loop_state.session_lock import ended, held, running
from failure import Failure
from release_plan.todo_table import items
from text_files.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 checks whether the loop has ended.
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 can't be read or 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 until the chunk has an item.
items: tuple[Taken, ...]
Show = typing.Callable[[tuple[Taken, ...]], None]
@dataclasses.dataclass(frozen=True)
class Listed:
"""How a running loop shows itself in loop-inbox."""
# Where the loop keeps its questions: Paths.waiting where it holds its session's lock. Where another loop on the session holds the lock, a folder of its own that loop-inbox doesn't read, so this loop never touches the other's questions.
folder: pathlib.Path
show: Show
def running_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.running"
@contextlib.contextmanager
def shown_running(folder: pathlib.Path, session: str, root: str, effects: Effects) -> typing.Iterator[Listed]:
"""Lists the loop in loop-inbox as running while the with block runs, at first with no item. A failure only warns: the loop runs unlisted, and its questions are answered on its terminal."""
with contextlib.ExitStack() as stack:
if unlocked := locked_soon(stack, folder, session, effects):
say(f"loop-inbox cannot list this loop or its questions: {unlocked.reason}", effects)
unlisted = folder / "unlisted" / effects.new_id()
try:
yield Listed(unlisted, lambda items: None)
finally:
shutil.rmtree(unlisted, ignore_errors=True)
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 Listed(folder, show)
finally:
# A file this fails to remove stays until loop-inbox removes it, 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, session: str, effects: Effects) -> Failure | None:
"""Holds the session's lock until stack closes, trying LOCK_TRIES times; returns None once it holds the lock, else the last try's failure."""
for _ in range(LOCK_TRIES):
attempt = contextlib.ExitStack()
unlocked = attempt.enter_context(held(folder, session))
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 running(folder, loop.session)]
return sorted(loops, key=lambda loop: loop.root)
def drop_ended_loops(folder: pathlib.Path) -> None:
"""Removes each running file whose session's lock no loop holds: a loop that was killed leaves it behind. A file it cannot remove stays on disk, and running_loops leaves it out all the same."""
for session in ended(folder, "*.running"):
with contextlib.suppress(OSError):
running_file(folder, session).unlink(missing_ok=True)
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 taken_items(todo: str | Failure, routed: int, taken_in: tuple[int, ...]) -> tuple[Taken, ...]:
"""The items a chunk takes, as the module docstring says, with their taglines from todo, the default branch's todo.md. routed, the item the chunk was routed on, is 0 for none."""
found = items(todo) if isinstance(todo, str) else []
taglines = {item.id: item.tagline.removeprefix("**").removesuffix("**") for item in found} if isinstance(found, list) else {}
ids = dict.fromkeys(([routed] if routed else []) + list(taken_in))
return tuple(Taken(id_, taglines.get(id_, "")) for id_ in ids)
-66
View File
@@ -1,66 +0,0 @@
"""The lock by which loop-inbox tells whether a loop-claude still runs.
A loop holds <session>.lock for its whole run (running_loops.py), 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.
"""
import contextlib
import fcntl
import pathlib
import typing
from failure import Failure
from text_files.file_writes import make_private
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.lock"
@contextlib.contextmanager
def held(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 takes the lock for a moment through ended, on each session whose files are still on disk, so a loop may find it held."""
path = lock_file(folder, session)
try:
make_private(folder)
except OSError as failure:
yield Failure(f"cannot make {folder}: {failure.strerror}")
return
try:
handle = open(path, "a")
except OSError as failure:
yield Failure(f"cannot open {path}: {failure.strerror}")
return
with handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
yield Failure(f"another process holds {path}")
return
except OSError as failure:
yield Failure(f"cannot lock {path}: {failure.strerror}")
return
yield None
def ended(folder: pathlib.Path, pattern: str) -> typing.Iterator[str]:
"""Each session with a file in folder that matches pattern, such as "*.json", and whose lock no loop holds. It yields each while holding that lock, so a loop that starts meanwhile keeps its files."""
try:
sessions = {path.stem for path in folder.glob(pattern)}
except OSError:
return
for session in sessions:
with held(folder, session) as unlocked:
if not unlocked:
yield session
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."""
try:
with open(lock_file(folder, session)) as handle:
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
return True
except OSError:
return False
return False
-41
View File
@@ -1,41 +0,0 @@
import errno
import pathlib
import shutil
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from loop_state import session_lock
class SessionLock(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
self.path = session_lock.lock_file(self.folder, "s1")
def test_a_held_lock_refuses_a_second_taker_and_reads_as_running_until_let_go(self):
self.assertFalse(session_lock.running(self.folder, "s1"))
with session_lock.held(self.folder, "s1") as first:
self.assertIsNone(first)
with session_lock.held(self.folder, "s1") as second:
self.assertEqual(second, Failure(f"another process holds {self.path}"))
self.assertTrue(session_lock.running(self.folder, "s1"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_that_cannot_be_opened_is_a_failure_and_no_loop_running(self):
self.path.mkdir()
with session_lock.held(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot open {self.path}: Is a directory"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_the_kernel_refuses_is_a_failure_and_no_loop_running(self):
self.path.touch()
with unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
with session_lock.held(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot lock {self.path}: No locks available"))
self.assertFalse(session_lock.running(self.folder, "s1"))
-11
View File
@@ -1,11 +0,0 @@
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
<session> is the worker's session id, so a loop lists one question at a time. The loop removes the ask once the question
is answered or the loop stops. loop-inbox lists an ask only while the loop holds the session's lock (running_loops.py),
and removes one whose lock is free. loop-inbox answers by replacing <session>.answer, which names the
ask's id. So an answer meant for an earlier question, or sent as the loop took an answer on its terminal,
never answers a later one.
Its modules import only those before them: ask, answers, listing, talk.
"""
-68
View File
@@ -1,68 +0,0 @@
"""What loop-inbox sends to a waiting ask, in <session>.answer, and how the loop reads it.
The message types stay here beside `received`, which reads them back, so that a change to one meets the other."""
import dataclasses
import json
import pathlib
from loop_state.waiting.ask import Ask, tagged
from failure import Failure
from text_files.file_writes import replace_json
@dataclasses.dataclass(frozen=True)
class Typed:
text: str
@dataclasses.dataclass(frozen=True)
class ClaudeOpening:
"""loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk."""
pid: int
@dataclasses.dataclass(frozen=True)
class ClaudeEnded:
"""The claude loop-inbox opened for the ask has ended."""
# What answers a waiting ask.
Answer = Typed | ClaudeOpening
Message = Answer | ClaudeEnded
def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.answer"
def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None:
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)})
def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
"""The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session."""
message = received(folder, ask)
return message if isinstance(message, Typed | ClaudeOpening) else None
def claude_ended(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether loop-inbox said the claude it opened for this ask has ended."""
return isinstance(received(folder, ask), ClaudeEnded)
def received(folder: pathlib.Path, ask: Ask) -> Message | None:
try:
data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(data, dict) or data.get("ask") != ask.id:
return None
match data:
case {"kind": "Typed", "text": str(text)}:
return Typed(text)
# alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever.
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
return ClaudeOpening(pid)
case {"kind": "ClaudeEnded"}:
return ClaudeEnded()
return None
-79
View File
@@ -1,79 +0,0 @@
"""An interrupt's question as loop-inbox lists it, and how its file is read; `tagged` writes the kind that `ask_state` reads.
The ask's state says whether the loop waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox."""
import dataclasses
import json
import pathlib
import typing
from loop_state.hand_over import ClaudeCommand
from text_files.utc_stamp import seconds, utc
if typing.TYPE_CHECKING:
from _typeshed import DataclassInstance
@dataclasses.dataclass(frozen=True)
class Asking:
"""The ask waits for an answer; talk opens the worker's claude session for /talk."""
talk: ClaudeCommand
@dataclasses.dataclass(frozen=True)
class OpenOnTerminal:
"""claude is open for the ask on the loop's own terminal; the loop takes no answer from loop-inbox."""
@dataclasses.dataclass(frozen=True)
class OpenInInbox:
"""claude is open for the ask in the loop-inbox whose process is pid."""
pid: int
AskState = Asking | OpenOnTerminal | OpenInInbox
def tagged(value: "DataclassInstance") -> dict[str, object]:
"""value's fields, with its kind, which ask_state and answers.received read it back by."""
return dataclasses.asdict(value) | {"kind": type(value).__name__}
@dataclasses.dataclass(frozen=True)
class Ask:
"""An interrupt's question, as loop-inbox lists it."""
id: str
session: str
# The checkout the loop runs in.
root: str
question: str
# When the loop asked, in seconds since the epoch; its file holds it as an ISO UTC datetime, as ask_fields writes it.
asked: float
state: AskState
def ask_fields(ask: Ask) -> dict[str, object]:
"""ask as its file holds it, which read_ask reads back to the second."""
return dataclasses.asdict(ask) | {"asked": utc(ask.asked), "state": tagged(ask.state)}
def read_ask(path: pathlib.Path) -> Ask | None:
"""The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does."""
try:
data = json.loads(path.read_text(encoding="utf-8"))
ask = Ask(**{**data, "asked": seconds(data["asked"]), "state": ask_state(data["state"])})
except (OSError, ValueError, TypeError, KeyError):
return None
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
return ask if texts and ask.session == path.stem else None
def ask_state(data: object) -> AskState:
match data:
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}} if all(isinstance(text, str) for text in [*args, *env.values()]):
return Asking(ClaudeCommand(args, cwd, env))
case {"kind": "OpenOnTerminal"}:
return OpenOnTerminal()
case {"kind": "OpenInInbox", "pid": int(pid)}:
return OpenInInbox(pid)
raise ValueError(f"not an ask's state: {data!r}")
-69
View File
@@ -1,69 +0,0 @@
"""The ask's file in the folder loop-inbox reads, and which asks it lists."""
import contextlib
import pathlib
import typing
from loop_state.waiting.answers import answer_file
from loop_state.waiting.ask import Ask, ask_fields, read_ask
from loop_effects.effects import Effects, say
from loop_state.session_lock import ended, running
from failure import Failure
from text_files.file_writes import make_private, replace_json
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.json"
def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
try:
make_private(folder)
except OSError as failure:
return Failure(f"cannot make {folder}: {failure.strerror}")
return replace_json(ask_file(folder, ask.session), ask_fields(ask))
def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
"""Removes the session's ask and any answer to it."""
for path in (ask_file(folder, session), answer_file(folder, session)):
try:
path.unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {path}: {failure.strerror}")
return None
def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
"""Lists ask in loop-inbox, in its state. A failure only warns: the question is still answered on the loop's terminal."""
if unshown := publish(folder, ask):
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
@contextlib.contextmanager
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to list it only warns: the question is still answered on the loop's terminal.
listed doesn't take the session's lock, which loop-inbox needs held to list the ask. Pass the folder running_loops.shown_running yields: shown_running holds the lock for the loop's whole run.
"""
shown(folder, ask, effects)
try:
yield
finally:
# An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it.
withdraw(folder, ask.session)
def waiting(folder: pathlib.Path) -> list[Ask]:
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
try:
paths = sorted(folder.glob("*.json"))
except OSError:
return []
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
return sorted(asks, key=lambda ask: ask.asked)
def drop_ended(folder: pathlib.Path) -> None:
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
for session in ended(folder, "*.json"):
withdraw(folder, session)
-45
View File
@@ -1,45 +0,0 @@
"""/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk
returns True once it reads that, and loop-inbox opens claude.
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with answers.claude_ended. The loop also stops waiting
if loop-inbox's process is gone.
"""
import dataclasses
import pathlib
import typing
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, read_ask
from loop_state.waiting.listing import ask_file, shown
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send
from loop_effects.effects import Effects, POLL_SECONDS
from failure import Failure
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
TALK = "/talk"
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
"""loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS. False where the ask is gone or replaced, its state is no longer Asking (answered first, claude open on the loop's own terminal, or the loop made way for another loop-inbox), or the loop didn't make way in time."""
if unsent := send(folder, ask, ClaudeOpening(pid)):
return unsent
deadline = now() + MAKE_WAY_SECONDS
while now() < deadline:
current = read_ask(ask_file(folder, ask.session))
if current is None or current.id != ask.id:
return False
if current.state == OpenInInbox(pid):
return True
if not isinstance(current.state, Asking):
return False
sleep(0.1)
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
send(folder, ask, ClaudeEnded())
return False
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
+1 -1
View File
@@ -23,7 +23,7 @@ def unsorted_imports(source: str) -> list[int]:
class ImportOrder(unittest.TestCase):
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude", "bin/loop-inbox"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
self.assertIn("bin/loop-claude", listed)
for name in listed:
with self.subTest(name):
+1 -1
View File
@@ -256,7 +256,7 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
+2 -18
View File
@@ -7,7 +7,7 @@ Each project principle states one rule that the decisions below apply; their ent
3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is loop-claude's, `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo.
4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it.
5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `deploy-release --cut`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere.
6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude loop-claude starts bypasses permissions inside its sandbox, each claude it or loop-inbox opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried.
6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude loop-claude starts bypasses permissions inside its sandbox, each claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried.
7. **One word names one thing, and one rule has one home.** In `bin/`, an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names. `CLAUDE.md` holds only the rules no path can scope, and each `rules/` file loads by its `paths:`.
# Decisions no project principle covers
@@ -18,7 +18,6 @@ Each project principle states one rule that the decisions below apply; their ent
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
@@ -123,7 +122,7 @@ Valid while `~/.claude` is a checkout of this repo.
2026-11-08, lilleman, todo item 262. Serves goals 1 and 1.5. A worker takes its own recommendation on a choice no rule reserves for the human, and records it. `CLAUDE.md` → "Working loop", "Ask, don't guess" names the three choices always reserved, and keeps any other rule's ask for approval. The worker's account of which goal settles a choice still doesn't decide a reserved one. The judge no longer interrupts for an unreserved choice the worker took, or asked about with a recommendation; it answers such an ask by quoting that rule, which it may quote again for each new ask. 92 of the 255 interrupts in loop-claude's archive on 2026-11-08 carried the worker's recommendation, and a finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. Valid while the human reverses few of the choices workers take this way, goal 1.2's counter-signal.
## loop-claude: every claude it or loop-inbox opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, so Claude Code skips its trust dialog, and neither tool writes `~/.claude.json`
## loop-claude: every claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, so Claude Code skips its trust dialog, and it doesn't write `~/.claude.json`
2026-09-21, lilleman. Serves goal 1. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone would still land the human in the trust dialog.
@@ -182,21 +181,6 @@ Hours. A chunk ran a median 0.7 hours from its first message to its last, one in
Valid while cache reads cost a twentieth of input and Claude Code's compaction keeps the worker's task.
## loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
2026-10-28, lilleman, todo item 243. Serves goal 1. With several loops running, each asked on its own terminal, and the human searched the terminals for the ones that waited. loop-inbox lists every loop's interrupts, the routing calls included, oldest first, and the human answers each one there. A loop asking for its project's model, as on a project's first run, asks on its terminal only: the human has just started it there, and no worker session exists yet. `bin/loop_state/waiting/` holds the protocol:
- An answer reaching the wrong loop is the worst failure. Each answer names the question it answers by a fresh id, so an answer meant for an earlier question, or sent as the terminal answered, never answers a later one.
- `/talk` from loop-inbox waits for the loop to stop reading its terminal before claude opens, so only one claude holds the worker's session.
- While claude is open for a question, as for a release ready to cut, the routing calls or a `/talk`, loop-inbox lists the loop and where claude is open, but takes no answer for it.
- loop-inbox runs the claude command the loop wrote, `bypassPermissions` included, so that claude runs in the same sandbox as the loop. Since loop-inbox runs a command read from a file, the folder is private to the user.
- Files, read by polling, need no daemon and only the standard library, and a loop with no loop-inbox running is answered on its terminal as before.
- loop-inbox lists a question only while its loop holds the session's lock file with flock, and removes a question whose lock is free. The loop holds the lock for its whole run. The kernel frees the lock however the loop ends, killed included. A process id could not tell a running loop from a killed one: on 2026-10-29 this machine's kernel handed out its 32,768 ids again every 30 to 75 minutes, so a killed loop's question came back whenever another process got its id. The lock file stays once the loop ends, one per project: removing it while another process has it open could let loop-inbox lock a file no loop holds. PR #396.
- A loop also lists itself as running, with the items its chunk takes, in `<session>.running`, under the same lock: one lock tells loop-inbox both that the loop runs and that its question stands. The items are the one the chunk was routed on, then those the worker names on its latest `Chunk items:` line (`routing: loop-claude reads the items a chunk takes`).
A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0.
Valid while every loop and loop-inbox run on one machine under one user's home.
## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, in the forms its `checked` text in `bin/rule_hook/rules.py` lists. 2026-11-04, lilleman: other forms, such as `uv run mutmut run` or `sudo docker build`, pass until one becomes a problem. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once.
+15
View File
@@ -1949,3 +1949,18 @@ Read most (opens and searches):
- `bin/rule_hook/env_file.py` 2
- `bin/rule_hook/repeat_read.py` 2
- `settings.json` 2
## Reading cost, chunk 1caad4fcf0dd, finished 2026-11-13T22:12:27Z
83788 new input tokens before the first commit.
Read most (opens and searches):
- `bin/rule_hook/test_rule_hook.py` 6
- `bin/rule_hook/env_file.py` 4
- `bin/command_lines/shell_command.py` 3
- `README.md` 2
- `CHANGELOG.md` 1
- `bin/repo_checks/test_import_order.py` 1
- `bin/rule_hook/rules.py` 1
- `docs/decisions.md` 1
+7 -10
View File
@@ -397,7 +397,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<text class="s" x="708" y="498">the repo's docs</text><text class="s" x="708" y="516">answer it</text>
<rect class="you" x="866" y="452" width="152" height="80" rx="7"/>
<circle class="f-you" cx="882" cy="471" r="6"/><text class="t" x="894" y="476" style="font-size:15px">Human's call</text>
<text class="s" x="876" y="498">terminal, inbox</text><text class="s" x="876" y="516">or /talk</text>
<text class="s" x="876" y="498">a line typed</text><text class="s" x="876" y="516">or /talk</text>
<path class="edge" d="M1112,532 L1112,552 L438,552 L438,538" marker-end="url(#ah)"/>
<path class="edge" d="M606,552 L606,538" marker-end="url(#ah)"/>
<path class="edge" d="M774,552 L774,538" marker-end="url(#ah)"/>
@@ -469,7 +469,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<li><code>skills/larv-review/</code> <span>the review recipe and its standards</span></li>
<li><code>skills/comprehension-panel/</code> <span>the simulated readers</span></li>
<li><code>principles/</code> <span>technical principles reviewers hold code to</span></li>
<li><code>bin/</code> <span>the tools: <code>loop-claude</code>, <code>loop-inbox</code>, <code>chunk-preflight</code>, <code>chunk-pr</code>, <code>rule-hook</code>, <code>rank_todo.py</code>, <code>run-heavy</code> and more</span></li>
<li><code>bin/</code> <span>the tools: <code>loop-claude</code>, <code>chunk-preflight</code>, <code>chunk-pr</code>, <code>rule-hook</code>, <code>rank_todo.py</code>, <code>run-heavy</code> and more</span></li>
<li><code>settings.json</code> <span>runs <code>rule-hook</code> before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call</span></li>
</ul>
</div>
@@ -480,7 +480,6 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<li><code>~/code/&lt;repo&gt;-item-&lt;ID&gt;</code> <span>a worktree per chunk; its branch <code>item-&lt;ID&gt;</code> becomes the PR</span></li>
<li><code>~/.claude/loop-claude-transcripts/</code> <span>every run's full log</span></li>
<li><code>~/.local/state/larv-review/</code> <span>every review report</span></li>
<li><code>~/.local/state/loop-claude/</code> <span>open questions, for <code>loop-inbox</code></span></li>
<li><code>~/.claude/loop-claude-models.json</code> <span>each project's model</span></li>
<li>the forge (GitHub or Gitea) <span>the pull request and CI</span></li>
</ul>
@@ -884,7 +883,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<section class="page" id="talk">
<div class="part">Part 2 · In depth</div>
<h2>Talking to the loop</h2>
<p class="lead">You start it with one command. It interrupts you in its terminal and in a shared inbox.</p>
<p class="lead">You start it with one command. It interrupts you in its terminal.</p>
<pre class="term"><span class="d"># inside a project checkout whose README has ## Goals and ## Audience</span>
<span class="p">$</span> loop-claude "Do the next chunk."
<span class="d">… worker running: item 12 on claude-opus-5-5 at medium effort</span>
@@ -904,7 +903,6 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<tr><td>a line of text</td><td>The worker resumes headless with your answer. It must record it before the chunk can finish.</td></tr>
<tr><td><code>/talk</code></td><td>Opens the worker's session for you (<code>claude --resume</code>). Read the diff, discuss, then exit.</td></tr>
<tr><td>Enter alone</td><td>Stops the loop. Rerunning resumes where it was.</td></tr>
<tr><td><code>loop-inbox</code></td><td>One screen for every loop on the machine: waiting questions, oldest first, and what each loop works on. Answer there or in the loop's own terminal; the first answer counts.</td></tr>
</tbody>
</table>
</div>
@@ -1012,7 +1010,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<h3 class="group">The machine</h3>
<div class="tablewrap"><table class="src-t"><colgroup><col style="width:4%"><col style="width:24%"><col style="width:72%"></colgroup><tbody>
<tr id="src-27"><td>27</td><td><b>Shared heavy slots and memory limits</b></td><td><span class="kind x">Experience</span> On 2026-10-22 an 8-CPU, 16 GiB machine thrashed for hours: four to six loops ran mutation tests, builds and e2e tests at once. The next day, with 7.6 GiB, it hung until a hard reset, from containers with no memory limit. So heavy commands wait for a slot, one per 4 CPUs, and every container gets a limit.</td></tr>
<tr id="src-28"><td>28</td><td><b>Names and syntax picked by the people who use them</b></td><td><span class="kind m">Own measurement</span> A panel of three readers, seated as the users, picks each new name or spelling. It picked <code>loop-inbox</code> 3–0.</td></tr>
<tr id="src-28"><td>28</td><td><b>Names and syntax picked by the people who use them</b></td><td><span class="kind m">Own measurement</span> A panel of three readers, seated as the users, picks each new name or spelling. It picked <code>/talk</code>, which opens claude for a question.</td></tr>
</tbody></table></div>
<p class="note">Most measurements come from loop-claude's archive of every run, across all projects; others from git history, review replays, the readability history and two machine incidents. The setup's own <code>docs/decisions.md</code> and <code>docs/scoring-and-goals-research.md</code> hold the full reasoning.</p>
</section>
@@ -1025,7 +1023,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<dt>Item</dt><dd>One row of <code>todo.md</code>: a bold one-sentence summary of the change, and its scores.</dd>
<dt>Worker</dt><dd>The headless Claude Code session that does the chunk.</dd>
<dt>Judge</dt><dd>The short AI run that reads each worker run and gives a verdict.</dd>
<dt>Interrupt</dt><dd>A question only you can answer. Shown in the terminal and in <code>loop-inbox</code>.</dd>
<dt>Interrupt</dt><dd>A question only you can answer, asked on loop-claude's terminal.</dd>
<dt>Pass</dt><dd>One kind of review, such as Stability. It runs in rounds.</dd>
<dt>Round</dt><dd>One review by one reviewer. At most two per pass per chunk, five in the release review.</dd>
<dt>Gate</dt><dd>The checks a PR must pass to merge: tests, CI, plan format.</dd>
@@ -1034,9 +1032,8 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<dt>Worktree</dt><dd>A separate git checkout per chunk, so your main checkout stays untouched.</dd>
</dl>
<h3>The two commands you use</h3>
<pre class="term"><span class="p">$</span> loop-claude "Do the next chunk." <span class="d"># start the loop in a project</span>
<span class="p">$</span> loop-inbox <span class="d"># answer every loop's questions</span></pre>
<h3>The command you use</h3>
<pre class="term"><span class="p">$</span> loop-claude "Do the next chunk." <span class="d"># start the loop in a project</span></pre>
</section>
</main>
+4 -11
View File
@@ -12,7 +12,6 @@
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 371 | 0.11.0 | | owner | **Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.** | 3 | 2 | 3 | 6 | 5 | code health by 3 | 2.9 |
| 354 | 0.11.0 | | | **Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 4, code health by 1 | 1.2 |
| 364 | 0.11.0 | 354 | | **Read a client repo's own `CLAUDE.md` and `AGENTS.md`, propose to its team each change that aligns them with this setup, and record each conflict left as a decision in the project's records.** | 2 | 2 | 2 | 4 | 2 | 1.6 by 4, 1.2 by 2 | 2.2 |
| 376 | 0.11.0 | | owner | **Make `principles/technical-principles.md` ask for files in folders before comment banners, and for an entry point a newcomer finds at once.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 4 | 1.6 |
@@ -25,11 +24,11 @@
| 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 362 | 0.11.0 | | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 |
| 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 |
| 373 | 0.11.0 | 371 | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
| 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
| 352 | 0.11.0 | 351 | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
| 355 | 0.11.0 | 349, 354 | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
| 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 |
| 372 | 0.11.0 | 371 | | **Key loop-claude's lock, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
| 372 | 0.11.0 | | | **Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
| 374 | 0.11.0 | 360, 372 | | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
| 359 | 0.11.0 | 350 | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
| 375 | 0.11.0 | 372, 373, 374 | | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
@@ -91,12 +90,6 @@
## Details
### 371. Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.
lilleman's call, 2026-11-13: loop-inbox didn't work out, so it goes, and the parallel chunks in items 372 to 375 don't build on it. An interrupt is answered at loop-claude's terminal only, with `/talk` opening the worker's session there, as before todo item 243. The Mattermost DM keeps telling the human that a loop waits.
Remove `bin/loop-inbox`, `bin/loop_inbox/`, and the parts of `bin/loop_state/waiting/` that only loop-inbox reads: the question files, `OpenInInbox`, and `input_or`'s watch of the inbox in `bin/loop_effects/effects.py`. Keep what loop-claude still needs, such as the session lock and `running_loops`, where something other than loop-inbox reads it. Remove the decision `loop-inbox: a loop-claude lists itself while it runs ...` and its title at the head of `docs/decisions.md`. Reword the decisions that name loop-inbox beside the terminal, such as the one on `CLAUDE_CODE_SANDBOXED`. Drop loop-inbox from `CLAUDE.md` → "Vocabulary" → "interrupt", the README, `.gitignore` and `presentation/index.html`. The changelog says loop-inbox is gone and that interrupts are answered on loop-claude's terminal.
### 354. Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.
lilleman's call, 2026-11-12: each record has its own backend setting, so a client project can keep, say, decisions and changelog in Confluence and anchors and comprehension history as files. Which goes where is asked per client at setup. Every tool and agent that reads or writes a record goes through the interface: the judge's records, `rank_todo.py`'s decision check, `todo-item finish --changelog`, larv-review's scoring and places, `score-outcomes`, `rules/decisions.md`. The plan store's contract suite has a twin for records, on fakes. R is above 5, so this item ships alone.
@@ -182,11 +175,11 @@ lilleman's calls, 2026-11-12: one page per record, whose ID the config names. Th
lilleman's call, 2026-11-12: the folder replaces the default, as item 347's principles folder does. Readers: the reviewers under `agents/`, the judge's records, larv-review, and the repo check that keeps the standards present.
### 372. Key loop-claude's lock, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
### 372. Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
lilleman's call, 2026-11-13, splitting item 361. Items 373 to 375 run several chunks of one project at once. Today a project has one session and one chunk at a time. This item makes two loop-claudes in one project, each on its own chunk, safe to run side by side. It doesn't yet start them; item 375 does that.
Key per chunk, not per project: the session lock, the archive keys, routing's state, and loop-claude's record of its running loop. Serialize item 345's commits to the config's folder, `~/.claude-projects/<key>/`, with a file lock, since two chunks may commit there at once. Leave `todo.md`'s and `CHANGELOG.md`'s edits to item 374, which moves them to merge time. A test runs two loops in one project and checks that neither reads or overwrites the other's state.
Key per chunk, not per project: the worker's session, which `session_named` names after the project, the archive keys and routing's state. Item 371 removed the session lock and the record of a running loop, which only loop-inbox read. Serialize item 345's commits to the config's folder, `~/.claude-projects/<key>/`, with a file lock, since two chunks may commit there at once. Leave `todo.md`'s and `CHANGELOG.md`'s edits to item 374, which moves them to merge time. A test runs two loops in one project and checks that neither reads or overwrites the other's state.
`bin/loop_claude/cycle/run.py:154` `rule` and `run.py:94` `archived` are places the comprehension seats found hard: the archive helpers sit in the cycle runner, and `rule` archives twice in an order only the code states. Make them easier to read where the archive keys change.