From 59697806ee440f321c9a01dd240e69cd7edbf4fe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 30 Oct 2026 12:41:48 +0100 Subject: [PATCH 1/5] Items 250, 253, 256, 258 - Move repeat-read's reads into repeat_read.py, split waiting.py by role, name an untagged release's review, fix release-review findings in-release --- AGENTS.md | 1 + CHANGELOG.md | 5 + README.md | 2 +- bin/chunk_pick.py | 18 +- bin/loop_claude/cycle/interrupt.py | 5 +- bin/loop_claude/loop/routing_check.py | 3 +- bin/loop_claude/paths.py | 2 +- bin/loop_claude/running_loops.py | 4 +- bin/loop_claude/test_black_box.py | 8 +- bin/loop_claude/test_loop_claude.py | 25 +-- bin/loop_claude/waiting.py | 233 -------------------------- bin/loop_claude/waiting/__init__.py | 15 ++ bin/loop_claude/waiting/answers.py | 71 ++++++++ bin/loop_claude/waiting/ask.py | 64 +++++++ bin/loop_claude/waiting/listing.py | 70 ++++++++ bin/loop_claude/waiting/talk.py | 45 +++++ bin/loop_inbox/inbox.py | 3 +- bin/loop_inbox/main.py | 7 +- bin/loop_inbox/test_loop_inbox.py | 123 +++++++------- bin/rule_hook/main.py | 36 +--- bin/rule_hook/repeat_read.py | 67 ++++++-- bin/rule_hook/test_rule_hook.py | 4 +- bin/test_chunk_pick.py | 22 +++ docs/decisions.md | 4 + skills/larv-review/SKILL.md | 3 +- 25 files changed, 468 insertions(+), 372 deletions(-) delete mode 100644 bin/loop_claude/waiting.py create mode 100644 bin/loop_claude/waiting/__init__.py create mode 100644 bin/loop_claude/waiting/answers.py create mode 100644 bin/loop_claude/waiting/ask.py create mode 100644 bin/loop_claude/waiting/listing.py create mode 100644 bin/loop_claude/waiting/talk.py diff --git a/AGENTS.md b/AGENTS.md index 18ff39d1..74d41f68 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,7 @@ Decisions live in `docs/decisions.md`: - review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began - review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health - review: a project decision may suspend the comprehension check for the plan items it names +- review: a release review fixes its findings in the release it reviews, and files only a finding that needs a human answer or adds a feature, under that release - review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge - review: a reviewer under `agents/` marks a ๐Ÿ”ด or ๐ŸŸก `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk - review: an ask no user answers leaves the PR unmerged diff --git a/CHANGELOG.md b/CHANGELOG.md index d72a71fa..1ea1d1cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- A release review now fixes the findings of its architecture and principles passes in the release it reviews. Before, it filed every one in `todo.md` under a later release, so the release held the drift the review had found. It files only a finding whose fix needs a human answer, marked `question`, or adds a feature, and a finding left after round five, all under the release being reviewed, which keeps that release from being ready to cut. +- `chunk-preflight` now calls a release that never had a tag finished once `todo.md` no longer files an item under it, so its release review is due and no later release's item is taken. Before, a repo with no tag lost sight of such a release. + ## 0.4.0 - `~/.claude` now holds only a release, and this repo is developed in a clone, `~/code/claude-config`. A new tool, `deploy-release`, moves `~/.claude` to the newest `v*` tag and prints `CHANGELOG.md`'s section for each version it moved past. It refuses while a tracked file there has an uncommitted change the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, or where the move would drop commits no release holds; a model picked with `/model` is no such change. To switch a machine over: diff --git a/README.md b/README.md index 3a7dfa1c..e514944a 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,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`. +- `loop_inbox` imports `loop_claude`'s question files (`waiting/`), 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. diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index f0ab8652..8325bc73 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -16,7 +16,7 @@ class LastCut: changelog: str | Failure # How many commits follow the tag, or make up the branch where it has none. commits: int | Failure - # todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; empty without a tag. + # todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; where the branch has no tag, at each commit that changed it. Empty where the tags cannot be read. todos_since: list[str] | Failure # Whether a release review has landed since the tag, as release_reviewed reads it. reviewed: bool | Failure = False @@ -25,9 +25,9 @@ class LastCut: @dataclasses.dataclass(frozen=True) class Upcoming: """The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` โ†’ "Working loop" uses both.""" - # The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the plan's earliest. None where there is none. + # The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the earliest todo.md has ever named or the plan holds. None where there is none. release: tuple[int, int, int] | None - # Whether it is the plan's earliest release. Without a cut, it always is, even where the plan holds no item. + # Whether it is the plan's earliest release. Without a cut, it also is where todo.md never named a release, even though the plan holds no item. is_earliest: bool # Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them. landed: bool | Failure @@ -102,13 +102,13 @@ def release_reviewed(tag: str | None, ref: str, cwd: str) -> bool | Failure: def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure: """LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent.""" - if not isinstance(tag, str): + if isinstance(tag, Failure): return [] - changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd) + changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd) if isinstance(changed, Failure): return changed texts = [] - for commit in [tag, *changed.split()]: + for commit in [*([tag] if tag else []), *changed.split()]: text = file_at(commit, "todo.md", cwd) if isinstance(text, Failure): return text @@ -126,9 +126,11 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: """The next release after cut, and whether work has landed towards it. found holds the plan's items. Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read. + Where the branch has no tag, every release todo.md named is after the cut, so one whose items are all done still reads as the next release and gets its release review. """ earliest = min((item.release for item in found), default=None) - cut_version = version_of(cut.tag) + untagged = cut.tag is None + cut_version = (0, 0, 0) if untagged else version_of(cut.tag) if cut_version is None: return Upcoming(earliest, True, landed(cut)) if earliest is not None and earliest <= cut_version: @@ -140,7 +142,7 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: if earliest is not None: after.add(earliest) release = min(after, default=None) - return Upcoming(release, earliest is not None and earliest == release, landed(cut)) + return Upcoming(release, earliest == release and (earliest is not None or untagged), landed(cut)) def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None: diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 9328e93f..aa231f5a 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -3,11 +3,14 @@ import sys import typing import uuid -from loop_claude.waiting import Answer, answered, Ask, Asking, claude_ended, ClaudeOpening, listed, make_way, OpenInInbox, OpenOnTerminal, shown, TALK, Typed +from loop_claude.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed +from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal 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.waiting.listing import listed, shown +from loop_claude.waiting.talk import make_way, TALK from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from model_routing.ladder import Rung diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 5f6453f9..793faebc 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -2,11 +2,12 @@ import pathlib from routing_figures import archive -from loop_claude.waiting import Ask, listed, OpenOnTerminal +from loop_claude.waiting.ask import Ask, 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.waiting.listing import listed from loop_claude.paths import Paths from model_routing.ladder import Rung from loop_claude.stop import Stop diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index 269bc383..c4981e26 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -10,7 +10,7 @@ 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). + # Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting/). waiting: pathlib.Path diff --git a/bin/loop_claude/running_loops.py b/bin/loop_claude/running_loops.py index dc4d41be..f016fc0c 100644 --- a/bin/loop_claude/running_loops.py +++ b/bin/loop_claude/running_loops.py @@ -3,9 +3,9 @@ A running loop holds its session's lock (session_lock.py) in Paths.waiting for its whole run. Beside the lock it keeps .running, which holds the loop's checkout and each item its chunk takes, by ID and by its tagline on the default branch as last fetched. The items are the one the chunk was routed on, then those the judge's latest ruling found the -worker took in, each listed once. loop-inbox lists a loop, and its question (waiting.py), only while the loop holds its +worker took in, each listed once. loop-inbox lists a loop, and its question (waiting/), only while the loop holds its lock. So a killed loop drops off the list, though its files stay until loop-inbox removes them: .running -through drop_ended_loops here, and the question through waiting.drop_ended. +through drop_ended_loops here, and the question through waiting.listing.drop_ended. """ import contextlib import dataclasses diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index c5803843..07b56c1a 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -18,7 +18,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env -from loop_claude import session_lock, waiting +from loop_claude.waiting.answers import send, Typed +from loop_claude import session_lock +from loop_claude.waiting.listing import waiting BIN = pathlib.Path(__file__).resolve().parents[1] TASK = "Do the next chunk." @@ -747,8 +749,8 @@ class Interrupt(unittest.TestCase): checkout = Checkout(self) folder = checkout.home / ".local" / "state" / "loop-claude" def answered_in_inbox(): - [ask] = waiting.waiting(folder) - waiting.send(folder, ask, waiting.Typed("B")) + [ask] = waiting(folder) + send(folder, ask, Typed("B")) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox)) self.assertEqual(run.code, 130) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index f45000ed..ed0ea2b3 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -20,11 +20,13 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, measure +from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal from loop_claude.project import checkout, model_choice, records +from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed from chunk_pick import DefaultPlan, LastCut 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, hand_over, paths, routing, running_loops, session_lock, waiting +from loop_claude import escalation_mark, hand_over, paths, routing, running_loops, session_lock from failure import Failure from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker @@ -40,6 +42,7 @@ from loop_claude.stop import Stop from loop_claude.running_loops import Taken from utc_stamp import utc from loop_claude.cycle.judge import verdict_from +from loop_claude.waiting.listing import waiting # How the archive records a worker that runs off the ladder. OFF_LADDER = '{"model": "worker-model"}' @@ -689,17 +692,17 @@ class Interrupts(unittest.TestCase): return answer, said.getvalue() def asked(self): - return waiting.waiting(self.paths.waiting) + return waiting(self.paths.waiting) def ask(self, question="Which one?", state=None): """The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session.""" resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) - return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or waiting.Asking(resumed)) + return Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or Asking(resumed)) def opening(self, other): """loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer.""" [ask] = self.asked() - waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(INBOX)) + send(self.paths.waiting, ask, ClaudeOpening(INBOX)) return other() def typed_there(self, args): @@ -742,9 +745,9 @@ class Interrupts(unittest.TestCase): 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.")) + send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), Typed("Use A.")) self.assertIsNone(other()) - waiting.send(self.paths.waiting, ask, waiting.Typed(" Use C. ")) + send(self.paths.waiting, ask, Typed(" Use C. ")) return other() fake = FakeEffects() effects = dataclasses.replace(fake.effects(), input_or=answered) @@ -763,10 +766,10 @@ class Interrupts(unittest.TestCase): 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))]) + self.assertEqual(self.asked(), [self.ask(state=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()) + send(self.paths.waiting, self.ask(), ClaudeEnded()) fake = FakeEffects(inputs=[self.opening]) self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n")) self.assertEqual((fake.made("claude_on_terminal"), asks_and_answers(self.paths.waiting)), ([], [])) @@ -778,7 +781,7 @@ class Interrupts(unittest.TestCase): return pid == INBOX def ended(seconds): slept.append(seconds) - waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded()) + send(self.paths.waiting, self.ask(), ClaudeEnded()) fake = FakeEffects(inputs=[self.opening]) stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended)) self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX], [POLL_SECONDS])) @@ -797,7 +800,7 @@ class Interrupts(unittest.TestCase): 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())]) + self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", OpenOnTerminal())]) return 0 fake = FakeEffects(inputs=typed, on_terminal_claude=[ran], git=[""]) self.put(fake, answer_here, question="Cut 0.4.0?") @@ -848,7 +851,7 @@ class RoutingCheck(unittest.TestCase): 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), [waiting.Ask(ASK_ID, "s1", "/code/log", question, NOW, waiting.OpenOnTerminal())]) + self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, NOW, OpenOnTerminal())]) return 0 self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""])) self.assertEqual(asks_and_answers(self.paths.waiting), []) diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py deleted file mode 100644 index fc5dfb26..00000000 --- a/bin/loop_claude/waiting.py +++ /dev/null @@ -1,233 +0,0 @@ -"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there. - -A waiting loop keeps its ask in .json in Paths.waiting: the question, with an id new for each question. - is the worker's session id, so a loop lists one question at a time. The loop removes the ask once the question -is answered or the loop stops. loop-inbox lists an ask only while the loop holds the session's lock (running_loops.py), -and removes one whose lock is free. 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 .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 loop_claude.session_lock import ended, running -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 - 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 list it only warns: the question is still answered on the loop's terminal. - - listed doesn't take the session's lock, which loop-inbox needs held to list the ask. Pass the folder running_loops.shown_running yields: shown_running holds the lock for the loop's whole run. - """ - shown(folder, ask, effects) - try: - yield - finally: - # An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it. - withdraw(folder, ask.session) - - -def waiting(folder: pathlib.Path) -> list[Ask]: - """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out.""" - try: - paths = sorted(folder.glob("*.json")) - except OSError: - return [] - asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)] - return sorted(asks, key=lambda ask: ask.asked) - - -def drop_ended(folder: pathlib.Path) -> None: - """Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. An ask it cannot remove stays on disk, and waiting leaves it out all the same.""" - for session in ended(folder, "*.json"): - withdraw(folder, session) - - -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)) - return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) 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) - # alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever. - case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0: - return ClaudeOpening(pid) - case {"kind": "ClaudeEnded"}: - return ClaudeEnded() - return None - - -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) diff --git a/bin/loop_claude/waiting/__init__.py b/bin/loop_claude/waiting/__init__.py new file mode 100644 index 00000000..61bcfec0 --- /dev/null +++ b/bin/loop_claude/waiting/__init__.py @@ -0,0 +1,15 @@ +"""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 .json in Paths.waiting: the question, with an id new for each question. + is the worker's session id, so a loop lists one question at a time. The loop removes the ask once the question +is answered or the loop stops. loop-inbox lists an ask only while the loop holds the session's lock (running_loops.py), +and removes one whose lock is free. loop-inbox answers by replacing .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. + +One module per role, each importing only those before it: +- ask.py: the ask, its state and the file format. +- answers.py: what loop-inbox sends, and the answer file. +- listing.py: the ask's file in the folder, and which asks are listed. +- talk.py: the /talk handshake. +""" diff --git a/bin/loop_claude/waiting/answers.py b/bin/loop_claude/waiting/answers.py new file mode 100644 index 00000000..220f4091 --- /dev/null +++ b/bin/loop_claude/waiting/answers.py @@ -0,0 +1,71 @@ +"""What loop-inbox sends to a waiting ask, in .answer, and how the loop reads it.""" +import dataclasses +import json +import pathlib + +from loop_claude.waiting.ask import Ask, AskState +from failure import Failure +from file_writes import replace_json + + +@dataclasses.dataclass(frozen=True) +class Typed: + text: str + + +@dataclasses.dataclass(frozen=True) +class ClaudeOpening: + """loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk.""" + pid: int + + +@dataclasses.dataclass(frozen=True) +class ClaudeEnded: + """The claude loop-inbox opened for the ask has ended.""" + + +# What answers a waiting ask. +Answer = Typed | ClaudeOpening +Message = Answer | ClaudeEnded + + +def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path: + return folder / f"{session}.answer" + + +def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None: + return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)}) + + +def tagged(value: AskState | Message) -> dict[str, object]: + """value's fields, with its kind, which ask.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) + # alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever. + case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0: + return ClaudeOpening(pid) + case {"kind": "ClaudeEnded"}: + return ClaudeEnded() + return None diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py new file mode 100644 index 00000000..8eea3cad --- /dev/null +++ b/bin/loop_claude/waiting/ask.py @@ -0,0 +1,64 @@ +"""An interrupt's question as loop-inbox lists it, and its file format. + +The ask's state says whether the loop waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox.""" +import dataclasses +import json +import pathlib + +from loop_claude.hand_over import ClaudeCommand + + +@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 + state: AskState + + +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)) + return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) 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}") + diff --git a/bin/loop_claude/waiting/listing.py b/bin/loop_claude/waiting/listing.py new file mode 100644 index 00000000..a9ead8fa --- /dev/null +++ b/bin/loop_claude/waiting/listing.py @@ -0,0 +1,70 @@ +"""The ask's file in the folder loop-inbox reads, and which asks it lists.""" +import contextlib +import dataclasses +import pathlib +import typing + +from loop_claude.waiting.answers import answer_file, tagged +from loop_claude.waiting.ask import Ask, read_ask +from loop_claude.effects import Effects, say +from loop_claude.session_lock import ended, running +from failure import Failure +from file_writes import make_private, replace_json + + +def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path: + return folder / f"{session}.json" + + +def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: + try: + make_private(folder) + except OSError as failure: + return Failure(f"cannot make {folder}: {failure.strerror}") + return replace_json(ask_file(folder, ask.session), 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 list it only warns: the question is still answered on the loop's terminal. + + listed doesn't take the session's lock, which loop-inbox needs held to list the ask. Pass the folder running_loops.shown_running yields: shown_running holds the lock for the loop's whole run. + """ + shown(folder, ask, effects) + try: + yield + finally: + # An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it. + withdraw(folder, ask.session) + + +def waiting(folder: pathlib.Path) -> list[Ask]: + """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out.""" + try: + paths = sorted(folder.glob("*.json")) + except OSError: + return [] + asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)] + return sorted(asks, key=lambda ask: ask.asked) + + +def drop_ended(folder: pathlib.Path) -> None: + """Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. An ask it cannot remove stays on disk, and waiting leaves it out all the same.""" + for session in ended(folder, "*.json"): + withdraw(folder, session) diff --git a/bin/loop_claude/waiting/talk.py b/bin/loop_claude/waiting/talk.py new file mode 100644 index 00000000..225d776b --- /dev/null +++ b/bin/loop_claude/waiting/talk.py @@ -0,0 +1,45 @@ +"""/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session: +1. loop-inbox's claim_talk sends ClaudeOpening, with its pid. +2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk + returns True once it reads that, and loop-inbox opens claude. +3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with answers.claude_ended. The loop also stops waiting + if loop-inbox's process is gone. +""" +import dataclasses +import pathlib +import typing + +from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, read_ask +from loop_claude.waiting.listing import ask_file, shown +from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send +from loop_claude.effects import Effects, POLL_SECONDS +from failure import Failure + +# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way. +MAKE_WAY_SECONDS = 10 * POLL_SECONDS +# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience. +TALK = "/talk" + + +def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure: + """loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where 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) diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 832bef2e..68c6abcf 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -10,8 +10,9 @@ import dataclasses import textwrap import typing -from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, TALK +from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal from loop_claude.running_loops import RunningLoop, Taken +from loop_claude.waiting.talk import TALK ENTER = "enter" BACKSPACE = "backspace" diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index c7384d7d..0a6f112e 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -26,7 +26,7 @@ above where it waits for an answer, and a line per todo.md item its chunk takes, tagline on the default branch. A loop whose process is gone drops off this list too. The loops' questions are files in ~/.local/state/loop-claude, read and written as -bin/loop_claude/waiting.py describes; the running loops are files beside them, as +bin/loop_claude/waiting/ describes; the running loops are files beside them, as bin/loop_claude/running_loops.py describes. Exit 2 when stdin or stdout is not a terminal, or on an unknown argument. @@ -39,7 +39,10 @@ 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, drop_ended, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting +from loop_claude.waiting.ask import Ask, Asking, read_ask +from loop_claude.waiting.listing import ask_file, drop_ended, waiting +from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS +from loop_claude.waiting.answers import ClaudeEnded, send, Typed from loop_claude.running_loops import drop_ended_loops, running_loops from loop_claude.effects import Effects, system_effects from failure import Failure diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index 1275c6bd..8f30ca98 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -12,13 +12,16 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from loop_claude.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send -from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, Typed +from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask +from loop_claude.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw +from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS 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 import running_loops, session_lock, waiting +from loop_claude import running_loops, session_lock from loop_claude.running_loops import RunningLoop, Taken from loop_claude.effects import system_effects @@ -94,32 +97,32 @@ class Answers(unittest.TestCase): 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))), *number, ENTER, *text, ENTER) + action = keyed(Listing(tuple(waiting(self.folder))), *number, ENTER, *text, ENTER) self.assertIsInstance(action, Send) return main.sent(self.folder, action.ask, action.text) def test_two_waiting_loops_each_get_their_own_answer(self): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) for ask in (bender, log): - waiting.publish(self.folder, ask) + 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."))) + self.assertEqual((answered(self.folder, log), answered(self.folder, bender)), (Typed("Use A."), Typed("Use B."))) def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) for ask in (log, bender): - waiting.publish(self.folder, ask) - picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER) + publish(self.folder, ask) + picked = keyed(Listing(tuple(waiting(self.folder))), "1", ENTER, "A", ENTER) # log is answered on its terminal before the answer typed here is sent; bender is now first. - waiting.withdraw(self.folder, "s1") + withdraw(self.folder, "s1") self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.") self.assertEqual(asks_and_answers(self.folder), ["s2.json"]) def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self): log = asked("s1", "/code/log") for ask in (log, asked("s3", "/code/bender")): - waiting.publish(self.folder, ask) + publish(self.folder, ask) self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a.")) def test_the_list_shows_the_loops_running_now(self): @@ -129,7 +132,7 @@ class Answers(unittest.TestCase): 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) + publish(self.folder, bender) self.assertEqual(main.refreshed(typing, self.folder), typing) self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender)) @@ -140,14 +143,14 @@ class Answers(unittest.TestCase): def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self): ask = asked("s1", "/code/log") - waiting.publish(self.folder, ask) + publish(self.folder, ask) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us")) - waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask")) + publish(self.folder, dataclasses.replace(ask, id="a later ask")) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")) def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self): ask = asked("s3", "/code/bender") - waiting.publish(self.folder, ask) + publish(self.folder, ask) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped.")) def claim(self, ask, loop_does): @@ -157,31 +160,31 @@ class Answers(unittest.TestCase): 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 + return claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10 def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self): ask = asked("s1", "/code/log") def made_way_for_the_claim(): - claim = waiting.answered(self.folder, ask) - if isinstance(claim, waiting.ClaudeOpening): - waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid))) + claim = answered(self.folder, ask) + if isinstance(claim, ClaudeOpening): + publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid))) for loop_does, claimed in ( (made_way_for_the_claim, (True, 0.1)), - (lambda: 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)), + (lambda: withdraw(self.folder, "s1"), (False, 0.1)), + (lambda: publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)), + (lambda: publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)), + (lambda: None, (False, MAKE_WAY_SECONDS)), ): with self.subTest(claimed=claimed): - waiting.publish(self.folder, ask) + 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) + 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)) + self.assertEqual((answered(self.folder, ask), claude_ended(self.folder, ask)), (None, True)) def never_opens(args, cwd, env): @@ -195,18 +198,18 @@ class Opens(unittest.TestCase): self.paths = paths_from(home) self.ask = asked("s1", "/code/log") loops_hold(self, self.paths.waiting, "s1") - waiting.publish(self.paths.waiting, self.ask) + 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)) + 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) + self.ended = claude_ended(self.paths.waiting, self.ask) def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self): def unstarted(args, cwd, env): @@ -216,7 +219,7 @@ class Opens(unittest.TestCase): (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) + publish(self.paths.waiting, self.ask) self.assertEqual(self.open(claude), said) self.assertTrue(self.ended) @@ -232,7 +235,7 @@ class Opens(unittest.TestCase): 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") + withdraw(self.paths.waiting, "s1") self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.") self.assertEqual(asks_and_answers(self.paths.waiting), []) @@ -252,16 +255,16 @@ class Typing(unittest.TestCase): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) loops_hold(self, paths.waiting, "s1", "s2") for ask in (log, bender): - waiting.publish(paths.waiting, ask) + publish(paths.waiting, ask) def answered_on_terminal(): - waiting.withdraw(paths.waiting, "s1") + 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))) + publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX))) effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way) with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()): main.run(window, contextlib.nullcontext, paths, effects) - return waiting.answered(paths.waiting, log), waiting.answered(paths.waiting, bender) + return answered(paths.waiting, log), answered(paths.waiting, bender) def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self): # Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit. @@ -322,35 +325,35 @@ class Waiting(unittest.TestCase): late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal()) loops_hold(self, pathlib.Path(folder), "s1", "s2") for ask in (late, early, stopped): - waiting.publish(pathlib.Path(folder), ask) + publish(pathlib.Path(folder), ask) pathlib.Path(folder, "s4.json").write_text("{") pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}') pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"')) - self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late]) + self.assertEqual(waiting(pathlib.Path(folder)), [early, late]) def test_drops_and_removes_the_ask_a_killed_loop_left_behind(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) - lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, session_lock, system_effects, waiting\nwith session_lock.held(pathlib.Path(sys.argv[1]), 's1'), waiting.listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)" + lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, session_lock, listed, system_effects\nwith session_lock.held(pathlib.Path(sys.argv[1]), 's1'), listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)" loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE) self.addCleanup(loop.wait) self.addCleanup(loop.kill) loop.stdout.readline() - waiting.send(folder, asked("s1", "/a"), Typed("Use A.")) - self.assertEqual(waiting.waiting(folder), [asked("s1", "/a")]) + send(folder, asked("s1", "/a"), Typed("Use A.")) + self.assertEqual(waiting(folder), [asked("s1", "/a")]) # SIGKILL runs none of the loop's cleanup. loop.kill() loop.wait() - self.assertEqual(waiting.waiting(folder), []) - waiting.drop_ended(folder) + self.assertEqual(waiting(folder), []) + drop_ended(folder) self.assertEqual(asks_and_answers(folder), []) def test_loop_inbox_removes_a_killed_loops_ask_answer_and_running_file_as_it_looks(self): with tempfile.TemporaryDirectory() as home: paths = paths_from(pathlib.Path(home)) ask = asked("s1", "/a") - waiting.publish(paths.waiting, ask) - waiting.send(paths.waiting, ask, Typed("Use A.")) + publish(paths.waiting, ask) + send(paths.waiting, ask, Typed("Use A.")) running_loops.running_file(paths.waiting, "s1").write_text(json.dumps({"root": "/a", "items": []})) main.run(Window("q"), contextlib.nullcontext, paths, system_effects()) self.assertEqual(asks_and_answers(paths.waiting), []) @@ -360,11 +363,11 @@ class Waiting(unittest.TestCase): folder = pathlib.Path(temp) loops_hold(self, folder, "s1") for ask in (asked("s1", "/a"), asked("s2", "/b")): - waiting.publish(folder, ask) - waiting.send(folder, ask, Typed("Use A.")) + publish(folder, ask) + send(folder, ask, Typed("Use A.")) for session in ("s1", "s2", "s3"): running_loops.running_file(folder, session).write_text(json.dumps({"root": "/a", "items": []})) - waiting.drop_ended(folder) + drop_ended(folder) self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running", "s2.running", "s3.running"]) running_loops.drop_ended_loops(folder) self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running"]) @@ -374,15 +377,15 @@ class Waiting(unittest.TestCase): ask = asked("s1", "/a") for pid in (0, -1): with self.subTest(pid=pid): - waiting.send(pathlib.Path(temp), ask, waiting.ClaudeOpening(pid)) - self.assertIsNone(waiting.answered(pathlib.Path(temp), ask)) + send(pathlib.Path(temp), ask, ClaudeOpening(pid)) + self.assertIsNone(answered(pathlib.Path(temp), ask)) def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self): with tempfile.TemporaryDirectory() as temp: - path = waiting.ask_file(pathlib.Path(temp), "s1") - waiting.publish(path.parent, asked("s1", "/a")) + path = ask_file(pathlib.Path(temp), "s1") + publish(path.parent, asked("s1", "/a")) good = json.loads(path.read_text()) - self.assertEqual(waiting.read_ask(path), asked("s1", "/a")) + self.assertEqual(read_ask(path), asked("s1", "/a")) for field, value in ( ("id", 1), ("session", "s2"), @@ -394,23 +397,23 @@ class Waiting(unittest.TestCase): ): with self.subTest(field=field, value=value): path.write_text(json.dumps(good | {field: value})) - self.assertIsNone(waiting.read_ask(path)) + self.assertIsNone(read_ask(path)) def test_withdraw_says_what_it_cannot_remove(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp, "a file") folder.write_text("") - self.assertEqual(waiting.withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory")) + self.assertEqual(withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory")) def test_a_message_reaches_only_the_ask_it_names(self): with tempfile.TemporaryDirectory() as temp: folder, ask = pathlib.Path(temp), asked("s1", "/a") another = dataclasses.replace(ask, id="another") - for message, answer, ended in ((Typed("A"), Typed("A"), False), (waiting.ClaudeOpening(7), waiting.ClaudeOpening(7), False), (waiting.ClaudeEnded(), None, True)): + for message, answer, ended in ((Typed("A"), Typed("A"), False), (ClaudeOpening(7), ClaudeOpening(7), False), (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)) + send(folder, ask, message) + self.assertEqual((answered(folder, ask), claude_ended(folder, ask)), (answer, ended)) + self.assertEqual((answered(folder, another), claude_ended(folder, another)), (None, False)) class RunningLoops(unittest.TestCase): @@ -440,15 +443,15 @@ class RunningLoops(unittest.TestCase): def test_a_second_loop_on_the_session_warns_and_leaves_the_first_listed_with_its_question(self): ask = asked("s1", "/code/log") with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as first: - waiting.publish(first.folder, ask) + publish(first.folder, ask) with contextlib.redirect_stderr(io.StringIO()) as said: with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as second: second.show((Taken(1, "Do it."),)) - with waiting.listed(second.folder, asked("s1", "/code/log", question="Mine?"), self.effects): - self.assertEqual(waiting.waiting(self.folder), [ask]) + with listed(second.folder, asked("s1", "/code/log", question="Mine?"), self.effects): + self.assertEqual(waiting(self.folder), [ask]) self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(self.folder, 's1')}", said.getvalue()) self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())]) - self.assertEqual(waiting.waiting(self.folder), [ask]) + self.assertEqual(waiting(self.folder), [ask]) self.assertEqual(list((self.folder / "unlisted").iterdir()), []) def test_takes_the_lock_once_loop_inbox_lets_go_of_it(self): diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 3bd00e29..cc40d549 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -29,23 +29,19 @@ override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git c checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it cannot read. """ -import datetime -import itertools import json import os import pathlib -import stat import sys import time import typing from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text -from rule_hook.repeat_read import asked_lines, repeat_breaches, shown_lines from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help from git_command import commits -from claude_code.transcript import current_thread, read_transcript from failure import Failure from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override +from rule_hook.repeat_read import read_breaches from rule_hook.reviewer_report import report_breaches from rule_hook.reviewer_rung import reviewer_breaches from rule_hook.round_cap import round_cap_breaches @@ -115,36 +111,6 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]: return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)] -def read_breaches(call: Call, home: str) -> list[Breach]: - """The repeat-read breaches of a call, read from the calling agent's transcript and the asked file; none where either cannot be read, or the file is not a regular file.""" - asked = asked_lines(call.tool, call.given, call.cwd, home) - changed = modified(asked.path) if asked else None - entries = read_transcript(call.transcript) if changed and call.transcript else [] - if asked is None or changed is None or isinstance(entries, Failure): - return [] - shown = shown_lines(current_thread(entries), call.tool, asked.path, changed, home) - # No line past the last one shown is in context, so the file's lines through one past it tell as much as all of them, and a long file is not read whole. - return repeat_breaches(asked, first_lines(asked.path, max(shown) + 1), shown, call.cwd) if shown else [] - - -def modified(path: str) -> str | None: - """When a regular file last changed, stamped as a transcript entry is; None for any other path, such as a FIFO, whose read could hang.""" - try: - status = os.stat(path) - except (OSError, ValueError): - return None - return datetime.datetime.fromtimestamp(status.st_mtime, datetime.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") if stat.S_ISREG(status.st_mode) else None - - -def first_lines(path: str, count: int) -> list[str]: - """The file's first count lines, without their line ends; none where it cannot be read as UTF-8.""" - try: - with open(path, encoding="utf-8") as file: - return [line.removesuffix("\n") for line in itertools.islice(file, count)] - except (OSError, UnicodeDecodeError): - return [] - - def read(path: str) -> str: try: return pathlib.Path(path).read_text(encoding="utf-8") diff --git a/bin/rule_hook/repeat_read.py b/bin/rule_hook/repeat_read.py index 17d97347..0300aa25 100644 --- a/bin/rule_hook/repeat_read.py +++ b/bin/rule_hook/repeat_read.py @@ -3,10 +3,16 @@ A line is in context when a read since the transcript thread's last compaction showed it at its line number, as the file holds it now. Against a Read, no line is in context when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did.""" import dataclasses +import datetime +import itertools +import os import re +import stat from rule_hook.rules import Breach -from rule_hook.call import FILE_TOOLS, text +from rule_hook.call import Call, FILE_TOOLS, text +from claude_code.transcript import current_thread, read_transcript +from failure import Failure from claude_code.entries import parts, tool_call, tool_result, tool_use_id from shell_command import resolved, simple_commands @@ -26,6 +32,47 @@ class Asked: last: int | None +def read_breaches(call: Call, home: str) -> list[Breach]: + """The repeat-read breaches of a call, read from the calling agent's transcript and the asked file; none where either cannot be read, or the file is not a regular file.""" + asked = asked_lines(call.tool, call.given, call.cwd, home) + changed = modified(asked.path) if asked else None + entries = read_transcript(call.transcript) if changed and call.transcript else [] + if asked is None or changed is None or isinstance(entries, Failure): + return [] + shown = shown_lines(current_thread(entries), call.tool, asked.path, changed, home) + # No line past the last one shown is in context, so the file's lines through one past it tell as much as all of them, and a long file is not read whole. + return repeat_breaches(asked, first_lines(asked.path, max(shown) + 1), shown, call.cwd) if shown else [] + + +def modified(path: str) -> str | None: + """When a regular file last changed, stamped as a transcript entry is, since shown_lines compares the two as text; None for any other path, such as a FIFO, whose read could hang.""" + try: + status = os.stat(path) + except (OSError, ValueError): + return None + return datetime.datetime.fromtimestamp(status.st_mtime, datetime.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") if stat.S_ISREG(status.st_mode) else None + + +def first_lines(path: str, count: int) -> list[str]: + """The file's first count lines, without their line ends; none where it cannot be read as UTF-8.""" + try: + with open(path, encoding="utf-8") as file: + return [line.removesuffix("\n") for line in itertools.islice(file, count)] + except (OSError, UnicodeDecodeError): + return [] + + +@dataclasses.dataclass(frozen=True) +class Used: + """A successful result in the thread of a call that read lines of a file or wrote it.""" + tool: object + # None for a write. + asked: Asked | None + result: str + # The result's entry's timestamp. + stamp: str + + def repeat_breaches(asked: Asked, lines: list[str], shown: dict[int, str], cwd: str) -> list[Breach]: """shown is what shown_lines found, and lines the asked file's lines now, read at least through one past the last shown line.""" last = len(lines) if asked.last is None else min(asked.last, len(lines)) @@ -75,32 +122,32 @@ def shown_lines(thread: list[dict], asker: str, path: str, changed: str, home: s changed is when the file last changed, stamped as the transcript stamps its entries, so the two compare as text.""" used = results_on(thread, path, home) # Claude Code's Edit and Write refuse such a file until a Read, and a Bash read does not count as one. - touched = max((stamp for tool, _, _, stamp in used if tool == "Read" or tool in FILE_TOOLS), default="") + touched = max((use.stamp for use in used if use.tool == "Read" or use.tool in FILE_TOOLS), default="") if asker == "Read" and changed > touched: return {} shown: dict[int, str] = {} - for tool, asked, result, _ in used: - shown |= result_lines(tool, asked, result) if asked else {} + for use in used: + shown |= result_lines(use.tool, use.asked, use.result) if use.asked else {} return shown -def results_on(thread: list[dict], path: str, home: str) -> list[tuple[object, Asked | None, str, str]]: - """Each successful result in the thread of a call that read lines of path or wrote it: the call's tool, the lines it read (None for a write), the result's text and its entry's timestamp.""" +def results_on(thread: list[dict], path: str, home: str) -> list[Used]: + """Each successful result in the thread of a call that read lines of path or wrote it.""" calls: dict[str, tuple[object, Asked | None]] = {} - found: list[tuple[object, Asked | None, str, str]] = [] + found: list[Used] = [] for entry in thread: cwd = str(entry.get("cwd", "")) for part in parts(entry): if (call := tool_call(part)) and (called := tool_use_id(part)): asked = asked_lines(*call, cwd, home) - if (asked.path if asked else written(*call, cwd, home)) == path: + if (asked.path if asked else written_path(*call, cwd, home)) == path: calls[called] = (call[0], asked) elif (result := tool_result(part)) and not result.failed and (use := calls.get(result.tool_use_id)): - found.append((use[0], use[1], result.text, text(entry, "timestamp"))) + found.append(Used(use[0], use[1], result.text, text(entry, "timestamp"))) return found -def written(tool: object, given: object, cwd: str, home: str) -> str: +def written_path(tool: object, given: object, cwd: str, home: str) -> str: """The file an Edit, MultiEdit or Write call writes; empty for any other call.""" return resolved(cwd, path, home) if tool in FILE_TOOLS and isinstance(given, dict) and (path := text(given, "file_path")) else "" diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index f8df799b..79bd0b93 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -10,9 +10,9 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from rule_hook.repeat_read import Asked, result_lines +from rule_hook.repeat_read import Asked, modified, read_breaches, result_lines from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides -from rule_hook.main import breaches_of, modified, read_breaches +from rule_hook.main import breaches_of from rule_hook.call import Call, parsed_call from git_command import Commit, commit_message, commits from test_rank_todo import DECISIONS, README, TODO diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index 0ac67e59..17720956 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -93,6 +93,28 @@ class ChunkItem(unittest.TestCase): self.assertEqual(chunk_pick.chunk_item(plan_under((1, 3, 0)), cut(False)), chunk_pick.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out") self.assertEqual(chunk_pick.chunk_item([], chunk_pick.LastCut("v1.2.3", "", 0, naming({(1, 3, 0)}))), chunk_pick.Unplanned((1, 3, 0))) + def test_calls_a_release_that_never_had_a_tag_finished_once_the_plan_files_no_item_under_it(self): + history = [HEADER + ROW.format(id=1, release="0.1.0") + ROW.format(id=2, release="0.1.1"), HEADER + ROW.format(id=2, release="0.1.1")] + cut = lambda reviewed: chunk_pick.LastCut(None, "", 4, history, reviewed) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 1, 1)), cut(False)), chunk_pick.ReviewDue((0, 1, 0))) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 1, 1)), cut(True)), chunk_pick.ReadyToCut((0, 1, 0))) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 1, 0)), cut(False)), chunk_pick.Next((0, 1, 0), one((0, 1, 0)))) + + def test_reads_every_version_of_todo_md_where_the_branch_has_no_tag(self): + repo = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", repo]) + run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True) + run("init", "-q", "-b", "main") + first, newest = HEADER + ROW.format(id=1, release="0.1.0"), HEADER + ROW.format(id=2, release="0.1.1") + pathlib.Path(repo, "todo.md").write_text(first) + run("add", "todo.md") + run("commit", "-q", "-m", "Plan") + run("commit", "-q", "--allow-empty", "-m", "Ship item 1") + pathlib.Path(repo, "todo.md").write_text(newest) + run("commit", "-q", "-a", "-m", "Ship item 1 for good") + self.assertEqual(chunk_pick.todos_since(None, "main", repo), [first, newest]) + self.assertEqual(chunk_pick.todos_since(Failure("tags unreadable"), "main", repo), []) + def test_finds_a_release_review_among_the_commits_since_the_cut(self): repo = tempfile.mkdtemp() self.addCleanup(subprocess.run, ["rm", "-rf", repo]) diff --git a/docs/decisions.md b/docs/decisions.md index 3363f913..304fa0e6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -200,6 +200,10 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r 2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it. +## review: a release review fixes its findings in the release it reviews, and files only a finding that needs a human answer or adds a feature, under that release + +2026-10-30, lilleman through todo item 258. Serves goal 1.1. fejkdata.dev's release review of 0.1.0 filed the architect's findings as items 28 to 36, in releases after 0.1.0, so the release the human was about to cut still held the drift the review had found. A release review's branch opens with an empty commit, so under `larv-review` ยง3 โ†’ "Findings" โ†’ "Outside the chunk" every finding lay outside its change and was filed. The review's whole point is to leave the release without the drift its small changes made, so the whole project is its chunk and the passes fix within their five rounds. Two kinds of finding are still filed, marked `question` where a human must answer: one whose fix needs a human answer, and one whose fix adds a feature. A finding left after round five is filed under the release being reviewed, which keeps the release from being ready to cut until a chunk answers it. Valid while a release review's rounds can fix what they find. + ## review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge 2026-10-15, lilleman asked for it through todo item 144, implemented by claude. Serves goal 1.1: a cheap reviewer that finds the work below standard can have a more capable one check that ruling, and work below standard gets a more capable rung to fix it. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 59629315..bb6b0b0f 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -104,7 +104,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside **Findings.** A reviewer rates each finding ๐Ÿ”ด must fix, ๐ŸŸก should fix, ๐ŸŸข nit, โ“ question, or ๐Ÿ”€ escalation naming the reviewer whose concern it is. -- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A ๐Ÿ”ด is marked `defect`. A ๐ŸŸก against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". +- **Outside the chunk.** In the release review, the whole project is the chunk's change: fix each finding there, unless it needs a human answer or adds a feature, and file such a finding per this item, marked `question` where it needs the answer, under the release being reviewed. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A ๐Ÿ”ด is marked `defect`. A ๐ŸŸก against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". - **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable โ†’ filed, marked `question`, the goal or decision left as is. - **๐Ÿ”ด.** A ๐Ÿ”ด is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` โ†’ "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. - **๐ŸŸก.** A ๐ŸŸก is fixed, shown factually wrong like a ๐Ÿ”ด, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` โ†’ "Working loop", "Ask, don't guess"; no user reachable โ†’ fix. Never drop one silently, and never decline one for convenience or the size of the fix. @@ -120,6 +120,7 @@ The release review is a release's last chunk, run once the release holds no item - **Branch.** `release-review-`, off the default branch. Open it with `git commit --allow-empty -m "Release review of "`. - **Passes.** Architecture, then Principles, each over the whole project, per "Waves". Tell both to refactor boldly where the code needs it. Each takes up to five rounds. - **Their fixes** re-enter Stability, Security, Overrides and Prose per "Re-entry", each at most two rounds. +- **Findings.** The passes fix their findings in the release they review, within their five rounds, so the release ready to cut holds no drift the review found. A finding left after round five is filed under that release, not a later one, so the release isn't ready to cut until a chunk answers it. "Findings" โ†’ "Outside the chunk" says which findings are filed. - **Comprehension check.** It runs its paired ruling here, per "Comprehension check". ### Architecture -- 2.52.0 From fd19b90f07b99344074991c52ff10c41eef7e211 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 30 Oct 2026 12:42:41 +0100 Subject: [PATCH 2/5] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 10f10df3e90f75ff7f384ca20ad9c90accd34289 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 30 Oct 2026 13:01:58 +0100 Subject: [PATCH 3/5] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20finish=20a?= =?UTF-8?q?=20release=20only=20once=20it=20holds=20no=20item,=20say=20no?= =?UTF-8?q?=20cut=20yet=20on=20an=20untagged=20branch,=20move=20tagged=20t?= =?UTF-8?q?o=20ask.py,=20add=20three=20missing=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 2 +- bin/chunk_pick.py | 14 +++++++++----- bin/chunk_preflight/choices.py | 9 +++++---- bin/loop_claude/test_loop_claude.py | 8 ++++++++ bin/loop_claude/waiting/__init__.py | 6 +----- bin/loop_claude/waiting/answers.py | 11 ++++------- bin/loop_claude/waiting/ask.py | 11 ++++++++++- bin/loop_claude/waiting/listing.py | 4 ++-- bin/loop_claude/waiting/talk.py | 2 +- bin/rule_hook/repeat_read.py | 2 +- bin/rule_hook/test_rule_hook.py | 6 ++++++ bin/test_chunk_pick.py | 5 +++++ todo.md | 2 +- 13 files changed, 54 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c1434161..0d9347a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,7 +7,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project. - **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it. - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code. -- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` ยง3 โ†’ "Release review"). **Once that has merged, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. +- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` ยง3 โ†’ "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` โ†’ `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them. - **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs. diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 8325bc73..7b8dcb81 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -7,6 +7,10 @@ from failure import Failure from todo_table import Item, items, next_item, release_of, renames from markdown_text import sections +# The version a branch with no v* tag counts as cut, so that every release todo.md names comes after it. +BEFORE_FIRST_RELEASE = (0, 0, 0) + + @dataclasses.dataclass(frozen=True) class LastCut: """What the default branch holds about its last release, which chunk_item weighs the plan against.""" @@ -25,9 +29,9 @@ class LastCut: @dataclasses.dataclass(frozen=True) class Upcoming: """The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` โ†’ "Working loop" uses both.""" - # The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the earliest todo.md has ever named or the plan holds. None where there is none. + # The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the earliest todo.md has named or the plan holds. None where there is none. release: tuple[int, int, int] | None - # Whether it is the plan's earliest release. Without a cut, it also is where todo.md never named a release, even though the plan holds no item. + # Whether it is the plan's earliest release. Also True without a cut where todo.md has never named a release and the plan holds no item. is_earliest: bool # Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them. landed: bool | Failure @@ -126,14 +130,14 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: """The next release after cut, and whether work has landed towards it. found holds the plan's items. Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read. - Where the branch has no tag, every release todo.md named is after the cut, so one whose items are all done still reads as the next release and gets its release review. + Where the branch has no tag, the cut counts as BEFORE_FIRST_RELEASE, so a release todo.md named whose items are all done still reads as the next release. """ earliest = min((item.release for item in found), default=None) untagged = cut.tag is None - cut_version = (0, 0, 0) if untagged else version_of(cut.tag) + cut_version = BEFORE_FIRST_RELEASE if untagged else version_of(cut.tag) if cut_version is None: return Upcoming(earliest, True, landed(cut)) - if earliest is not None and earliest <= cut_version: + if earliest is not None and earliest <= cut_version and not untagged: return Cut(earliest) named = named_releases(cut.todos_since) if isinstance(named, Failure): diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index a3f970e7..764e4bcb 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -21,15 +21,16 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: return NoItem(f"{where} holds no items table.") if isinstance(found, Failure): return NoItem(f"{where} cannot be read: {found.reason}.") + last_cut = f"the last cut, {cut.tag}" if cut.tag is not None else "the start, since no release is cut yet" pick = chunk_item(found, cut) if isinstance(pick, Cut): - return NoItem(f"{where} files items under release {version(pick.release)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.") + return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.") if isinstance(pick, Unknown): - return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.") + return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.") if isinstance(pick, ReadyToCut | ReviewDue | Unplanned): - upcoming = f"release {version(pick.release)}, the next after the last cut, {cut.tag}" if pick.release else f"the next release after the last cut, {cut.tag}" + upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}" if isinstance(pick, ReviewDue): - return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of ` has landed since the cut. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` โ†’ \"Release review\" says; once it merges, the release is ready to cut.") + return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of ` has landed since the cut. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` โ†’ \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.") if isinstance(pick, ReadyToCut): return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- renamed to ` to todo.md's `## Renamed` section.") return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index ed0ea2b3..cbfbc795 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -34,6 +34,7 @@ from model_routing import ladder from model_routing.ladder import LADDER, Rung from claude_code.reply import Limited from loop_claude.loop import main, reload, routing_check +from loop_claude.waiting.talk import make_way from machine_load import memory from transcript_archive import outcomes, write from transcript_archive.location import project_archive @@ -763,6 +764,13 @@ class Interrupts(unittest.TestCase): 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_only_warns_where_loop_inbox_cannot_list_the_open_claude(self): + self.paths.waiting.parent.mkdir(parents=True) + self.paths.waiting.write_text("") + with contextlib.redirect_stderr(io.StringIO()) as said: + make_way(self.paths.waiting, self.ask(), INBOX, FakeEffects().effects()) + self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said.getvalue()) + def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self): def claude_ran(_): # loop-inbox opens claude only once the loop lists it as open there. diff --git a/bin/loop_claude/waiting/__init__.py b/bin/loop_claude/waiting/__init__.py index 61bcfec0..bf6a84f1 100644 --- a/bin/loop_claude/waiting/__init__.py +++ b/bin/loop_claude/waiting/__init__.py @@ -7,9 +7,5 @@ and removes one whose lock is free. loop-inbox answers by replacing .an 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. -One module per role, each importing only those before it: -- ask.py: the ask, its state and the file format. -- answers.py: what loop-inbox sends, and the answer file. -- listing.py: the ask's file in the folder, and which asks are listed. -- talk.py: the /talk handshake. +Its modules import only those before them: ask, answers, listing, talk. """ diff --git a/bin/loop_claude/waiting/answers.py b/bin/loop_claude/waiting/answers.py index 220f4091..ca8a7cb2 100644 --- a/bin/loop_claude/waiting/answers.py +++ b/bin/loop_claude/waiting/answers.py @@ -1,9 +1,11 @@ -"""What loop-inbox sends to a waiting ask, in .answer, and how the loop reads it.""" +"""What loop-inbox sends to a waiting ask, in .answer, and how the loop reads it. + +The message types stay here beside `received`, which reads them back, so that a change to one meets the other.""" import dataclasses import json import pathlib -from loop_claude.waiting.ask import Ask, AskState +from loop_claude.waiting.ask import Ask, tagged from failure import Failure from file_writes import replace_json @@ -37,11 +39,6 @@ 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 ask.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) diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py index 8eea3cad..1fd302dd 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -1,12 +1,16 @@ -"""An interrupt's question as loop-inbox lists it, and its file format. +"""An interrupt's question as loop-inbox lists it, and how its file is read; `tagged` writes the kind that `ask_state` reads. The ask's state says whether the loop waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox.""" import dataclasses import json import pathlib +import typing from loop_claude.hand_over import ClaudeCommand +if typing.TYPE_CHECKING: + from _typeshed import DataclassInstance + @dataclasses.dataclass(frozen=True) class Asking: @@ -28,6 +32,11 @@ class OpenInInbox: AskState = Asking | OpenOnTerminal | OpenInInbox +def tagged(value: "DataclassInstance") -> dict[str, object]: + """value's fields, with its kind, which ask_state and answers.received read it back by.""" + return dataclasses.asdict(value) | {"kind": type(value).__name__} + + @dataclasses.dataclass(frozen=True) class Ask: """An interrupt's question, as loop-inbox lists it.""" diff --git a/bin/loop_claude/waiting/listing.py b/bin/loop_claude/waiting/listing.py index a9ead8fa..2f0cadc7 100644 --- a/bin/loop_claude/waiting/listing.py +++ b/bin/loop_claude/waiting/listing.py @@ -4,8 +4,8 @@ import dataclasses import pathlib import typing -from loop_claude.waiting.answers import answer_file, tagged -from loop_claude.waiting.ask import Ask, read_ask +from loop_claude.waiting.answers import answer_file +from loop_claude.waiting.ask import Ask, read_ask, tagged from loop_claude.effects import Effects, say from loop_claude.session_lock import ended, running from failure import Failure diff --git a/bin/loop_claude/waiting/talk.py b/bin/loop_claude/waiting/talk.py index 225d776b..3bf34933 100644 --- a/bin/loop_claude/waiting/talk.py +++ b/bin/loop_claude/waiting/talk.py @@ -22,7 +22,7 @@ TALK = "/talk" def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure: - """loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, stopped, made way for another loop-inbox, or didn't make way in time.""" + """loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS. False where the ask is gone or replaced, its state is no longer Asking (answered first, claude open on the loop's own terminal, or the loop made way for another loop-inbox), or the loop didn't make way in time.""" if unsent := send(folder, ask, ClaudeOpening(pid)): return unsent deadline = now() + MAKE_WAY_SECONDS diff --git a/bin/rule_hook/repeat_read.py b/bin/rule_hook/repeat_read.py index 0300aa25..df76b449 100644 --- a/bin/rule_hook/repeat_read.py +++ b/bin/rule_hook/repeat_read.py @@ -45,7 +45,7 @@ def read_breaches(call: Call, home: str) -> list[Breach]: def modified(path: str) -> str | None: - """When a regular file last changed, stamped as a transcript entry is, since shown_lines compares the two as text; None for any other path, such as a FIFO, whose read could hang.""" + """When a regular file last changed, stamped as a transcript entry is; None for any other path, such as a FIFO, whose read could hang.""" try: status = os.stat(path) except (OSError, ValueError): diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 79bd0b93..dccb1b5e 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -576,6 +576,12 @@ class RepeatRead(unittest.TestCase): def test_a_missing_transcript_lets_the_read_through(self): self.assertEqual(read_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), []) + def test_a_read_of_a_missing_path_or_a_directory_lets_the_read_through(self): + self.read(1, 10) + for path in (f"{self.folder}/none.txt", self.folder): + with self.subTest(path=path): + self.assertEqual(self.found("Read", {"file_path": path}), []) + def test_the_hook_blocks_a_repeated_read_without_offering_an_override(self): self.read(1, 10) self.used("Bash", {"command": f"head -n 5 {self.file}"}, self.shown(1, 5)) diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index 17720956..fb86370f 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -93,6 +93,11 @@ class ChunkItem(unittest.TestCase): self.assertEqual(chunk_pick.chunk_item(plan_under((1, 3, 0)), cut(False)), chunk_pick.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out") self.assertEqual(chunk_pick.chunk_item([], chunk_pick.LastCut("v1.2.3", "", 0, naming({(1, 3, 0)}))), chunk_pick.Unplanned((1, 3, 0))) + def test_takes_an_item_of_any_release_on_a_branch_with_no_tag(self): + for release in ((0, 0, 0), (0, 0, 1), (0, 1, 0)): + with self.subTest(release=release): + self.assertEqual(chunk_pick.chunk_item(plan_under(release), chunk_pick.LastCut(None, "", 4, naming(set()))), chunk_pick.Next(release, one(release))) + def test_calls_a_release_that_never_had_a_tag_finished_once_the_plan_files_no_item_under_it(self): history = [HEADER + ROW.format(id=1, release="0.1.0") + ROW.format(id=2, release="0.1.1"), HEADER + ROW.format(id=2, release="0.1.1")] cut = lambda reviewed: chunk_pick.LastCut(None, "", 4, history, reviewed) diff --git a/todo.md b/todo.md index f47da5c3..0204fc3a 100644 --- a/todo.md +++ b/todo.md @@ -125,7 +125,7 @@ Filed from PR #387's architecture round 1. The decision's 2026-10-16 addendum sa ### 254. Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files. -Found by the principles review of item 252, against the technical principles' rule that timestamps are ISO UTC. `Ask.asked` in `bin/loop_claude/waiting.py` is a float of seconds since the epoch, which `publish` writes to `.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change the code that shows it too. +Found by the principles review of item 252, against the technical principles' rule that timestamps are ISO UTC. `Ask.asked` in `bin/loop_claude/waiting/ask.py` is a float of seconds since the epoch, which `publish` writes to `.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change the code that shows it too. ### 240. Give loop-claude's worker prompt the reading rule "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", and keep it only where the 20 chunks after it hold the 20 before's review rounds, unfinished verdicts, ๐Ÿ”ด, ๐ŸŸก and misread findings, dollars and hours per chunk. -- 2.52.0 From 8b1ba3a133d136bec73574d9ef5da23fe81ba978 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 30 Oct 2026 13:01:58 +0100 Subject: [PATCH 4/5] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=209=20=F0=9F=9F=A1=20(0=20misread);=20state=20the?= =?UTF-8?q?=20release=20review's=20filing=20rule=20once,=20in=20Release=20?= =?UTF-8?q?review,=20and=20reword=20its=20title,=20changelog=20and=20comme?= =?UTF-8?q?nts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- CHANGELOG.md | 4 ++-- docs/decisions.md | 6 +++--- skills/larv-review/SKILL.md | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 74d41f68..4feb90b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ Decisions live in `docs/decisions.md`: - review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began - review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health - review: a project decision may suspend the comprehension check for the plan items it names -- review: a release review fixes its findings in the release it reviews, and files only a finding that needs a human answer or adds a feature, under that release +- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds - review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge - review: a reviewer under `agents/` marks a ๐Ÿ”ด or ๐ŸŸก `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk - review: an ask no user answers leaves the PR unmerged diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ea1d1cd..a4290dff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,8 @@ ## Unreleased -- A release review now fixes the findings of its architecture and principles passes in the release it reviews. Before, it filed every one in `todo.md` under a later release, so the release held the drift the review had found. It files only a finding whose fix needs a human answer, marked `question`, or adds a feature, and a finding left after round five, all under the release being reviewed, which keeps that release from being ready to cut. -- `chunk-preflight` now calls a release that never had a tag finished once `todo.md` no longer files an item under it, so its release review is due and no later release's item is taken. Before, a repo with no tag lost sight of such a release. +- A release review now fixes the findings of its architecture and principles passes in the release it reviews. Before, it filed each one in `todo.md`, so the release held the drift the review had found. It files only three kinds of finding, each under the release being reviewed: one whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. Until each is done, the release isn't ready to cut. +- In a repo with no tag yet, `chunk-preflight` now calls a release finished once `todo.md` files no item under it: its release review is due, and no later release's item is taken. Before, it lost sight of such a release. ## 0.4.0 diff --git a/docs/decisions.md b/docs/decisions.md index 304fa0e6..6ca14814 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -107,7 +107,7 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k ## loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question -2026-10-28, lilleman, todo item 243. Serves goal 1. With several loops running, each asked on its own terminal, and the human searched the terminals for the ones that waited. loop-inbox lists every loop's interrupts, the routing calls included, oldest first, and the human answers each one there. A loop asking for its project's model, as on a project's first run, asks on its terminal only: the human has just started it there, and no worker session exists yet. `bin/loop_claude/waiting.py` holds the protocol: +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/` 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. @@ -200,9 +200,9 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r 2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it. -## review: a release review fixes its findings in the release it reviews, and files only a finding that needs a human answer or adds a feature, under that release +## review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds -2026-10-30, lilleman through todo item 258. Serves goal 1.1. fejkdata.dev's release review of 0.1.0 filed the architect's findings as items 28 to 36, in releases after 0.1.0, so the release the human was about to cut still held the drift the review had found. A release review's branch opens with an empty commit, so under `larv-review` ยง3 โ†’ "Findings" โ†’ "Outside the chunk" every finding lay outside its change and was filed. The review's whole point is to leave the release without the drift its small changes made, so the whole project is its chunk and the passes fix within their five rounds. Two kinds of finding are still filed, marked `question` where a human must answer: one whose fix needs a human answer, and one whose fix adds a feature. A finding left after round five is filed under the release being reviewed, which keeps the release from being ready to cut until a chunk answers it. Valid while a release review's rounds can fix what they find. +2026-10-30, lilleman through todo item 258. Serves goal 1.1. fejkdata.dev's release review of 0.1.0 filed the architect's findings as items 28 to 36, in releases after 0.1.0, so the release the human was about to cut still held the drift the review had found. A release review's branch opens with an empty commit, so under `larv-review` ยง3 โ†’ "Findings" โ†’ "Outside the chunk" every finding lay outside its change and was filed. The review's whole point is to leave the release without the drift the release's small changes made, so the whole project is its chunk and the passes fix within their five rounds. Three kinds of finding are still filed, each under the release being reviewed, or under the earliest release `rules/todo-items.md` allows where that release's semver bump forbids it, such as a feature in a patch release: one whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. The release isn't ready to cut while one is open, so `CLAUDE.md` โ†’ "Working loop" calls a release finished only once its review has merged and it holds no item. Valid while a release review's rounds can fix what they find. ## review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index bb6b0b0f..6aef2bd8 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -104,7 +104,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside **Findings.** A reviewer rates each finding ๐Ÿ”ด must fix, ๐ŸŸก should fix, ๐ŸŸข nit, โ“ question, or ๐Ÿ”€ escalation naming the reviewer whose concern it is. -- **Outside the chunk.** In the release review, the whole project is the chunk's change: fix each finding there, unless it needs a human answer or adds a feature, and file such a finding per this item, marked `question` where it needs the answer, under the release being reviewed. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A ๐Ÿ”ด is marked `defect`. A ๐ŸŸก against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". +- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A ๐Ÿ”ด is marked `defect`. A ๐ŸŸก against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". In the release review the whole project is the chunk's change, so nothing lies outside it; "Release review" โ†’ "Findings" says which of its findings are filed. - **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable โ†’ filed, marked `question`, the goal or decision left as is. - **๐Ÿ”ด.** A ๐Ÿ”ด is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` โ†’ "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. - **๐ŸŸก.** A ๐ŸŸก is fixed, shown factually wrong like a ๐Ÿ”ด, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` โ†’ "Working loop", "Ask, don't guess"; no user reachable โ†’ fix. Never drop one silently, and never decline one for convenience or the size of the fix. @@ -120,7 +120,7 @@ The release review is a release's last chunk, run once the release holds no item - **Branch.** `release-review-`, off the default branch. Open it with `git commit --allow-empty -m "Release review of "`. - **Passes.** Architecture, then Principles, each over the whole project, per "Waves". Tell both to refactor boldly where the code needs it. Each takes up to five rounds. - **Their fixes** re-enter Stability, Security, Overrides and Prose per "Re-entry", each at most two rounds. -- **Findings.** The passes fix their findings in the release they review, within their five rounds, so the release ready to cut holds no drift the review found. A finding left after round five is filed under that release, not a later one, so the release isn't ready to cut until a chunk answers it. "Findings" โ†’ "Outside the chunk" says which findings are filed. +- **Findings.** The passes fix their findings in the release they review, within their five rounds, so the release holds no drift the review found. They file only three kinds in `todo.md`, each under that release, or under the earliest release `~/.claude/rules/todo-items.md` allows where that release's bump forbids it: a finding whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. The release isn't ready to cut while one is open. - **Comprehension check.** It runs its paired ruling here, per "Comprehension check". ### Architecture -- 2.52.0 From aef3a945e9bb5368ec5ec72e77471d3862fd1f17 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 30 Oct 2026 13:06:42 +0100 Subject: [PATCH 5/5] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20count=20an?= =?UTF-8?q?=20untagged=20branch=20as=20cut=20below=200.0.0=20and=20test=20?= =?UTF-8?q?it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_pick.py | 6 +++--- bin/chunk_preflight/choices.py | 2 +- bin/test_chunk_pick.py | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 7b8dcb81..91714a06 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -7,8 +7,8 @@ from failure import Failure from todo_table import Item, items, next_item, release_of, renames from markdown_text import sections -# The version a branch with no v* tag counts as cut, so that every release todo.md names comes after it. -BEFORE_FIRST_RELEASE = (0, 0, 0) +# The version a branch with no v* tag counts as cut: below every release, 0.0.0 included, so that every release todo.md names comes after it. +BEFORE_FIRST_RELEASE = (-1, 0, 0) @dataclasses.dataclass(frozen=True) @@ -137,7 +137,7 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: cut_version = BEFORE_FIRST_RELEASE if untagged else version_of(cut.tag) if cut_version is None: return Upcoming(earliest, True, landed(cut)) - if earliest is not None and earliest <= cut_version and not untagged: + if earliest is not None and earliest <= cut_version: return Cut(earliest) named = named_releases(cut.todos_since) if isinstance(named, Failure): diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 764e4bcb..4b0fa5b0 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -30,7 +30,7 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: if isinstance(pick, ReadyToCut | ReviewDue | Unplanned): upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}" if isinstance(pick, ReviewDue): - return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of ` has landed since the cut. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` โ†’ \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.") + return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of ` has landed {'since the cut' if cut.tag is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` โ†’ \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.") if isinstance(pick, ReadyToCut): return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- renamed to ` to todo.md's `## Renamed` section.") return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.") diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index fb86370f..c04ef9a9 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -98,6 +98,10 @@ class ChunkItem(unittest.TestCase): with self.subTest(release=release): self.assertEqual(chunk_pick.chunk_item(plan_under(release), chunk_pick.LastCut(None, "", 4, naming(set()))), chunk_pick.Next(release, one(release))) + def test_calls_a_release_0_0_0_finished_on_a_branch_with_no_tag(self): + history = [HEADER + ROW.format(id=1, release="0.0.0"), HEADER] + self.assertEqual(chunk_pick.chunk_item([], chunk_pick.LastCut(None, "", 4, history)), chunk_pick.ReviewDue((0, 0, 0))) + def test_calls_a_release_that_never_had_a_tag_finished_once_the_plan_files_no_item_under_it(self): history = [HEADER + ROW.format(id=1, release="0.1.0") + ROW.format(id=2, release="0.1.1"), HEADER + ROW.format(id=2, release="0.1.1")] cut = lambda reviewed: chunk_pick.LastCut(None, "", 4, history, reviewed) -- 2.52.0