Merge pull request 'Show every waiting loop-claude in loop-inbox and take each one's answer there' (#394) from item-243 into main
This commit was merged in pull request #394.
This commit is contained in:
@@ -42,6 +42,9 @@
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/loop-inbox
|
||||
!bin/loop_inbox/
|
||||
!bin/loop_inbox/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/markdown_text.py
|
||||
|
||||
@@ -10,12 +10,13 @@ Decisions live in `docs/decisions.md`:
|
||||
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
|
||||
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
- loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
|
||||
- loop-inbox: a waiting loop-claude lists its question as one file 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
|
||||
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
|
||||
- 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
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Link it onto `PATH` as README → Install shows.
|
||||
- Ctrl-C in a claude that `loop-claude` opens on its terminal, for `/talk`, a release ready to cut or the routing calls, now reaches only that claude. Before, it also stopped `loop-claude`, which closed that claude a quarter second later.
|
||||
- `reading-cost` now lists the files a chunk read in the worktree `chunk-preflight` made, `<checkout>-item-<ID>`. It listed none, since no transcript command names that worktree.
|
||||
- `larv-review ruling-base` now finds the last measured commit when run in a subfolder of a checkout. Before, it found no change to the comprehension history there and fell back to the merge base.
|
||||
- `score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, each a defect that review let through. A later chunk counts where a change of it rewrites or removes lines that `git blame` traces to the earlier chunk: its whole change where it ships a `todo.md` item marked `defect` or `security`, or one of its round commits whose title counts both a 🔴 and a finding a reviewer marked `[misread]`. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the mean per rung, over the chunks whose later fixes are known, in a new column of the routed-chunks table. To find them, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read.
|
||||
|
||||
@@ -122,7 +122,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **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 `README.md` or the judge's records.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
|
||||
- **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, and a routing call opens claude in `~/.claude`, both on loop-claude's terminal.
|
||||
- **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 README's 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.
|
||||
|
||||
@@ -66,7 +66,7 @@ Then pick a model with `/model`.
|
||||
|
||||
After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Update
|
||||
|
||||
@@ -93,12 +93,13 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
|
||||
|
||||
## Tools
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
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.
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung 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 the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `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, and takes each one's answer, `/talk` included; `loop-inbox --help` states how.
|
||||
- `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.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
@@ -131,6 +132,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py
|
||||
- `judge_replay` imports `loop_claude`'s judge.
|
||||
- `larv_review` imports `rank_todo.py`'s ranking.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_inbox` imports `loop_claude`'s question files (`waiting.py`), its effects and paths, and `hand_over.py`, which opens claude 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.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
|
||||
@@ -114,7 +114,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(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=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)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/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,65 +1,105 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.waiting import Answer, answered, Ask, Asking, claude_ended, ClaudeOpening, listed, make_way, OpenInInbox, OpenOnTerminal, shown, TALK, Typed
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were 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.
|
||||
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 Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
class WorkerSession:
|
||||
"""The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox."""
|
||||
root: str
|
||||
id: uuid.UUID
|
||||
rung: Rung
|
||||
transcript_path: str
|
||||
# Added to the environment of the worker's claude, and of the claude /talk opens.
|
||||
env: dict[str, str]
|
||||
|
||||
def claude_command(self) -> ClaudeCommand:
|
||||
return ClaudeCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: Paths, 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 nothing, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
|
||||
with listed(paths.waiting, ask, effects):
|
||||
answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal()
|
||||
if isinstance(answer, OpenOnTerminal | OpenInInbox):
|
||||
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, paths, effects)) or Talked()
|
||||
return answer
|
||||
|
||||
|
||||
def first_answer(ask: Ask, paths: Paths, 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 nothing, or the input ends."""
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
# Annotated since mypy infers input_or's T as object from the lambda.
|
||||
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
|
||||
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")
|
||||
if not answer:
|
||||
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 Talk() if answer == TALK else answer
|
||||
return OpenOnTerminal() if text == TALK else text
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, paths: Paths, 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(paths.waiting, dataclasses.replace(ask, state=where), effects)
|
||||
if unstarted := hand_over(session.claude_command(), paths, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
case OpenInInbox(pid):
|
||||
make_way(paths.waiting, ask, pid, effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not claude_ended(paths.waiting, ask) and effects.alive(pid):
|
||||
effects.sleep(POLL_SECONDS)
|
||||
case _:
|
||||
typing.assert_never(where)
|
||||
return None
|
||||
|
||||
|
||||
def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None:
|
||||
"""Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there."""
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
entries = read_transcript(path)
|
||||
if stop := held_open():
|
||||
return stop
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
@@ -10,11 +10,11 @@ from claude_code.session import delete_session, Session, session_open, transcrip
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
|
||||
from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
@@ -99,8 +99,6 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
@@ -124,6 +122,10 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
|
||||
|
||||
|
||||
def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
|
||||
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle))
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
@@ -160,7 +162,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | HumanTalked | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
@@ -168,11 +170,14 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
answer = interrupt(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.paths, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
|
||||
|
||||
@@ -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."""
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal or in loop-inbox."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
@@ -32,7 +32,7 @@ class Judging:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupting:
|
||||
"""The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
"""The human answers, by typing or in the worker's claude session; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
transcript_path: str
|
||||
ruling: Interrupt | QuotedAnswer
|
||||
quoted_answers: int = 0
|
||||
@@ -40,13 +40,6 @@ class Interrupting:
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Closing:
|
||||
transcript_path: str
|
||||
@@ -58,7 +51,7 @@ class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Talking | Closing
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@@ -79,14 +72,9 @@ class HumanTyped:
|
||||
typed: TypedAnswer
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
"""The human typed in the worker's claude session, which /talk opens, or a release ready to cut opens at once."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -94,7 +82,7 @@ class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived
|
||||
Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived
|
||||
|
||||
|
||||
def transition(state: State, event: Event) -> State:
|
||||
@@ -111,10 +99,8 @@ def transition(state: State, event: Event) -> State:
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
case Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
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."""
|
||||
|
||||
@@ -23,6 +34,8 @@ 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.
|
||||
@@ -30,12 +43,15 @@ 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]
|
||||
@@ -56,22 +72,46 @@ 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=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
|
||||
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
|
||||
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
|
||||
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
|
||||
try:
|
||||
return subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode
|
||||
finally:
|
||||
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]
|
||||
@@ -83,6 +123,21 @@ 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")
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Opens claude on the terminal for the human. It sits outside cycle/, since loop-inbox's /talk and the loop's routing calls open claude too."""
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeCommand:
|
||||
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]
|
||||
|
||||
|
||||
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
|
||||
"""Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal(command.args, command.cwd, command.env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
@@ -22,13 +22,16 @@ is shown the passage the judge quoted as the work remaining. The next chunk star
|
||||
Cycles continue until an 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 and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
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:
|
||||
- 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
|
||||
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. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
@@ -54,9 +57,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. 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-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.
|
||||
|
||||
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
|
||||
@@ -75,9 +78,10 @@ Once 20 cycles have closed across all projects in the archive since the last mea
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/measure.py). 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 ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
|
||||
are listed in routing-calls-raised.md beside the figures, 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.
|
||||
on the terminal in ~/.claude, asked to put the calls to the human; loop-inbox lists it too. Once
|
||||
that claude ends, the calls are listed in routing-calls-raised.md beside the figures, 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.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
@@ -110,7 +114,8 @@ 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, or for a release ready to cut, ends with nothing typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session.
|
||||
|
||||
@@ -195,7 +200,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
|
||||
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
|
||||
|
||||
|
||||
@@ -2,24 +2,25 @@
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.waiting import Ask, listed, OpenOnTerminal
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from utc_stamp import utc
|
||||
|
||||
|
||||
def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung is the rung of the claude that puts the calls to the human."""
|
||||
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, session is its worker's session id, which loop-inbox lists the calls under, and rung is the rung of the claude that puts the calls to the human."""
|
||||
with archive.locked(root) as held:
|
||||
new = new_calls(root, paths, effects) if held else []
|
||||
if isinstance(new, Failure):
|
||||
say(f"routing figures: {new.reason}", effects)
|
||||
return None
|
||||
return raise_calls(root, new, rung, paths, effects) if new else None
|
||||
return raise_calls(root, checkout, session, new, rung, paths, effects) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
|
||||
@@ -42,15 +43,19 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
|
||||
return [call for call in found if call not in kept.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
listed = "".join(f"- {call}\n" for call in new)
|
||||
say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects)
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; 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."""
|
||||
bullets = "".join(f"- {call}\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}", effects)
|
||||
if not effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}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 as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing 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 as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), effects.pid(), OpenOnTerminal())
|
||||
with listed(paths.waiting, ask, effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects)
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
|
||||
@@ -10,6 +10,8 @@ class Paths:
|
||||
home: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
# Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting.py).
|
||||
waiting: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home: pathlib.Path) -> Paths:
|
||||
@@ -21,4 +23,5 @@ 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",
|
||||
)
|
||||
|
||||
@@ -18,6 +18,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from loop_claude import waiting
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
@@ -36,7 +37,7 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN}}
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -97,8 +98,12 @@ if role == "worker":
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
@@ -726,6 +731,20 @@ 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.waiting(folder, lambda pid: True)
|
||||
waiting.send(folder, ask, waiting.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(list(folder.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")
|
||||
@@ -760,6 +779,14 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_leaves_ctrl_c_to_the_claude_open_for_talk(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, interrupt(type="B", ctrl_c=True), judge(evidence="B")], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "interrupt", "judge", "worker"]))
|
||||
self.assertFalse(run.calls[2]["ctrl_c_ignored"])
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -20,9 +21,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from routing_figures import archive, measure
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from chunk_pick import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, paths, routing
|
||||
from loop_claude import escalation_mark, hand_over, paths, routing, waiting
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
@@ -51,6 +52,10 @@ 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):
|
||||
@@ -75,16 +80,20 @@ 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)),
|
||||
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,
|
||||
@@ -94,6 +103,14 @@ 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)
|
||||
return self.answer("claude_on_terminal", args)
|
||||
@@ -178,10 +195,8 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)),
|
||||
(states.Talking("/t"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
@@ -191,8 +206,8 @@ class Transitions(unittest.TestCase):
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -207,7 +222,7 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
|
||||
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -638,10 +653,38 @@ class MemoryWait(unittest.TestCase):
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def put(self, fake, answer_here=True):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.transcript = self.home / "t.jsonl"
|
||||
self.transcript.write_text(json.dumps(human("a")) + "\n")
|
||||
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
|
||||
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
put = interrupt.put_question("Which one?", answer_here, fake.effects())
|
||||
return put, said.getvalue()
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, self.paths, effects or fake.effects())
|
||||
return answer, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting, lambda pid: True)
|
||||
|
||||
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 waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, PID, state or waiting.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()
|
||||
waiting.send(self.paths.waiting, ask, waiting.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:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
return 0
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
@@ -656,8 +699,8 @@ class Interrupts(unittest.TestCase):
|
||||
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk())
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there], git=[""])
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked())
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
@@ -665,24 +708,90 @@ 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(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
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(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self):
|
||||
def answered(_, other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), waiting.Typed("Use A."))
|
||||
self.assertIsNone(other())
|
||||
waiting.send(self.paths.waiting, ask, waiting.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(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
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 may still list this question: cannot remove {self.paths.waiting / f'{self.session.id}.json'}: Not a directory", said)
|
||||
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""]))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
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=waiting.OpenInInbox(INBOX))])
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.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"), list(self.paths.waiting.iterdir())), ([], []))
|
||||
|
||||
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)
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.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 with nothing 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 with nothing 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?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[ran], git=[""])
|
||||
self.put(fake, answer_here, question="Cut 0.4.0?")
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
stop, _ = self.put(fake)
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
|
||||
interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [handed])
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
class RoutingCheck(unittest.TestCase):
|
||||
@@ -707,10 +816,20 @@ class RoutingCheck(unittest.TestCase):
|
||||
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"}))
|
||||
|
||||
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:
|
||||
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.paths, fake.effects())
|
||||
stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, fake.effects())
|
||||
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.waiting(self.paths.waiting, lambda pid: True), [waiting.Ask(ASK_ID, "s1", "/code/log", question, NOW, PID, waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""]))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
|
||||
self.chunks(5, 3)
|
||||
self.assertEqual(self.check(FakeEffects()), (None, ""))
|
||||
@@ -773,6 +892,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.chunks(5, 4)
|
||||
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD, ""]))
|
||||
self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_says_a_figure_it_cannot_write_and_goes_on(self):
|
||||
@@ -1145,6 +1265,28 @@ class LocalTime(unittest.TestCase):
|
||||
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
|
||||
|
||||
|
||||
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 = []
|
||||
self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number)))
|
||||
before = signal.getsignal(signal.SIGINT)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
claude = pathlib.Path(folder, "claude")
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
|
||||
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
|
||||
claude.chmod(0o755)
|
||||
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
|
||||
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
|
||||
|
||||
|
||||
class PythonEffect(unittest.TestCase):
|
||||
def test_runs_a_script_in_the_given_directory(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
@@ -1579,9 +1721,9 @@ class ExitContract(unittest.TestCase):
|
||||
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("cycle/interrupt.py", "talk", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
|
||||
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""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 file once the
|
||||
question is answered or the loop stops. 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. 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.
|
||||
|
||||
/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 claude_ended. The loop also stops waiting
|
||||
if loop-inbox's process is gone.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from file_writes import make_private, replace_json
|
||||
|
||||
# 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"
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@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.
|
||||
asked: float
|
||||
pid: int
|
||||
state: AskState
|
||||
|
||||
|
||||
@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 ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.json"
|
||||
|
||||
|
||||
def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.answer"
|
||||
|
||||
|
||||
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), dataclasses.asdict(ask) | {"state": tagged(ask.state)})
|
||||
|
||||
|
||||
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 take it out only warns: loop-inbox drops the ask once the loop's process ends."""
|
||||
shown(folder, ask, effects)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if unwithdrawn := withdraw(folder, ask.session):
|
||||
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> 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 alive(ask.pid)]
|
||||
return sorted(asks, key=lambda ask: ask.asked)
|
||||
|
||||
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
"""The ask in path; None where a field has the wrong type, or names another session than path does."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
ask = Ask(**{**data, "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))
|
||||
# A pid of 0 or below would name a process group to alive.
|
||||
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 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}")
|
||||
|
||||
|
||||
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 tagged(value: AskState | Message) -> dict[str, object]:
|
||||
"""value's fields, with its kind, which read_ask and received read it back by."""
|
||||
return dataclasses.asdict(value) | {"kind": type(value).__name__}
|
||||
|
||||
|
||||
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)
|
||||
case {"kind": "ClaudeOpening", "pid": int(pid)}:
|
||||
return ClaudeOpening(pid)
|
||||
case {"kind": "ClaudeEnded"}:
|
||||
return ClaudeEnded()
|
||||
return None
|
||||
|
||||
|
||||
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 it was answered first, stopped, made way for another loop-inbox, or 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)
|
||||
@@ -0,0 +1,153 @@
|
||||
"""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.
|
||||
"""
|
||||
import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, 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 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 = ""
|
||||
|
||||
|
||||
@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 Listing(shown, typed[:-1])
|
||||
# isdigit would also take "²", which int() rejects.
|
||||
return Listing(shown, typed + key) 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("")
|
||||
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 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"
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here.
|
||||
|
||||
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 nothing, 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.
|
||||
|
||||
The loops' questions are files in ~/.local/state/loop-claude, read and written as
|
||||
bin/loop_claude/waiting.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_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.hand_over import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
|
||||
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:
|
||||
screen = entered(screen, refreshed(screen, folder, effects.alive), 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, alive: typing.Callable[[int], bool]) -> Screen:
|
||||
"""screen with the loops as they wait 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, alive)), "", note)
|
||||
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 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)
|
||||
|
||||
|
||||
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, paths, 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()
|
||||
@@ -0,0 +1,451 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
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 loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from failure import Failure
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_claude import waiting
|
||||
|
||||
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
|
||||
# The pids of a running loop, of this loop-inbox, and of a loop that has stopped.
|
||||
LOOP, INBOX, GONE = 4242, 4343, 13
|
||||
ANSWERED_ON_TERMINAL = object()
|
||||
|
||||
|
||||
def alive(pid):
|
||||
return pid != GONE
|
||||
|
||||
|
||||
def asked(session, root, question="Which one?", at=100.0, pid=LOOP, state=ASKING):
|
||||
return Ask(f"ask-{session}", session, root, question, at, pid, state)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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.waiting(self.folder, alive))), *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):
|
||||
waiting.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((waiting.answered(self.folder, log), waiting.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):
|
||||
waiting.publish(self.folder, ask)
|
||||
picked = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), "1", ENTER, "A", ENTER)
|
||||
# log is answered on its terminal before the answer typed here is sent; bender is now first.
|
||||
waiting.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(sorted(path.name for path in self.folder.iterdir()), ["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("s2", "/code/bender", pid=GONE)):
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder, alive), Listing((log,), "", "Sent to /a."))
|
||||
|
||||
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")
|
||||
waiting.publish(self.folder, bender)
|
||||
self.assertEqual(main.refreshed(typing, self.folder, alive), 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_answer_screen_leaves_once_its_loop_no_longer_waits(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Answering(ask, "Us"))
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Listing(note="/code/log 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 waiting.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 = waiting.answered(self.folder, ask)
|
||||
if isinstance(claim, waiting.ClaudeOpening):
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid)))
|
||||
for loop_does, claimed in (
|
||||
(made_way_for_the_claim, (True, 0.1)),
|
||||
(lambda: waiting.withdraw(self.folder, "s1"), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)),
|
||||
(lambda: None, (False, waiting.MAKE_WAY_SECONDS)),
|
||||
):
|
||||
with self.subTest(claimed=claimed):
|
||||
waiting.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")
|
||||
waiting.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((waiting.answered(self.folder, ask), waiting.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")
|
||||
waiting.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(_):
|
||||
waiting.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 = waiting.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):
|
||||
waiting.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):
|
||||
waiting.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(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
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)
|
||||
for ask in (log, bender):
|
||||
waiting.publish(paths.waiting, ask)
|
||||
def answered_on_terminal():
|
||||
waiting.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):
|
||||
waiting.publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX)))
|
||||
effects = dataclasses.replace(system_effects(), alive=alive, 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 waiting.answered(paths.waiting, log), waiting.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_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, pid=GONE, state=OpenOnTerminal())
|
||||
for ask in (late, early, stopped):
|
||||
waiting.publish(pathlib.Path(folder), ask)
|
||||
pathlib.Path(folder, "s4.json").write_text("{")
|
||||
pathlib.Path(folder, "s5.json").write_text('{"pid": 0}')
|
||||
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder), alive), [early, late])
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder), lambda pid: True), [stopped, early, late])
|
||||
|
||||
def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
path = waiting.ask_file(pathlib.Path(temp), "s1")
|
||||
waiting.publish(path.parent, asked("s1", "/a", pid=1))
|
||||
good = json.loads(path.read_text())
|
||||
self.assertEqual(waiting.read_ask(path), asked("s1", "/a", pid=1))
|
||||
for field, value in (
|
||||
("id", 1),
|
||||
("session", "s2"),
|
||||
("root", None),
|
||||
("question", 3),
|
||||
("pid", 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(waiting.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(waiting.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), (waiting.ClaudeOpening(7), waiting.ClaudeOpening(7), False), (waiting.ClaudeEnded(), None, True)):
|
||||
with self.subTest(message=message):
|
||||
waiting.send(folder, ask, message)
|
||||
self.assertEqual((waiting.answered(folder, ask), waiting.claude_ended(folder, ask)), (answer, ended))
|
||||
self.assertEqual((waiting.answered(folder, another), waiting.claude_ended(folder, another)), (None, False))
|
||||
|
||||
|
||||
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.",
|
||||
"",
|
||||
], [
|
||||
"Type a number and Enter to answer that loop; q",
|
||||
"quits loop-inbox, and the loops keep waiting.",
|
||||
"> 1",
|
||||
]))
|
||||
|
||||
def test_an_empty_list_says_no_loop_waits(self):
|
||||
self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", ""], ["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()
|
||||
@@ -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"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude", "bin/loop-inbox"], 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):
|
||||
|
||||
@@ -215,7 +215,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(claude=claude, claude_on_terminal=unused, discard_typed=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)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=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)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
@@ -2927,3 +2927,270 @@ Inherited architect, decided by:
|
||||
- Locality: `bin/git_repo.py:48` `Git`: the protocol moved out of `loop_claude/effects.py` into `git_repo`, and `default_ref` and `branch_chunks` take the runner as an injected `run`, so the guarded and timed path reads at the call site
|
||||
- Locality: `bin/branch_chunks/fixes.py:50` `with_fixes`: `branch.owner[commit] > change.chunk` means a later chunk fixed an earlier one only because chunks are ordered newest first, which only `Branch`'s and `chunk_log`'s docstrings state; not enough to move the ruling
|
||||
- Self-sufficiency: `bin/routing_figures/measure.py:336` `fixes_per_chunk`: explains its choice by pointing to "item 247" in the plan, while `later_fixes_of` and `fixes.py`'s docstring state their rules in full, so it is mixed
|
||||
|
||||
## 2026-10-29T00:40:36Z, PR #394 at bbb33f5, against b743228
|
||||
|
||||
Ruling: worse
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | worse | same | worse |
|
||||
| Inherited architect | same | worse | worse | same | worse |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/cycle/interrupt.py:36` `put_question`, with `bin/loop_claude/cycle/interrupt.py:90` `talk`: the ask is published in `put_question`, whose `finally` leaves it listed on a `Talk`, and `talk`'s own `finally` removes it one state later; changing either means following the ask's lifecycle across both and the `Talking` state, where at the base each did one local thing
|
||||
- Locality, Shape: `bin/loop_claude/cycle/interrupt.py:98` `opened`: its call to `shown` is also the go-ahead `claim_talk` (`bin/loop_claude/waiting.py:192`) polls for, so a function named for showing a question is one step of a handshake between two processes; only the comment above it and `waiting.py`'s docstring warn
|
||||
- Shape: `bin/loop_claude/loop/routing_check.py:7` `raise_calls`: the imports now reach into `cycle.interrupt` for `claude_args`, `shown` and `withdrawn` plus the `waiting` types, and it builds an `Ask` whose session is its own id
|
||||
- Shape: `bin/loop_claude/effects.py:12` the import of `Answer`: the low-level effects module, and `states.py`, now depend on the domain module `waiting.py` for their types
|
||||
- Shape, Self-sufficiency: `bin/loop_claude/cycle/states.py:12` `TypedAnswer`: its docstring still says typed at loop-claude's terminal, though an answer from loop-inbox becomes one too, and `Talking` lost its docstring; minor, outweighed by `waiting.py`'s docstring
|
||||
- Shape: `bin/loop_claude/cycle/interrupt.py:22` `WorkerSession`: bundles the base's seven loose `talk` arguments and six `hand_over` arguments, which reads better and keeps Shape only mildly worse
|
||||
- Navigation: `README.md:102` the loop-inbox entry: the new tool is signposted from the README, `loop-claude --help` and `loop-inbox --help`, so a symptom crosses more files but each is named where you would look
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:36` `put_question`, with `bin/loop_claude/cycle/interrupt.py:90` `talk`: on a `Talk` the ask's file stays up while the answer passes through `run.ask`, `TalkChosen`, `transition` and `Talking`, and `talk`'s `finally` takes it down; to be sure it is always removed, a reader holds the state machine across three files
|
||||
- Locality: `bin/loop_claude/waiting.py:192` `claim_talk`: loop-inbox waits 5 s for `OpenInInbox`, which the loop shows only after five units in three other files, so step 2 of the protocol is spread out and the timeout rests on that path staying quick
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:78` `shown`: confirming its docstring's failure path, loop-inbox gives up and the loop stops, takes four steps across two processes and two files
|
||||
- Shape: `bin/loop_inbox/main.py:39` the import of `hand_over`: `interrupt.py` under `cycle/` now also holds `hand_over`, `claude_args`, `shown` and `withdrawn`, which `routing_check` and loop-inbox import, so its name and folder no longer say who depends on it, while `waiting.py` holds only the raw `publish` and `withdraw`
|
||||
- Shape: `bin/loop_claude/cycle/states.py:12` `TypedAnswer`: its docstring still says typed at loop-claude's terminal; `Talking` lost its docstring, and `states.py` and `effects.py:12` now import from the inbox's file format
|
||||
- Locality: `bin/loop_claude/cycle/run.py:102` `step`, the `Talking` branch: `WorkerSession` gathers the base's seven loose arguments and `claude_command` builds the resume command in one place, a smaller gain outweighed by the above
|
||||
- Self-sufficiency: `bin/loop_claude/waiting.py:1` the module docstring: documents the file protocol in three numbered steps, so nothing new needs a document beside it; the cost is how far apart the pieces are
|
||||
|
||||
## 2026-10-29T00:46:50Z, PR #394 at bbb33f5
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Maintainability senior | 6 | 5 | 6 | 5.5 | 5.5 |
|
||||
| Inherited architect | 7 | 6 | 5.5 | 7.5 | 6.5 |
|
||||
| Mean | 6.75 | 5.50 | 6.13 | 6.25 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: four interacting rules, with helpers in ladder.py, route.py and escalation_mark.py, so predicting one rung means holding the rung, the unfinished count, the mark, the cap and taking_in at once
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: English instructions assembled from routing state and review_choice.chosen, whose order matters and whose result only the docstring examples show
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with REJECTED and RETIRED sentinels and an unstated `fits` convention, where a small mistake breaks the reload's hand-over of state
|
||||
- `bin/loop_claude/cycle/judge.py:150` `run_judge`: a misquote ends three different ways, with a verdict precedence only the comments in `Grounds` resolve
|
||||
- `bin/rank_todo.py:410` `blockers_first`: recursive blocker placement with loop detection, and every scoring function branches on the old and new table shapes
|
||||
- `bin/chunk_pick.py:11` `LastCut`: fields typed with `Failure` put errors inside the data, and the renamed-release rule lives only in named_releases
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": dense rules held together by cross-references, so one question took four files
|
||||
- `bin/rule_hook/rules.py:160` `unlimited_container`: a PATH heuristic about run-heavy decides whether a container is capped
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one rule raises, steps once, caps, moves the escalation mark and takes in E + I, readable only with routing.py, escalation_mark.py, route.py and ladder.py open together
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: which rung a step-up is charged to travels as a StepUp inside the states, action at a distance the comments at 145 and 170 resolve twice
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a recursive reflective decoder with sentinels and a duck-typed `fits`, whose consequence is spelled out only on LoopRun
|
||||
- `bin/rank_todo.py:428` `place`: recursive blocker placement, with the old and new table shapes running through read_scoring, weigh, score and cited_goals_failure
|
||||
- `bin/comprehension_history.py:207` `labelled_bullets`: a stateful line parser whose branches serve formats from before PR #232 and #255
|
||||
- `bin/loop_claude/cycle/judge.py:164` `quotes_checked`: a misquoted reply ends three ways, plus grounded's ellipsis matching, found only by tracing each caller
|
||||
- `bin/model_routing/route.py:84` `route_from`: reads three spellings of one value, and nothing says when the legacy form can go
|
||||
- `bin/review_replay/main.py:234` `redirected`: rewrites archived prompt paths where order matters, and guesses a round's commit from author times
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: five rung concepts, each defined elsewhere, plus the unfinished counter, a mark counted in transcript entries and taking_in, replayed by hand on examples
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: generic reflection machinery inside a domain package; nothing says when a field becomes RETIRED instead of REJECTED
|
||||
- `bin/rank_todo.py:410` `blockers_first`: two table shapes side by side, recursive placement, and weight rules stated together only in the module docstring
|
||||
- `bin/chunk_pick.py:166` `named_releases`: the next release derived from every todo.md since the tag minus renames, clearer in chunk-preflight's help than at its home
|
||||
- `bin/comprehension_history.py:130` `newest_scored`: prefix-matched commits, regex headings whose differences matter, and legacy carve-outs citing PR numbers instead of the old shapes
|
||||
- `bin/loop_claude/cycle/run.py:190` `archive_stepped`: the route update runs in a channel beside the states, so what changes the route has two answers, here and in loop/main.py's after_verdict
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: which sentences reach a worker's prompt depends on a dozen small functions, and no whole prompt is visible
|
||||
- `bin/rule_hook/rules.py:312` `unlimited_container`: slice arithmetic on words, and resets_path counts -i and -u whatever launcher they follow
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/round_titles.py:8` `CAP`: the round cap lives in a module named for commit titles, and nothing says a third reviewer launch is left unguarded on purpose
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the step-up policy is split from model_routing/ and spread over about six files, so why a worker is on rung X takes two packages
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: about twelve steps per cycle and an import fan-in of about 20 modules from 8 packages
|
||||
- `bin/loop_claude/waiting.py:76` `Typed`: one name over three concepts, with transcript.py's Typed and states.py's TypedAnswer
|
||||
- `bin/rung_replay/search.py:1` the imports: replay tools reach into loop_claude.cycle.retry and loop_claude.effects, so loop_claude is also the shared headless-claude library
|
||||
- `bin/loop_claude/cycle/judge.py:64` `Reply`: a new verdict field touches Reply, verdicts.py, states.py, routing.py, Route and the outcomes archive
|
||||
- `README.md:129` the module map: lists only cross-package imports, leaving the 18 root modules of bin/ without an index
|
||||
|
||||
## 2026-10-29T00:51:59Z, PR #394 rerun at bbb33f5
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Mid A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Maintainability senior | 6.5 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 7.5 | 6.5 |
|
||||
| Mean | 6.88 | 5.88 | 6.25 | 6.38 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: four rules meet in one expression, so one call means holding item_rung, ESCALATION_CAP, UNFINISHED_PER_STEP and the mark's entries_read while jumping to ladder.py and escalation_mark.py
|
||||
- `bin/comprehension_history.py:97` `entries`: the module parses its own markdown output, old formats are keyed only to PR numbers, and scored against scoring_runs differ in a way the code doesn't name
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: which route each archived line names before and after a step-up, with the cycle replaced inside run_cycle; the comments at 61, 145 and 170 resolve it
|
||||
- `skills/larv-review/SKILL.md:31` "Passes": dense rules pointing out to CLAUDE.md, rules/, the standards and --help, with the re-entry table and the round cap held together
|
||||
- `bin/rule_hook/round_cap.py:24` `earlier_titles`: returns an empty list when git fails, so a git failure turns the round cap off without saying so
|
||||
- `bin/rank_todo.py:568` `score`: both table shapes run through the whole 659-line file, and only rules/todo-items.md says what C, A and G mean
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: recursive type decoding with sentinels and a duck-typed fits hook, so a hot reload depends on dataclasses in other files
|
||||
- `bin/routing_figures/measure.py:174` `costed`: recorded costs scaled across list prices and messages matched to a rung by timestamp, resolved by long docstrings
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:263` `after_unfinished`: one condition needs rung, item rung, kept rung, L taken in, the escalation mark and the cap held at once, with rules/todo-items.md and the ladder open
|
||||
- `bin/rank_todo.py:332` `weigh`: a 658-line file carries a legacy scoring model through almost every function, so each one asks which shape it is in
|
||||
- `bin/loop_claude/escalation_mark.py:183` `checked`: part of the contract is a sentence spliced into the judge's schema text, so changing English changes behaviour
|
||||
- `bin/loop_claude/cycle/judge.py:316` `verdict_from`: the verdict precedence is encoded twice, as the order of the ifs and in the QUOTE_RULES prose
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: builds Cycle in one line of about 330 characters under 25 unordered imports, and plan_item defers to a todo.md item number
|
||||
- `bin/routing_figures/measure.py:59` `ChunkFigures`: fields documented in one dense paragraph instead of beside each field, and render builds tables inline in one huge literal
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": what counts as a round, the auto-reviewer exception and relaunches staying in their round took rereads beside round_titles.py and round_cap.py
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one verdict raises the rung, moves the mark, resets or bumps the count and takes in E + I, with invariants in route.py, ladder.py and escalation_mark.py held open at once
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: the StepUp travels through the Working and Interrupting states while run_cycle swaps Cycle.route out of sight of these handlers
|
||||
- `bin/rank_todo.py:568` `score`: the old table shape forks about eight functions, and the module docstring describes only the new shape
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: the worker's prompt is built from conditional fragments, so the text the worker reads appears only in docstring examples
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with first-fit union matching, sentinels and a duck-typed fits, which every LoopRun field quietly depends on
|
||||
- `bin/shell_command.py:44` `segments`: a hand-made state machine over shlex tokens tracks redirect targets, and a change's safety is unclear without the tests
|
||||
- `bin/chunk_pick.py:109` `next_release`: LastCut fields typed str, None or Failure, and recovering renamed releases from todo.md's history is explained only in passing
|
||||
- `bin/loop_claude/waiting.py:192` `claim_talk`: a handshake between processes with a timeout and a take-back, resolved by the module's three-step docstring
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `README.md:129` the module map: five domain modules sit at bin/'s root because two tools share them, so larv-review's rules spread over larv_review/, round_titles.py, review_passes.py, review_folder.py and comprehension_history.py
|
||||
- `bin/git_command.py:17` `commits`: parses git commit out of shell words and doesn't run git, beside git_repo.py's git and rule_hook/git.py's guarded git
|
||||
- `bin/rung_replay/search.py:1` the imports: replay tools reach into loop_claude.cycle.retry and loop_claude.effects, so loop_claude is also a shared library
|
||||
- `bin/rule_hook/main.py:79` `breaches_of`: rules.py is both the RULES registry and the checker of about half the rules, while the other half have their own modules
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the step-up policy is spread over about six files across loop_claude and model_routing, where the next routing rule lands
|
||||
- `bin/round_titles.py:8` `CAP`: enforced only on round commit titles, so a third reviewer launch is guarded by SKILL.md prose alone
|
||||
- `bin/loop_claude/project/records.py:1` `RECORD_FILES`: "records" means the judge's records here and a tool-kept document in AGENTS.md
|
||||
- `bin/loop_claude/loop/main.py:1` the module docstring: a 122-line contract restating README and SKILL.md, where drift will come from
|
||||
|
||||
## 2026-10-29T12:15:18Z, PR #394 at 9ebd06e, against b743228
|
||||
|
||||
Ruling: worse
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | better | same | worse |
|
||||
| Inherited architect | same | worse | same | same | worse |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: where the base's `put_question` read one terminal line, it waits on the terminal and on an answer file another process writes, and hands a lambda wrapping `claude_open` to `human_typed`, so a change means holding the two-process protocol; its docstring is one long sentence over every branch
|
||||
- Locality, Shape: `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way`: /talk from loop-inbox is a three-step handshake across two processes, with a take-back on timeout; order dependence with no counterpart at the base, though the module docstring explains it
|
||||
- Shape: `bin/loop_claude/cycle/interrupt.py:74` `first_answer`: `OpenOnTerminal`, an ask's state in loop-inbox's file, doubles as the return value for /talk and, at line 48, for a release ready to cut, so the name tells the truth about the file but not the control flow
|
||||
- Shape: `bin/loop_claude/cycle/states.py:34` `Interrupting`: the state machine loses `Talking` and `TalkChosen`, so `transition` has one state and one event fewer
|
||||
- Shape: `bin/loop_claude/hand_over.py:24` `hand_over`: opening claude on a terminal leaves `cycle/interrupt.py` for its own module, ending routing_check's sideways reach into the cycle, and `ClaudeCommand` replaces six loose arguments
|
||||
- Shape: `bin/loop_inbox/inbox.py:59` `pressed`: the new tool splits into a pure core of screens and keys behind a curses shell, with names that say what they are
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way`, `bin/loop_claude/cycle/interrupt.py:77` `claude_open` and `bin/loop_inbox/main.py:146` `opened`: /talk, one call in one process at the base, is a three-step handshake between two processes through a JSON file, over three files in two packages, resting on `MAKE_WAY_SECONDS`, a take-back after a timeout and pid liveness; the module docstring lays the steps out well
|
||||
- Locality: `bin/loop_claude/effects.py:105` `alive`: whether an ask still counts, and whether the loop still waits on loop-inbox's claude, rests on a pid being alive, and nothing addresses pid reuse, a risk neither caller shows
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:39` `interrupt`, with `bin/loop_claude/cycle/interrupt.py:94` `human_typed`: the base read straight down, `put_question` returning and the state machine stepping to `Talking`; now the wait sits inside `listed`, `first_answer` polls two sources, and the claude wait passes as a lambda; fewer states and `hand_over`'s move out of `cycle/` are real gains that don't offset it
|
||||
|
||||
## 2026-10-29T13:05:34Z, PR #394 at 9ebd06e
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6.5 | 5.5 | 6 |
|
||||
| Maintainability senior | 7.5 | 6 | 6.5 | 7 | 6.5 |
|
||||
| Inherited architect | 7 | 6 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.13 | 5.75 | 6.25 | 6.38 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: five interacting rules in one function, each resting on terms defined in ladder.py, route.py, escalation_mark.py and the charter; the module docstring's outline says which branch, not why the order
|
||||
- `bin/loop_claude/cycle/run.py:165` `ask`: the route before and after a step-up travel together, and seeing which one each archive line names meant tracing step_up through states.py; the comments at 61, 143 and 168 resolve it
|
||||
- `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way` and `bin/loop_claude/cycle/interrupt.py:77` `claude_open`: a three-step handshake between two processes through files, polled against a deadline with liveness checks; the module docstring gives the order, but who writes which file needs both sides
|
||||
- `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: a one-sentence docstring over about six outcomes, with the body spread over first_answer, claude_open and human_typed; accurate but too dense for one read
|
||||
- `bin/rank_todo.py:218` `rank`: about eight failure checks in sequence, and several functions branch on SHAPE versus OLD_SHAPE, a dual path explained only in todo_table.py
|
||||
- `bin/loop_claude/cycle/judge.py:164` `quotes_checked`: quietly turns a misquoted answer into an Interrupt, and verdict_from's branch order decides the meaning
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": a dense rulebook of passes, caps, re-entry and severities, part implemented in bin/larv_review and part followed by the agent; stayed too much to hold at once
|
||||
- `bin/model_routing/route.py:84` `route_from`: an archived line is JSON or an older regex format, and renaming a field breaks archived lines, guarded only by a comment
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: kept_rung, item_rung, raised, a one-rung step and a cap check held at once, plus two step triggers and a moving escalation mark; the docstring's index and escalation_mark.py's four steps resolve it partly, after three rereads
|
||||
- `bin/loop_claude/cycle/run.py:54` `run_cycle`: a step-up rides on state fields while run_cycle swaps Cycle.route on Ruled, HumanTalked drops it, and ran_on and archive_stepped decide which route a line names; the comments at 61, 143 and 168 explain it, read beside states.py
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with REJECTED and RETIRED sentinels, duck-typed to Route through `fits`, which nothing at Route mentions
|
||||
- `bin/rank_todo.py:332` `weigh`: OLD_SHAPE/SHAPE branches spread over weigh, score, cited_goals_failure and goal_weights instead of converted once at read time; why both exist is in todo_table.py
|
||||
- `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: a docstring of one sentence chain with four where/else turns, then a split across first_answer, claude_open, human_typed and the /talk handshake; waiting.py's module docstring resolves it
|
||||
- `bin/loop_claude/cycle/judge.py:106` `verdict_from`: an implicit priority order and silent coercions, a misquote becoming an Interrupt and an off-scale L becoming 0
|
||||
- `bin/rank_todo.py:428` `place`: recursive blocker placement with loop detection, fiddly by nature
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": dense rules pointing to CLAUDE.md, review-findings.md, standards/ and larv-review --help, not fully followed
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one unit raises the rung to an item's L, steps on every second unfinished verdict or on an escalation below the cap, moves the mark and records E + I, with rules from ladder.py, route.py and escalation_mark.py; the docstring states the rule but each branch needed tracing by hand
|
||||
- `bin/loop_claude/cycle/judge.py:96` `Grounds`: quotes from three sources, each misquote punished differently (Rejected, escalation dropped, answer turned to Interrupt), with the escalation half in escalation_mark.checked; each case commented, but the asymmetry is easy to break
|
||||
- `bin/chunk_pick.py:109` `next_release`: the outcomes come from combining is_earliest with landed, and LastCut's X | Failure fields push failure handling into the data; subtle by nature, clear on a second read
|
||||
- `bin/loop_claude/cycle/run.py:54` `run_cycle`: the route changes on Cycle at a Ruled step-up while step_up travels through the states, and ran_on versus cycle.route decides which rung each archive call charges; the comments at 61, 143 and 168 explain it, but the invariant spans two modules
|
||||
- `bin/rank_todo.py:428` `place`: recursive placement with loop detection, with OLD_SHAPE threading through older_columns, parse_weights, goal_term and cited_goals_failure; whether the old shape is still live stayed unclear
|
||||
- `bin/model_routing/route.py:84` `route_from`: layered backward compatibility (a JSON or legacy Worker line, reload's REJECTED and RETIRED sentinels and a `fits` found by name), so a change to Route's fields hits three decoders
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: timestamps compared as text, tool calls paired with results by id and truncation markers handled, closely tied to the transcript format; the comments resolve it
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": dense cross-referenced rules, waves, reruns and the re-entry table not holdable in one read
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/rule_hook/round_cap.py:8` `round_cap_breaches`: the round cap is split over round_titles.py, rule_hook/round_cap.py, larv_review/main.py and SKILL.md, and guards only `Answer <pass> round` commit titles, so a third reviewer run slips through on a launch without a round commit, a misspelled pass name or a slow git; nothing in the code says the cap is advisory at launch time
|
||||
- `bin/loop_claude/cycle/judge.py:186` `grounded`: fuzzy quote matching against a transcript rendered in escalation_mark.py and normalised in claude_code/transcript.py, three modules that must stay in step; where it rots first
|
||||
- `bin/round_titles.py:8` `CAP`: the `bin/` root holds about 55 peers, with review mechanics, shell parsing, plan reading and plumbing side by side, the README grouping only part; the worst level
|
||||
- `bin/git_command.py:17` `commits`: the name says it runs git, but it pulls commit messages from parsed shell words, beside git_repo.py, which runs git, and rule_hook/git.py, a third wrapper; three opens to sort out
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: routing reaches over routing.py, model_routing, cycle/prompts.py and, through environment variables, rule_hook/reviewer_rung.py; hard because the policy is, and documented
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: 120 lines of contract that restate CLAUDE.md's Vocabulary, AGENTS titles and the README's Tools, so a vocabulary change must land in four places
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": about twelve interacting concepts under one heading, the prose twin of the bin/ root
|
||||
- `bin/loop_claude/cycle/states.py:88` `transition`: "ruling" names both the judge's ruling and the comprehension paired ruling, "project" a rung, a package and project_key, "chunk" three tools
|
||||
|
||||
## 2026-10-29T13:05:37Z, PR #394 rerun at 9ebd06e
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 6 | 6 | 5.5 | 6 |
|
||||
| Maintainability senior | 7 | 6 | 7 | 6 | 6.5 |
|
||||
| Inherited architect | 7 | 6.5 | 5.5 | 6.5 | 6 |
|
||||
| Mean | 7.00 | 6.00 | 6.13 | 6.00 | 6.13 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the unfinished count, a step every two verdicts, a two-rung cap, the escalation mark and the item's rung interact, unpredictable on one read; the docstring and rules/todo-items.md gave the words, the arithmetic only made sense after tracing loop/main.py
|
||||
- `bin/loop_claude/escalation_mark.py:53` `checked`: the mark is an entry count that becomes a `[step]` line in the judge's prompt, which the grounding check in judge.py then relies on; one concept over three files, neither naming the other
|
||||
- `bin/rank_todo.py:428` `place`: recursive placement with loop detection, and the OLD_SHAPE/SHAPE branches through weigh, goal_term, score, parse_weights and cited_goals_failure; the spec docstring explains why, the recursion stayed hard
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a recursive type-directed decoder with REJECTED and RETIRED sentinels and a duck-typed `fits`, generic machinery whose reason lives at exec_if_edited
|
||||
- `bin/comprehension_history.py:150` `scoring_runs`: a near-twin of `scored` at 159 that a reader would mix up, with branches for formats from before PR #232 and #255 that need history the reader doesn't have
|
||||
- `bin/model_routing/review_choice.py:21` `chosen`: many near-synonym ladder helpers and an opaque "higher" loop; the docstrings explain edge cases, not the shape
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: timestamps compared as strings and truncation heuristics, correct only under assumptions not stated there
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: about 120 lines of contract before any code, accurate but costly, citing a plan item the reader may not open
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the kept rung, the item's rung, the cap, the mark's step and whether E + I was taken in, held at once, with meanings spread over routing.py, ladder.py, route.py and escalation_mark.py; no single place states the rule as a whole
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder signalling through REJECTED and RETIRED and duck-typing `fits`; why it exists is stated, which types reach `fits` took a grep
|
||||
- `bin/rank_todo.py:332` `weigh`: both table shapes branch inside weigh, score and cited_goals_failure, so a scoring change must be made right in several places; nothing collects the shape logic
|
||||
- `bin/routing_figures/measure.py:104` `measured`: many collaborators and a proportional cost scaling, a ChunkFigures docstring defining every field in one paragraph, and rung_at comparing timestamps as strings without saying why that holds
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: sentences that branch on route, project rung and taken-in state, a second copy of routing.py's rung rules in English; the worked examples help
|
||||
- `bin/model_routing/route.py:84` `route_from`: JSON and legacy regex lines both parse, RETIRED covers removed rungs, and nothing says when a form may be dropped
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: 120 lines of contract before the first import, which routed and closed_cycle only make sense against
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: rebuilds which lines a Read showed from transcript results with truncation heuristics and string-compared timestamps; the module docstring mostly resolves it
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/rank_todo.py:218` `rank`: the largest module, with every scoring step branching on OLD_SHAPE versus SHAPE and checks reaching into README.md and docs/decisions.md; the format docstring doesn't say why two shapes coexist
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: three rules in one function, followed only with route.py, escalation_mark.py, verdicts.py and ladder.py open; the docstrings and escalation_mark's overview resolve it eventually
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: calls `kind.fits` by naming convention, so Route.fits is action at a distance and a rename breaks the reload silently; the LoopRun comment warns about fields, not this hook
|
||||
- `bin/chunk_pick.py:109` `next_release`: the earliest release after the tag depends on renames across historical todo.md texts; chunk_preflight restates the rule, the rename tracking stays subtle
|
||||
- `bin/loop_claude/cycle/judge.py:150` `run_judge`: three kinds of ungrounded evidence end three ways, Rejected and retried, an Interrupt, or a silently dropped escalation; the Grounds comments resolve it
|
||||
- `bin/model_routing/review_choice.py:21` `chosen`: the `higher` loop records the lowest E + I per rung, and its `or` clause needs replay_applies and reviewers_rung from ladder.py; one terse comment
|
||||
- `bin/loop_claude/cycle/prompts.py:104` `escalation`: sentences assembled from ReviewChoice over three cases, the output described only by docstring examples
|
||||
- `bin/rank_todo.py:428` `place`: recursive topological placement with path-based loop detection, traced by hand
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/rule_hook/round_cap.py:24` `earlier_titles`: the round cap holds only at commit time, nothing refuses a third launch, and when git fails or no default branch is recorded it fails open; three files to establish that
|
||||
- `bin/round_titles.py:8` `CAP`: the `bin/` root holds about 60 entries, launchers, tool packages, shared modules and single-file tools at one level, told apart only by naming; the worst level
|
||||
- `bin/loop_claude/effects.py:36` `Effects`: 18 callables in loop-claude's home, yet imported by review_replay, loop_inbox and routing_check, so the README's claim that shared code lives at the bin/ root doesn't hold, and every feature adds a field every sharer pays for
|
||||
- `bin/git_command.py:17` `commits`: reads as "run a git command" but parses `git commit` out of shell words, one of three git modules
|
||||
- `bin/rule_hook/rules.py:139` `command_breaches`: some checks sit here, others in their own modules joined by main.py's bash_breaches, so adding a rule needs a choice the code doesn't explain
|
||||
- `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: a second source of truth for who is a reviewer, beside review_passes.py's table of the same name
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: "routing" spans loop_claude/routing.py, model_routing, routing_check, routing_figures and rung_replay
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: a fan-in of about 25 modules
|
||||
|
||||
+16
-1
@@ -50,12 +50,14 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the
|
||||
|
||||
2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
|
||||
|
||||
## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
## loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.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 still lands the human in the dialog. Trusting every worktree `git worktree list` names spares reading which one from the transcript. Since the human answers an interrupt on loop-claude's own terminal (todo item 168), claude opens there only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then. Valid while resume re-enters a recorded worktree and trust is kept per path.
|
||||
|
||||
2026-09-30, lilleman. A write by another claude inside `trust`'s read-modify-write window is lost, a risk larv-review accepted on 2026-09-24. Claude Code owns and writes `~/.claude.json`, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it.
|
||||
|
||||
2026-10-28, lilleman, todo item 243. `/talk` from loop-inbox opens claude in loop-inbox's terminal, through loop-claude's `hand_over`, which marks the trust just before. It adds a second writer to `~/.claude.json`, under the same risk, until item 6 ends it.
|
||||
|
||||
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
|
||||
2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session.
|
||||
@@ -99,6 +101,19 @@ 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 waiting loop-claude lists its question as one file 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_claude/waiting.py` 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.
|
||||
|
||||
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, whether direct or inside a container. 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.
|
||||
|
||||
@@ -919,3 +919,7 @@ Read most (opens and searches):
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/todo-items.md` 1
|
||||
|
||||
## Reading cost, chunk cfd9ab4f5b1b, finished 2026-10-28T22:00:08Z
|
||||
|
||||
64114 new input tokens before the first commit.
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 |
|
||||
| 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 |
|
||||
| 248 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 |
|
||||
| 250 | 0.5.0 | | | **Move the repeat-read rule's transcript, mtime and file reads from `bin/rule_hook/main.py` into `bin/rule_hook/repeat_read.py`, behind one `*_breaches` entry point like the other rules, and name the tuple `results_on` returns.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
|
||||
@@ -77,19 +76,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 243. Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.
|
||||
|
||||
lilleman's call, 2026-10-28: with several loops running, each asks on its own terminal, so the human jumps between terminals to find which wait. On 2026-10-28 three of five loops waited on round-cap questions at once. Today `put_question` in `bin/loop_claude/cycle/interrupt.py` reads the answer with `input()`, and nothing outside that terminal sees a question.
|
||||
|
||||
- Each loop, as it asks, writes one file per session under `~/.local/state/loop-claude/`, holding the project, the question, when it was asked, its pid and whether `/talk` is offered, and removes it once answered or stopped.
|
||||
- While it waits, the loop takes the first answer from either its terminal or the app, so a loop keeps working with no app running.
|
||||
- The app lists the waiting loops oldest first and sends a typed one-line answer to the loop it is meant for. A loop whose pid is gone drops off the list.
|
||||
- `/talk` from the app runs `claude --resume` for that session in the app's terminal; the loop then waits, as `talk` does today, until a human turn appears in the transcript.
|
||||
- A release ready to cut, which today opens the session at once, shows in the app too.
|
||||
- It runs on the host's Python with the standard library, such as `curses`, as `docs/decisions.md` → `bin/: the tools and their tests run on the host's Python` has it.
|
||||
|
||||
Bench the app's command name and how it shows a question with readers seated as the README's audience before it ships. An answer reaching the wrong loop is the worst failure: a test sends answers to two waiting loops and checks each gets its own. The change touches `loop-claude --help` in `bin/loop_claude/loop/main.py`, which the comprehension seats found hard: make it easier to read where it describes the interrupt.
|
||||
|
||||
### 226. Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.
|
||||
|
||||
Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, `python3 -m mutmut run`, `sudo docker build .`, `docker image build .` and `docker compose up --build` pass the rule, which `docs/decisions.md` → `machine load: …` and `RULES["run-heavy"]` describe as blocking docker builds and mutation runs. The rule's own text says a gate script isn't checked since no program can tell it from a light one, so the human decides where the line sits. Say what the rule's "checked" text promises either way. Where the answer widens the rule, the change touches `heavy` in `bin/rule_hook/heavy_command.py`, which the comprehension seats found hard: make it easier to read.
|
||||
@@ -364,7 +350,7 @@ The key names the project's session, archive folder and models entry. `project_k
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `put_question`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `first_answer`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
|
||||
@@ -380,7 +366,7 @@ The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/c
|
||||
|
||||
### 197. Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.
|
||||
|
||||
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. `effects.input` reads the answer to both of loop-claude's questions: the interrupt, in `cycle/interrupt.py`'s `put_question`, and the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. Importing `readline` in `effects.py` gives both line editing, at two costs. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. loop-claude asks two questions at its terminal. `effects.input` reads the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. `effects.input_or` reads the interrupt's answer, in `cycle/interrupt.py`'s `first_answer`, straight from stdin, since it also watches loop-inbox. Importing `readline` in `effects.py` gives `input` line editing, at two costs; `input_or` would also need to read through `input` while it watches. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
|
||||
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user