From 5b1f9034719a9fe6961a7347c4fd1917fd7f29b5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:11:09 +0100 Subject: [PATCH 1/6] Count a dated CHANGELOG heading as cut without a tag, read only regular files in rule-hook, stamp asks in ISO UTC, give workers the reading rule, and record the 200k window's measurement --- CHANGELOG.md | 7 +++ bin/chunk_pick.py | 54 +++++++++++++++------ bin/chunk_preflight/choices.py | 7 +-- bin/chunk_preflight/facts.py | 5 +- bin/chunk_preflight/main.py | 18 ++++--- bin/chunk_preflight/test_chunk_preflight.py | 6 +++ bin/loop_claude/cycle/interrupt.py | 3 +- bin/loop_claude/cycle/prompts.py | 6 ++- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_loop_claude.py | 16 ++++-- bin/loop_claude/waiting/ask.py | 13 +++-- bin/loop_inbox/inbox.py | 15 ++++-- bin/loop_inbox/test_loop_inbox.py | 10 +++- bin/rule_hook/main.py | 7 ++- bin/rule_hook/test_rule_hook.py | 8 +++ bin/test_chunk_pick.py | 30 ++++++++++++ bin/utc_stamp.py | 6 +++ docs/decisions.md | 6 +-- todo.md | 38 +++------------ 19 files changed, 176 insertions(+), 81 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13b652e3..bc8c40e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. +- `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file. +- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. Restart any `loop-claude` running when you deploy this release: until then, `loop-inbox` doesn't list its questions. +- Each chunk's first worker prompt now holds a 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. Once 20 chunks have run under it, a plan item measures them against the 20 before and drops the rule where any figure rose. + ## 0.5.0 - A bare run of `chunk-preflight` now only prints the facts. It no longer adds the worktree `-item-` and the branch `item-`, or runs `reading-cost`, `larv-review places` and its other checks in that worktree. `chunk-preflight --worktree` does all that, and `loop-claude` now passes it. Before, every run that found an item added the worktree and branch, and you had to remove them after a run made only to read the facts. diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 91714a06..93eb4db8 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -4,10 +4,10 @@ import re from git_repo import commits_since, file_at, git, newest_release_tag from failure import Failure -from todo_table import Item, items, next_item, release_of, renames +from todo_table import Item, items, next_item, release_of, renames, version from markdown_text import sections -# 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. +# The version a branch with no v* tag and no dated CHANGELOG.md heading 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) @@ -94,14 +94,19 @@ def default_plan(root: str, ref: str) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root) - reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root) - return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root), reviewed)) + changelog = file_at(ref, "CHANGELOG.md", root) + after = max(dated_headings(changelog), default=None) if tag is None else None + reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after) + return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, changelog, commits, todos_since(tag, ref, root), reviewed)) -def release_reviewed(tag: str | None, ref: str, cwd: str) -> bool | Failure: - """Whether ref holds, after tag or in all where tag is None, a commit titled as a release review opens: `Release review of `.""" +def release_reviewed(tag: str | None, ref: str, cwd: str, after: tuple[int, int, int] | None = None) -> bool | Failure: + """Whether ref holds, after tag or in all where tag is None, a commit titled as a release review opens: `Release review of `. Where after is given, the version a branch with no tag counts as cut, a title counts only where its release is later.""" titles = git("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd) - return titles if isinstance(titles, Failure) else any(title.startswith("Release review of ") for title in titles.splitlines()) + if isinstance(titles, Failure): + return titles + reviews = [title.removeprefix("Release review of ") for title in titles.splitlines() if title.startswith("Release review of ")] + return any(after is None or (re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", review) and release_of(review) > after) for review in reviews) def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure: @@ -130,23 +135,44 @@ 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, the cut counts as BEFORE_FIRST_RELEASE, so a release todo.md named whose items are all done still reads as the next release. + Where the branch has no tag, the cut is cut_version's, 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 = BEFORE_FIRST_RELEASE if untagged else version_of(cut.tag) - if cut_version is None: + version = cut_version(cut) + if 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 <= version: return Cut(earliest) named = named_releases(cut.todos_since) if isinstance(named, Failure): return Unknown() - after = {release for release in named if release > cut_version} + after = {release for release in named if release > version} if earliest is not None: after.add(earliest) release = min(after, default=None) - return Upcoming(release, earliest == release and (earliest is not None or untagged), landed(cut)) + return Upcoming(release, earliest == release and (earliest is not None or version == BEFORE_FIRST_RELEASE), landed(cut)) + + +def cut_version(cut: LastCut) -> tuple[int, int, int] | None: + """The version cut counts as cut: its tag's; on a branch with no tag, the newest under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE. None where the tag names no version.""" + if cut.tag is None: + return max(dated_headings(cut.changelog), default=BEFORE_FIRST_RELEASE) + return version_of(cut.tag) + + +def cut_name(cut: LastCut) -> str | None: + """How the preflight names cut_version's cut: the tag, or the version under its dated heading; None where nothing is cut.""" + if cut.tag is not None: + return None if isinstance(cut.tag, Failure) else cut.tag + headed = max(dated_headings(cut.changelog), default=None) + return None if headed is None else f"{version(headed)}, under CHANGELOG.md's dated heading" + + +def dated_headings(changelog: str | Failure) -> list[tuple[int, int, int]]: + """Each version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`, the heading a cut release takes; an undated heading is not cut.""" + if isinstance(changelog, Failure): + return [] + return [release_of(dated[1]) for heading in sections(changelog) if (dated := re.fullmatch(r"([0-9]+\.[0-9]+\.[0-9]+) - [0-9]{4}-[0-9]{2}-[0-9]{2}", heading))] def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None: diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 4b0fa5b0..6ffd4c5b 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -2,7 +2,7 @@ import pathlib import re -from chunk_pick import chunk_item, Cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned +from chunk_pick import chunk_item, Cut, cut_name, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned from failure import Failure from chunk_preflight.gathered import Forge, NoItem, Plan from todo_table import item_details, items, NoItemsTable, version @@ -21,7 +21,8 @@ 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" + named = cut_name(cut) + last_cut = f"the last cut, {named}" if named 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 {last_cut}; ask the human which release they belong to.") @@ -30,7 +31,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' 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.") + 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 named 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/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 0d9fe3ed..4f5520c8 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -2,7 +2,7 @@ from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran -from chunk_pick import LastCut, unreleased_entries +from chunk_pick import cut_name, LastCut, unreleased_entries from chunk_preflight.choices import PULLS_LIST from markdown_text import quoted @@ -19,7 +19,8 @@ def render(found: Gathered) -> list[str]: def last_release(default: str, release: LastCut) -> str: if isinstance(release.tag, Failure): return f"Last version cut: cannot be read: {release.tag.reason}" - cut = f"Last version cut: {release.tag or 'none'}." + named = cut_name(release) + cut = f"Last version cut: {named or 'none'}{', with no tag' if named and release.tag is None else ''}." entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index bec6a1f4..313b4399 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -9,17 +9,21 @@ with --worktree at the checkout root before each chunk's first worker, before it and quotes what it prints in the worker's prompt. It leaves the checkout as it is, and reads todo.md as the default branch holds it, the plan loop-claude routes on. It prints: -- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md - holds under ## Unreleased, or else how many commits followed the tag; +- the last version cut, and how many entries the default branch's CHANGELOG.md holds under + ## Unreleased, or else how many commits followed the tag. The last cut is the newest v* tag on + the default branch. On a branch with no tag, it is the newest version CHANGELOG.md heads + `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I. An item waits while it is marked question, or while an item still in todo.md - blocks it. Where the newest tag names a version x.y.z, the next release is the earliest after - x.y.z that todo.md has named at that tag or since, less a release its ## Renamed section marks - renamed. Otherwise it is todo.md's earliest release. - Where the next release holds no item, it says so, naming it where todo.md named it since the tag: + blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z + that todo.md has named at that cut or since, less a release its ## Renamed section marks + renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those + renamed, so a release whose items are all done still reads as next. + Where the next release holds no item, it says so, naming it where todo.md named it since the cut: its release review due where changes are unreleased (the ## Unreleased entries, or else the commits since the tag) and no commit titled `Release review of ` followed the tag, - finished and ready to cut once one did, and else to be planned first. + finished and ready to cut once one did, and else to be planned first. On a branch with no tag, + such a commit counts only where its is after the version under the dated heading. Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release already cut; - with --worktree, the item's worktree: a sibling of the checkout named -item-, on diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index d40cf24b..d1e4c634 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -367,6 +367,8 @@ class Render(unittest.TestCase): untagged = rendered(NoItem("x."), LastCut(None, "", 1, [])) self.assertIn("cut: none", untagged) self.assertIn("1 commit on origin/main", untagged) + headed = rendered(NoItem("x."), LastCut(None, "## 0.0.1 - 2026-10-03\n", 1, [])) + self.assertIn("cut: 0.0.1, under CHANGELOG.md's dated heading, with no tag.", headed) def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self): said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), [])) @@ -447,6 +449,10 @@ class Plans(unittest.TestCase): self.assertIn("holds no item", empty) self.assertNotIn("no items table", empty) + def test_names_a_release_cut_under_a_dated_heading_as_the_last_cut_on_a_branch_with_no_tag(self): + said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main").why + self.assertIn("the next release after the last cut, 0.0.1, under CHANGELOG.md's dated heading", said) + def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self): named = "release 0.2.0, the next after the last cut, v0.1.0" unnamed = "the next release after the last cut, v0.1.0" diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 8798892d..80482246 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -14,6 +14,7 @@ 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 +from utc_stamp import utc ANSWER_QUESTION = "answer the question above" # ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. @@ -46,7 +47,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: P return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() - ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) + ask = Ask(effects.new_id(), str(session.id), session.root, question, utc(effects.now()), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) with listed(paths.waiting, ask, effects): answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal() if isinstance(answer, OpenOnTerminal | OpenInInbox): diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 3be7ae34..990037ac 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -19,6 +19,10 @@ EACH_SEAT = "each comprehension seat" THE_SECURITY_PASS = "the security pass's subagent" +# The worker's reading rule, from PR #376's trials, where it alone cut a worker's reading; it is the worker's, not CLAUDE.md's, since reviewers under a like rule missed findings: docs/decisions.md → "loop-claude: the worker's claude compacts its context …". +READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context." + + AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it' @@ -26,7 +30,7 @@ def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: s """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project)) opening = f"{routed}\n\n" if routed else "" - return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" + return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" def routed_by(route: Route, project: Rung | None) -> str: diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 75c07afa..99de204a 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -53,7 +53,7 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." - ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal()) + ask = Ask(effects.new_id(), session, checkout, question, utc(effects.now()), OpenOnTerminal()) with listed(paths.waiting, ask, effects): unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), effects) if unstarted: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 4d7adeeb..5a2c5547 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -700,7 +700,7 @@ class Interrupts(unittest.TestCase): def ask(self, question="Which one?", state=None): """The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session.""" resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) - return Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or Asking(resumed)) + return Ask(ASK_ID, str(self.session.id), str(self.home), question, utc(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.""" @@ -861,7 +861,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(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, NOW, OpenOnTerminal())]) + self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, utc(NOW), OpenOnTerminal())]) return 0 self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD])) self.assertEqual(asks_and_answers(self.paths.waiting), []) @@ -1408,9 +1408,9 @@ class WorkerArgs(unittest.TestCase): def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed) + self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed) unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) - self.assertIn(f"before creating a new one.\n\n{self.FACTS}\n\nThe chunk's", unrouted) + self.assertIn(f"before creating a new one. {prompts.READING_RULE}\n\n{self.FACTS}\n\nThe chunk's", unrouted) self.assertNotIn("loop-claude runs you on", unrouted) def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): @@ -1420,6 +1420,12 @@ class WorkerArgs(unittest.TestCase): self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) + def test_gives_each_fresh_worker_the_reading_rule_once(self): + rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context" + for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))): + with self.subTest(route=route): + self.assertEqual(prompts.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1) + def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact.")) failed = prompts.preflight_failed("git could not start") @@ -1479,7 +1485,7 @@ class WorkerArgs(unittest.TestCase): self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus)) - self.assertIn("before creating a new one.\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS)) + self.assertIn(f"{prompts.READING_RULE}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS)) def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): opus = Rung("claude-opus-5-5", "medium") diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py index 1fd302dd..22fe7197 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -7,6 +7,7 @@ import pathlib import typing from loop_claude.hand_over import ClaudeCommand +from utc_stamp import seconds if typing.TYPE_CHECKING: from _typeshed import DataclassInstance @@ -45,20 +46,22 @@ class Ask: # The checkout the loop runs in. root: str question: str - # When the loop asked, in seconds since the epoch. - asked: float + # When the loop asked, as utc_stamp.utc writes it: an ISO UTC datetime. + asked: str 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.""" + """The ask in path; None where a field has the wrong type, asked is no stamp utc_stamp.utc writes, or the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) ask = Ask(**{**data, "state": ask_state(data["state"])}) + if not all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question, ask.asked)) or ask.session != path.stem: + return None + seconds(ask.asked) 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 + return ask def ask_state(data: object) -> AskState: diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 68c6abcf..0bc2e48c 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -13,6 +13,7 @@ import typing 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 +from utc_stamp import seconds ENTER = "enter" BACKSPACE = "backspace" @@ -108,7 +109,7 @@ def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[floa lines = [*wrapped(head, width), ""] for number, ask in enumerate(screen.shown, 1): state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}" - lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width) + lines += wrapped(f"[{number}] {ask.root}, {waiting_since(ask, now, local_time)}{state}", width) lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES) lines.append("") lines += running_lines(screen.running, screen.shown, width) @@ -139,7 +140,7 @@ def item_line(item: Taken | None) -> str: def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]: """The question, in lines of at most width characters, and its foot, the prompt for the answer.""" ask = screen.ask - head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):" + head = f"{ask.root}, {waiting_since(ask, now, local_time)}:" return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width) @@ -168,8 +169,14 @@ def cut(lines: list[str], count: int) -> list[str]: return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown -def waited(seconds: float) -> str: - minutes = int(seconds // 60) +def waiting_since(ask: Ask, now: float, local_time: typing.Callable[[float], str]) -> str: + """When ask's loop asked, in local time, and how long it has waited.""" + asked = seconds(ask.asked) + return f"waiting since {local_time(asked)} ({waited(now - asked)})" + + +def waited(span: float) -> str: + minutes = int(span // 60) if minutes < 60: return f"{minutes} min" hours, minutes = divmod(minutes, 60) diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index 8f30ca98..d406f917 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -24,6 +24,7 @@ from loop_claude.paths import paths_from from loop_claude import running_loops, session_lock from loop_claude.running_loops import RunningLoop, Taken from loop_claude.effects import system_effects +from utc_stamp import utc ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {})) # The pid of this loop-inbox. @@ -32,7 +33,7 @@ ANSWERED_ON_TERMINAL = object() def asked(session, root, question="Which one?", at=100.0, state=ASKING): - return Ask(f"ask-{session}", session, root, question, at, state) + return Ask(f"ask-{session}", session, root, question, utc(at), state) def loops_hold(test, folder, *sessions): @@ -141,6 +142,12 @@ class Answers(unittest.TestCase): with self.subTest(where=where): self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there.")) + def test_an_ask_file_says_when_the_loop_asked_as_an_iso_utc_datetime(self): + ask = asked("s1", "/code/log", at=100) + publish(self.folder, ask) + self.assertEqual(json.loads(ask_file(self.folder, "s1").read_text())["asked"], "1970-01-01T00:01:40Z") + self.assertEqual(read_ask(ask_file(self.folder, "s1")), ask) + def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self): ask = asked("s1", "/code/log") publish(self.folder, ask) @@ -392,6 +399,7 @@ class Waiting(unittest.TestCase): ("root", None), ("question", 3), ("asked", "noon"), + ("asked", 100.0), ("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}), ("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}), ): diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 01979067..485aed7e 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -31,7 +31,7 @@ cannot read. """ import json import os -import pathlib +import stat import sys import time import typing @@ -114,7 +114,10 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]: def read(path: str) -> str: + """path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it.""" try: - return pathlib.Path(path).read_text(encoding="utf-8") + # O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat. + with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened: + return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else "" except (OSError, UnicodeDecodeError): return "" diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 36a804c7..945d8d23 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -659,6 +659,14 @@ class Hook(unittest.TestCase): self.assertIn("Blocked by rule image-pin: ", ran.stderr) self.assertIn("`# rule-override image-pin: `", ran.stderr) + def test_an_edit_of_a_fifo_finishes(self): + fifo = f"{self.repo}/pipe" + os.mkfifo(fifo) + for tool, given in (("Write", {"content": "x\n"}), ("Edit", {"old_string": "a", "new_string": "b"}), ("MultiEdit", {"edits": [{"old_string": "a", "new_string": "b"}]})): + with self.subTest(tool=tool): + ran = hook({"cwd": self.repo, "tool_input": {"file_path": fifo, **given}, "tool_name": tool}, self.repo) + self.assertEqual(ran.returncode, 0) + def test_an_override_passes_and_is_listed_for_the_chunk(self): content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n" ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/sub/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index c04ef9a9..c3169fdd 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -109,6 +109,23 @@ class ChunkItem(unittest.TestCase): 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_counts_a_dated_changelog_heading_as_cut_on_a_branch_with_no_tag(self): + changelog = "# Changelog\n\n## Unreleased\n\n## 0.0.1 - 2026-10-03\n\n- Shipped.\n" + history = [HEADER + ROW.format(id=1, release="0.0.1"), HEADER] + self.assertEqual(chunk_pick.chunk_item([], chunk_pick.LastCut(None, changelog, 4, history)), chunk_pick.Unplanned(None)) + without_unreleased = chunk_pick.LastCut(None, "# Changelog\n\n## 0.0.1 - 2026-10-03\n", 4, history) + self.assertNotEqual(chunk_pick.chunk_item([], without_unreleased), chunk_pick.ReviewDue((0, 0, 1)), "0.0.1 is cut under its dated heading") + later = [HEADER + ROW.format(id=1, release="0.0.1") + ROW.format(id=2, release="0.1.0"), HEADER + ROW.format(id=2, release="0.1.0")] + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 1, 0)), chunk_pick.LastCut(None, changelog, 4, later)), chunk_pick.Next((0, 1, 0), one((0, 1, 0)))) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 0, 1)), chunk_pick.LastCut(None, changelog, 4, later)), chunk_pick.Cut((0, 0, 1))) + + def test_counts_neither_an_undated_heading_nor_a_heading_behind_a_tag_as_cut(self): + history = [HEADER + ROW.format(id=1, release="0.0.1"), HEADER] + undated = chunk_pick.LastCut(None, "# Changelog\n\n## 0.0.1\n\n- Shipped.\n", 4, history) + self.assertEqual(chunk_pick.chunk_item([], undated), chunk_pick.ReviewDue((0, 0, 1))) + tagged = chunk_pick.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 4, [HEADER + ROW.format(id=1, release="0.2.0")]) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 2, 0)), tagged), chunk_pick.Next((0, 2, 0), one((0, 2, 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]) @@ -140,6 +157,19 @@ class ChunkItem(unittest.TestCase): self.assertIsInstance(chunk_pick.release_reviewed("v9.9.9", "main", repo), Failure) self.assertEqual(chunk_pick.default_plan(repo, "main").cut.reviewed, True) + def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_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") + run("commit", "-q", "--allow-empty", "-m", "Release review of 0.0.1") + pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n") + run("add", "CHANGELOG.md") + run("commit", "-q", "-m", "Cut 0.0.1") + self.assertIs(chunk_pick.default_plan(repo, "main").cut.reviewed, False, "that review reviewed 0.0.1, which is cut") + run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0") + self.assertIs(chunk_pick.default_plan(repo, "main").cut.reviewed, True) + def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self): changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", changelog, 5, [])), 2) diff --git a/bin/utc_stamp.py b/bin/utc_stamp.py index 17542bc9..3ee83db9 100644 --- a/bin/utc_stamp.py +++ b/bin/utc_stamp.py @@ -1,3 +1,4 @@ +import calendar import time STAMP = "%Y-%m-%dT%H:%M:%SZ" @@ -6,3 +7,8 @@ STAMPED = r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ" def utc(at: float) -> str: return time.strftime(STAMP, time.gmtime(at)) + + +def seconds(stamp: str) -> int: + """The seconds since the epoch that stamp, as utc writes it, names; ValueError where it is no such stamp.""" + return calendar.timegm(time.strptime(stamp, STAMP)) diff --git a/docs/decisions.md b/docs/decisions.md index 683e6b0d..d24db79f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -84,20 +84,20 @@ loop-claude hands each worker's claude `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000` Why 200k. Item 231 asked for the best means to lower what a chunk spends on context, in dollars, then hours, with no loss of quality. Measured from loop-claude's archive, the 90 chunks with messages after the routing figures' reset of 2026-10-21 cost $1,215 at the list prices read on 2026-10-26 (Opus 5.5: $4 per million input tokens, $5 and $8 for 5-minute and 1-hour cache writes, $0.20 for cache reads, $20 for output; no model but Haiku 5.5 charges more above 200k). That is 0.86 of what the chunks' `cost-state` entries sum to, since some chunks' subagent transcripts are not in the archive. Worker main threads cost $375 (31%): 1-hour cache writes $149, cache reads $153, output $74. Subagents cost $840: 5-minute cache writes $379, output $274, cache reads $187, with the principles auditors at $274 over 342 runs, the stability reviewers $179 and general-purpose subagents $192. A worker starts at 41k tokens of context and peaks at a median 167k, one in ten past 358k, the largest at 848k. The worker's messages above 200k were 32% of its messages and 55% of its cost. -What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule (`todo.md` item 240), reviewers get no scout, and the principles audit keeps reading the project whole. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. +What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule, which every fresh worker prompt now holds (`READING_RULE` in `bin/loop_claude/cycle/prompts.py`) and `todo.md` item 260 keeps or drops, reviewers get no scout, and the principles audit keeps reading the project whole. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. The trials: four stability rounds and five principles rounds archived on 2026-10-23, each holding 🔴 or 🟡 findings, replayed on the project's rung as `review-replay` replays them, with the reviewer's definition changed through `--agents`; and three worker-like tasks, a search, a rename and an explanation, run on fresh clones at the project's rung. The baseline, the reviewer as it is, found 4 of its own 6 archived findings in each pass, so a variant that finds 4 or 5 of 6 does what the same reviewer does twice. The options todo item 231 named, each simulated on the 90 chunks and, where lilleman asked, tried: - Compaction of the worker. The saving and the compactions per chunk, by the point it compacts at: 150k saves $75 at 1.0 compactions; 167k to 180k, where a 200k window compacts, $77 to $78 at 0.8 to 0.7; 200k $78 at 0.5; 300k $54 at 0.2. $78 is 21% of the workers' $375 and 6% of all spend. Compaction also caps the 36 re-writes of a whole context after a gap longer than the cache's hour or a change of rung: they cost $61, up to 785k tokens each, and would cost about $34. Compacting subagents at 150k costs more than it saves, since a compaction reads the context once more and writes a summary, and subagents are short. - A fresh context for the review phase, handed 60k tokens of facts, saves $39. A compaction at 170k saves that too, and loop-claude would need a second session per chunk. -- Read with an offset and a limit, or Grep, in place of `cat`, `sed` and `head`. Steering the tool would not change how much is read: the worker's `sed` ranges are small already, and only 13% of its Bash-read characters came from whole files. A rule on how much to read did change it: under "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", the three worker tasks read 45% to 60% fewer characters at the same or lower cost, every task done as well, and the rename was the one run of four that also kept the import names sorted (`todo.md` item 240). A stability reviewer under the same rule with an `outline` script on PATH, which prints a file's symbols with their line ranges, read 4% less and found 2 of 6 findings, and the workers never ran the script. +- Read with an offset and a limit, or Grep, in place of `cat`, `sed` and `head`. Steering the tool would not change how much is read: the worker's `sed` ranges are small already, and only 13% of its Bash-read characters came from whole files. A rule on how much to read did change it: under "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", the three worker tasks read 45% to 60% fewer characters at the same or lower cost, every task done as well, and the rename was the one run of four that also kept the import names sorted. A stability reviewer under the same rule with an `outline` script on PATH, which prints a file's symbols with their line ranges, read 4% less and found 2 of 6 findings, and the workers never ran the script. - Code-intelligence tooling: the `LSP` tool, through a pyright plugin built from the marketplace manifest with `pyright-langserver` on PATH, answers a file's symbols, a definition or the references in a few hundred characters. Under a rule telling them to use it, the stability reviewers and the workers never called it; the auditors did, read as much or more, and missed the one 🔴, 0 of 1 against the baseline's 1 of 1. Each machine would also need a server per language (goal 2). Not worth an item. - A cap on tool results. Claude Code caps a Bash result at about 30k characters already. A PostToolUse hook capping it at 12k, which `updatedToolOutput` allows, left the stability reviewers 3 of 6 findings, two lost in one round. Read results, 59.9M characters in subagents' threads with 58% of their characters in results over 12k, are out of such a hook's reach. Not worth an item. - A scout: Haiku 5.5 reading raw content, whole files or long output, and returning facts as path:line and the ranges worth reading, so the agent's own context holds the summary and the chosen lines. In session, as an agent under `agents/`, its first request writes 37k tokens, $0.005, and a read of a 38KB file costs $0.008 in 8 seconds. As a slim headless `claude -p` with its own system prompt, no setting sources and no dynamic sections, which keeps the subscription login, it starts at 6k tokens and $0.0003 in 3 to 5 seconds, its prefix cached across calls, and the same read costs $0.004 in 7 seconds; a direct API call and `claude --bare` need an API key, so they are out. Stability reviewers with the agent scout found 5 of 6 findings and read 29% fewer characters at 6% less cost and 14% more time; with the CLI scout 4 of 6, 38% fewer, 17% less and 39% more; the auditors with the agent scout 3 of 6, the 🔴 among the lost, at the same cost and twice the time. Workers offered the scout never called it. - What a reviewer reads: the auditors read the project whole by design. Of their 🔴 and 🟡 findings since the reset, 47% named a file the chunk edited and 51% another file, so reading only the change would drop half of them (`review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies`). - The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions; `todo.md` item 52), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record. -Quality. 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Whether compaction raises unfinished verdicts stays open until `todo.md` item 235 measures it. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading. +Quality. 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Measured on 2026-11-04, the first 20 chunks whose worker started under the 200k window, from 2026-10-28, against the 20 before them, from 2026-10-23 to 2026-10-26, rose on no figure: per chunk, a mean 4.0 review rounds past each pass's first against 5.8, 0.20 unfinished verdicts against 0.30, 1.15 🔴 against 1.90, 11.9 🟡 against 19.4, 0.11 misread findings against 0.25, $22 against $34, and 9.6 hours against 42. The median dollars rose, $15.17 against $11.72, since the 20 before held four chunks of $94 to $167 and the 20 after none above $76; the mean weighs all spend, as this decision does. The two groups differ in projects and routing too, so the window's own share of the fall is unknown. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading. Hours. A chunk ran a median 0.7 hours from its first message to its last, one in ten past 12 hours, mostly waiting for the human or a usage limit. No option here changes that: a compaction takes 51 to 83 seconds, under a minute per chunk at 0.7 each, and a smaller context saves seconds per turn at most. Waiting on subagents took 66% of a worker's active time, so the hours lever is launching a round's reviewers together: larv-review §3 → "Waves" now launches each wave's reviewers in one message. diff --git a/todo.md b/todo.md index 1fd7e1ba..47c6520b 100644 --- a/todo.md +++ b/todo.md @@ -6,17 +6,12 @@ `Bar = 0.1` -`Next ID = 260` +`Next ID = 261` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 259 | 0.6.0 | | defect | **Make `chunk-preflight` count a version under a `## X.Y.Z - YYYY-MM-DD` heading in `CHANGELOG.md` as cut on a branch with no tag, and make its `--help` say what such a branch's next release is.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 3, code health by 2 | 12.1 | -| 235 | 0.6.0 | | decision | **Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 | -| 254 | 0.6.0 | | principle | **Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files.** | 1 | 1 | 2 | 2 | 2 | code health by 1 | 6.0 | -| 240 | 0.6.0 | | decision | **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.** | 1 | 2 | 3 | 4 | 2 | 1.4 by 3 | 4.0 | -| 249 | 0.6.0 | | | **Have rule-hook's Edit, MultiEdit and Write checks read only a regular file, so a FIFO or device as `file_path` no longer hangs or floods the hook.** | 1 | 1 | 3 | 3 | 2 | 1.5 by 2 | 2.6 | | 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | | 229 | 0.7.0 | | | **Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.** | 2 | 1 | 3 | 4 | 2 | code health by 3 | 18.0 | | 219 | 0.7.0 | | | **Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.** | 1 | 1 | 3 | 3 | 2 | code health by 2 | 12.0 | @@ -47,6 +42,7 @@ | 135 | 0.7.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 | | 171 | 0.7.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 4.0 | | 196 | 0.7.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 | +| 260 | 0.7.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 4.0 | | 68 | 0.7.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 | | 181 | 0.7.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 | | 192 | 0.7.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 | @@ -73,32 +69,6 @@ ## Details -### 259. Make `chunk-preflight` count a version under a `## X.Y.Z - YYYY-MM-DD` heading in `CHANGELOG.md` as cut on a branch with no tag, and make its `--help` say what such a branch's next release is. - -`chunk-preflight --help` says that where no tag names a version, the next release is todo.md's earliest. `next_release` in `bin/chunk_pick.py` also counts every release todo.md has ever named, as `test_reads_every_version_of_todo_md_where_the_branch_has_no_tag` pins, so that a release whose items are all done still reads as next. Neither reads a release heading in `CHANGELOG.md`. - -On 2026-11-04 this sent visthus's worker to a release review of 0.0.1, which its `CHANGELOG.md` already headed `## 0.0.1 - 2026-10-03`, on a repo with no tags. The worker had to stop and ask the owner, and a `## Renamed` line in `todo.md` was the only way past it. - -- Cut: a version under such a heading counts as cut where no tag does. A heading without a date, as this repo's `## 0.5.0`, doesn't count. Keep a tag ahead of any heading where a branch has one. -- Help: state both rules, so the text matches the code. -- Tests: one for an untagged branch whose newest release is under a heading, with its items done, which must no longer report a release review due for it, and one for a later release named in `todo.md`, which must read as next. - -### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose. - -`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged. - -### 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/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. - -lilleman's call, 2026-10-27, answering PR #376's trials, recorded in `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…`: three worker-like tasks each ran four ways, as workers run today, with an outline tool, with the LSP tool and under the rule, and only the rule cut reading, by 45% to 60%, at the same or lower cost and with the tasks done as well. The rule is for workers, so it goes into the prompt loop-claude gives a chunk's worker (`bin/loop_claude/cycle/prompts.py`), not into `CLAUDE.md`, which reviewers load too and where the one reviewer run under a like rule found 2 of 6 findings. A worker that reads less may misread more, so measure the 20 chunks after the rule merges against the 20 before, as item 235 measures the compaction window, and drop the rule where any of those figures rose. - -### 249. Have rule-hook's Edit, MultiEdit and Write checks read only a regular file, so a FIFO or device as `file_path` no longer hangs or floods the hook. - -Found by the stability review of PR #387. `read` in `bin/rule_hook/main.py`, which serves these checks, opens the target with `pathlib.Path(path).read_text` whatever it is. A FIFO without a writer hangs rule-hook until Claude Code's hook timeout, and a path such as `/dev/zero` makes it read without bound. rule-hook runs on every such call in every session. Reuse the check `modified` in the same file makes, `stat.S_ISREG` before any read, and have `read` return `""` for any other path. A test passes a FIFO and expects the check to finish. - ### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. @@ -237,6 +207,10 @@ Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far. +### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose. + +The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log -S READING_RULE` finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend. A worker that reads less may misread more, so a rise in misread findings drops the rule too. Wait for 20 such chunks before starting. + ### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan. "Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently. -- 2.52.0 From c134691c0127bcc68ede45d486d7896d175fac88 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:11:50 +0100 Subject: [PATCH 2/6] =?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?gs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 6f9155c1d0b3e28c168c526ef39ffba57ac45889 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:12:19 +0100 Subject: [PATCH 3/6] Sort the imports the chunk added --- bin/chunk_preflight/facts.py | 2 +- bin/loop_inbox/inbox.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 4f5520c8..95a8d79b 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,8 +1,8 @@ """The lines the preflight prints, stated from what it gathered.""" from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version +from chunk_pick import cut_name, LastCut, unreleased_entries from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran -from chunk_pick import cut_name, LastCut, unreleased_entries from chunk_preflight.choices import PULLS_LIST from markdown_text import quoted diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 0bc2e48c..2cb66a5c 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -12,8 +12,8 @@ import typing 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 from utc_stamp import seconds +from loop_claude.waiting.talk import TALK ENTER = "enter" BACKSPACE = "backspace" -- 2.52.0 From 45007d54f2d047acc15e08aa215906f72ae0ad20 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:14:51 +0100 Subject: [PATCH 4/6] =?UTF-8?q?Answer=20product-owner=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20count=20an?= =?UTF-8?q?=20untagged=20branch's=20unreleased=20commits=20from=20the=20co?= =?UTF-8?q?mmit=20that=20dated=20its=20heading,=20and=20drop=20the=20chang?= =?UTF-8?q?elog's=20advice=20to=20restart=20loops?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 ++-- bin/chunk_pick.py | 11 +++++++++-- bin/chunk_preflight/facts.py | 5 +++-- bin/chunk_preflight/main.py | 7 ++++--- bin/chunk_preflight/test_chunk_preflight.py | 1 + bin/test_chunk_pick.py | 4 ++++ 6 files changed, 23 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4338636..423fe7f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,9 @@ ## Unreleased - The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none. -- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. +- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. - `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file. -- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. Restart any `loop-claude` running when you deploy this release: until then, `loop-inbox` doesn't list its questions. +- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. A `loop-claude` running when you deploy reloads itself at its next cycle; `loop-inbox` doesn't list a question it asks before then, so answer that one on the loop's terminal. - Each chunk's first worker prompt now holds a 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. Once 20 chunks have run under it, a plan item measures them against the 20 before and drops the rule where any figure rose. ## 0.5.0 diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 93eb4db8..b50712a2 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -18,7 +18,7 @@ class LastCut: tag: str | None | Failure # CHANGELOG.md's text, empty where the branch holds none. changelog: str | Failure - # How many commits follow the tag, or make up the branch where it has none. + # How many commits follow the tag; on a branch with no tag, those after the commit that added the newest dated CHANGELOG.md heading, or all of them 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; where the branch has no tag, at each commit that changed it. Empty where the tags cannot be read. todos_since: list[str] | Failure @@ -93,13 +93,20 @@ class DefaultPlan: def default_plan(root: str, ref: str) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) - commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root) changelog = file_at(ref, "CHANGELOG.md", root) after = max(dated_headings(changelog), default=None) if tag is None else None + since = tag if after is None else heading_commit(after, ref, root) + commits = since if isinstance(since, Failure) else commits_since(since, ref, root) reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after) return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, changelog, commits, todos_since(tag, ref, root), reviewed)) +def heading_commit(release: tuple[int, int, int], ref: str, cwd: str) -> str | None | Failure: + """The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none.""" + added = git("log", "--reverse", "--format=%H", "-S", f"## {version(release)} - ", ref, "--", "CHANGELOG.md", cwd=cwd) + return added if isinstance(added, Failure) else next(iter(added.split()), None) + + def release_reviewed(tag: str | None, ref: str, cwd: str, after: tuple[int, int, int] | None = None) -> bool | Failure: """Whether ref holds, after tag or in all where tag is None, a commit titled as a release review opens: `Release review of `. Where after is given, the version a branch with no tag counts as cut, a title counts only where its release is later.""" titles = git("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd) diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 95a8d79b..bfddd55c 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,6 +1,6 @@ """The lines the preflight prints, stated from what it gathered.""" from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version -from chunk_pick import cut_name, LastCut, unreleased_entries +from chunk_pick import cut_name, dated_headings, LastCut, unreleased_entries from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran from chunk_preflight.choices import PULLS_LIST @@ -24,7 +24,8 @@ def last_release(default: str, release: LastCut) -> str: entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." - since = f"since {release.tag}" if release.tag else f"on {default}" + headed = max(dated_headings(release.changelog), default=None) if release.tag is None else None + since = f"since {release.tag}" if release.tag else f"since CHANGELOG.md dated {version(headed)}" if headed else f"on {default}" commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}" changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md" return f"{cut} Unreleased: {commits}; {changelog}." diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 313b4399..ca6c87ec 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -10,9 +10,10 @@ and quotes what it prints in the worker's prompt. It leaves the checkout as it i todo.md as the default branch holds it, the plan loop-claude routes on. It prints: - the last version cut, and how many entries the default branch's CHANGELOG.md holds under - ## Unreleased, or else how many commits followed the tag. The last cut is the newest v* tag on + ## Unreleased, or else how many commits followed the cut. The last cut is the newest v* tag on the default branch. On a branch with no tag, it is the newest version CHANGELOG.md heads - `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count; + `## X.Y.Z - YYYY-MM-DD`, and the commits counted follow the commit that added that heading; an + undated heading doesn't count; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I. An item waits while it is marked question, or while an item still in todo.md blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z @@ -21,7 +22,7 @@ todo.md as the default branch holds it, the plan loop-claude routes on. It print renamed, so a release whose items are all done still reads as next. Where the next release holds no item, it says so, naming it where todo.md named it since the cut: its release review due where changes are unreleased (the ## Unreleased entries, or else the - commits since the tag) and no commit titled `Release review of ` followed the tag, + commits since the cut) and no commit titled `Release review of ` followed the tag, finished and ready to cut once one did, and else to be planned first. On a branch with no tag, such a commit counts only where its is after the version under the dated heading. Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index d1e4c634..346c0502 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -369,6 +369,7 @@ class Render(unittest.TestCase): self.assertIn("1 commit on origin/main", untagged) headed = rendered(NoItem("x."), LastCut(None, "## 0.0.1 - 2026-10-03\n", 1, [])) self.assertIn("cut: 0.0.1, under CHANGELOG.md's dated heading, with no tag.", headed) + self.assertIn("1 commit since CHANGELOG.md dated 0.0.1", headed) def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self): said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), [])) diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index c3169fdd..2a66446f 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -167,6 +167,10 @@ class ChunkItem(unittest.TestCase): run("add", "CHANGELOG.md") run("commit", "-q", "-m", "Cut 0.0.1") self.assertIs(chunk_pick.default_plan(repo, "main").cut.reviewed, False, "that review reviewed 0.0.1, which is cut") + self.assertEqual(chunk_pick.default_plan(repo, "main").cut.commits, 0, "no commit follows the one that cut 0.0.1") + self.assertEqual(chunk_pick.chunk_item([], chunk_pick.default_plan(repo, "main").cut), chunk_pick.Unplanned(None)) + run("commit", "-q", "--allow-empty", "-m", "Ship item 2") + self.assertEqual(chunk_pick.default_plan(repo, "main").cut.commits, 1) run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0") self.assertIs(chunk_pick.default_plan(repo, "main").cut.reviewed, True) -- 2.52.0 From 0a475077564812ee3cf35ec3121446f940d831d6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:17:54 +0100 Subject: [PATCH 5/6] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20have=20the?= =?UTF-8?q?=20changelog=20restart=20loop-inbox,=20name=20the=20cut=20as=20?= =?UTF-8?q?dated=20in=20CHANGELOG.md,=20open=20the=20decision's=20Quality?= =?UTF-8?q?=20paragraph=20with=20the=20window's=20measurement,=20and=20mov?= =?UTF-8?q?e=20item=20260=20to=200.8.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 ++-- bin/chunk_pick.py | 11 +++++++---- bin/chunk_preflight/facts.py | 2 +- bin/chunk_preflight/main.py | 9 ++++----- bin/chunk_preflight/test_chunk_preflight.py | 4 ++-- bin/loop_claude/cycle/prompts.py | 2 +- bin/loop_claude/waiting/ask.py | 2 +- bin/utc_stamp.py | 2 +- docs/decisions.md | 4 ++-- todo.md | 10 +++++----- 10 files changed, 26 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 423fe7f1..08112e13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,8 @@ - The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none. - In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. - `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file. -- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. A `loop-claude` running when you deploy reloads itself at its next cycle; `loop-inbox` doesn't list a question it asks before then, so answer that one on the loop's terminal. -- Each chunk's first worker prompt now holds a 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. Once 20 chunks have run under it, a plan item measures them against the 20 before and drops the rule where any figure rose. +- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. Restart any `loop-inbox` running when you deploy: one started before doesn't list the new asks. A `loop-claude` running then reloads itself at its next cycle, and `loop-inbox` doesn't list a question it asks before that; answer such a question on the loop's terminal. +- Each chunk's first worker prompt now holds a 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. Where the 20 chunks after it take more review rounds, unfinished verdicts, findings, misread findings, dollars or hours than the 20 before, a later release drops it. ## 0.5.0 diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index b50712a2..0e12b872 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -108,7 +108,10 @@ def heading_commit(release: tuple[int, int, int], ref: str, cwd: str) -> str | N def release_reviewed(tag: str | None, ref: str, cwd: str, after: tuple[int, int, int] | None = None) -> bool | Failure: - """Whether ref holds, after tag or in all where tag is None, a commit titled as a release review opens: `Release review of `. Where after is given, the version a branch with no tag counts as cut, a title counts only where its release is later.""" + """Whether ref holds a commit titled as a release review opens, `Release review of `: after tag, or anywhere where tag is None. + + after is the version a branch with no tag counts as cut, or None. Where it is given, a title counts only where its release is later than after. + """ titles = git("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd) if isinstance(titles, Failure): return titles @@ -142,7 +145,7 @@ 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, the cut is cut_version's, so a release todo.md named whose items are all done still reads as the next release. + Where the branch has no tag, todos_since holds every version of todo.md, 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) version = cut_version(cut) @@ -161,7 +164,7 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: def cut_version(cut: LastCut) -> tuple[int, int, int] | None: - """The version cut counts as cut: its tag's; on a branch with no tag, the newest under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE. None where the tag names no version.""" + """Which version is cut. It is the tag's, or None where the tag names no version. On a branch with no tag, it is the newest version under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE.""" if cut.tag is None: return max(dated_headings(cut.changelog), default=BEFORE_FIRST_RELEASE) return version_of(cut.tag) @@ -172,7 +175,7 @@ def cut_name(cut: LastCut) -> str | None: if cut.tag is not None: return None if isinstance(cut.tag, Failure) else cut.tag headed = max(dated_headings(cut.changelog), default=None) - return None if headed is None else f"{version(headed)}, under CHANGELOG.md's dated heading" + return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" def dated_headings(changelog: str | Failure) -> list[tuple[int, int, int]]: diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index bfddd55c..d3d80e38 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -20,7 +20,7 @@ def last_release(default: str, release: LastCut) -> str: if isinstance(release.tag, Failure): return f"Last version cut: cannot be read: {release.tag.reason}" named = cut_name(release) - cut = f"Last version cut: {named or 'none'}{', with no tag' if named and release.tag is None else ''}." + cut = f"Last version cut: {named or 'none'}." entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index ca6c87ec..0fb3dc95 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -9,11 +9,10 @@ with --worktree at the checkout root before each chunk's first worker, before it and quotes what it prints in the worker's prompt. It leaves the checkout as it is, and reads todo.md as the default branch holds it, the plan loop-claude routes on. It prints: -- the last version cut, and how many entries the default branch's CHANGELOG.md holds under - ## Unreleased, or else how many commits followed the cut. The last cut is the newest v* tag on - the default branch. On a branch with no tag, it is the newest version CHANGELOG.md heads - `## X.Y.Z - YYYY-MM-DD`, and the commits counted follow the commit that added that heading; an - undated heading doesn't count; +- the last version cut: the newest v* tag on the default branch, or on a branch with no tag the + newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count. + Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how + many commits followed the cut: the tag, or the commit that added that heading; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I. An item waits while it is marked question, or while an item still in todo.md blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 346c0502..925d65b6 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -368,7 +368,7 @@ class Render(unittest.TestCase): self.assertIn("cut: none", untagged) self.assertIn("1 commit on origin/main", untagged) headed = rendered(NoItem("x."), LastCut(None, "## 0.0.1 - 2026-10-03\n", 1, [])) - self.assertIn("cut: 0.0.1, under CHANGELOG.md's dated heading, with no tag.", headed) + self.assertIn("cut: 0.0.1 (dated in CHANGELOG.md).", headed) self.assertIn("1 commit since CHANGELOG.md dated 0.0.1", headed) def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self): @@ -452,7 +452,7 @@ class Plans(unittest.TestCase): def test_names_a_release_cut_under_a_dated_heading_as_the_last_cut_on_a_branch_with_no_tag(self): said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main").why - self.assertIn("the next release after the last cut, 0.0.1, under CHANGELOG.md's dated heading", said) + self.assertIn("the next release after the last cut, 0.0.1 (dated in CHANGELOG.md)", said) def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self): named = "release 0.2.0, the next after the last cut, v0.1.0" diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 990037ac..7687ac67 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -19,7 +19,7 @@ EACH_SEAT = "each comprehension seat" THE_SECURITY_PASS = "the security pass's subagent" -# The worker's reading rule, from PR #376's trials, where it alone cut a worker's reading; it is the worker's, not CLAUDE.md's, since reviewers under a like rule missed findings: docs/decisions.md → "loop-claude: the worker's claude compacts its context …". +# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings. READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context." diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py index 22fe7197..a4ea0ec4 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -52,7 +52,7 @@ class Ask: def read_ask(path: pathlib.Path) -> Ask | None: - """The ask in path; None where a field has the wrong type, asked is no stamp utc_stamp.utc writes, or the ask names another session than path does.""" + """The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) ask = Ask(**{**data, "state": ask_state(data["state"])}) diff --git a/bin/utc_stamp.py b/bin/utc_stamp.py index 3ee83db9..c981626a 100644 --- a/bin/utc_stamp.py +++ b/bin/utc_stamp.py @@ -10,5 +10,5 @@ def utc(at: float) -> str: def seconds(stamp: str) -> int: - """The seconds since the epoch that stamp, as utc writes it, names; ValueError where it is no such stamp.""" + """The seconds since the epoch that stamp names, read in utc's format. Raises ValueError where time.strptime cannot read it so.""" return calendar.timegm(time.strptime(stamp, STAMP)) diff --git a/docs/decisions.md b/docs/decisions.md index d24db79f..559efc34 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -84,7 +84,7 @@ loop-claude hands each worker's claude `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000` Why 200k. Item 231 asked for the best means to lower what a chunk spends on context, in dollars, then hours, with no loss of quality. Measured from loop-claude's archive, the 90 chunks with messages after the routing figures' reset of 2026-10-21 cost $1,215 at the list prices read on 2026-10-26 (Opus 5.5: $4 per million input tokens, $5 and $8 for 5-minute and 1-hour cache writes, $0.20 for cache reads, $20 for output; no model but Haiku 5.5 charges more above 200k). That is 0.86 of what the chunks' `cost-state` entries sum to, since some chunks' subagent transcripts are not in the archive. Worker main threads cost $375 (31%): 1-hour cache writes $149, cache reads $153, output $74. Subagents cost $840: 5-minute cache writes $379, output $274, cache reads $187, with the principles auditors at $274 over 342 runs, the stability reviewers $179 and general-purpose subagents $192. A worker starts at 41k tokens of context and peaks at a median 167k, one in ten past 358k, the largest at 848k. The worker's messages above 200k were 32% of its messages and 55% of its cost. -What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule, which every fresh worker prompt now holds (`READING_RULE` in `bin/loop_claude/cycle/prompts.py`) and `todo.md` item 260 keeps or drops, reviewers get no scout, and the principles audit keeps reading the project whole. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. +What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule, reviewers get no scout, and the principles audit keeps reading the project whole. Every fresh worker prompt now holds that rule (`READING_RULE` in `bin/loop_claude/cycle/prompts.py`), and `todo.md` item 260 keeps or drops it. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. The trials: four stability rounds and five principles rounds archived on 2026-10-23, each holding 🔴 or 🟡 findings, replayed on the project's rung as `review-replay` replays them, with the reviewer's definition changed through `--agents`; and three worker-like tasks, a search, a rename and an explanation, run on fresh clones at the project's rung. The baseline, the reviewer as it is, found 4 of its own 6 archived findings in each pass, so a variant that finds 4 or 5 of 6 does what the same reviewer does twice. The options todo item 231 named, each simulated on the 90 chunks and, where lilleman asked, tried: @@ -97,7 +97,7 @@ The trials: four stability rounds and five principles rounds archived on 2026-10 - What a reviewer reads: the auditors read the project whole by design. Of their 🔴 and 🟡 findings since the reset, 47% named a file the chunk edited and 51% another file, so reading only the change would drop half of them (`review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies`). - The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions; `todo.md` item 52), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record. -Quality. 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Measured on 2026-11-04, the first 20 chunks whose worker started under the 200k window, from 2026-10-28, against the 20 before them, from 2026-10-23 to 2026-10-26, rose on no figure: per chunk, a mean 4.0 review rounds past each pass's first against 5.8, 0.20 unfinished verdicts against 0.30, 1.15 🔴 against 1.90, 11.9 🟡 against 19.4, 0.11 misread findings against 0.25, $22 against $34, and 9.6 hours against 42. The median dollars rose, $15.17 against $11.72, since the 20 before held four chunks of $94 to $167 and the 20 after none above $76; the mean weighs all spend, as this decision does. The two groups differ in projects and routing too, so the window's own share of the fall is unknown. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading. +Quality. Under the 200k window, every figure's mean per chunk fell. Measured on 2026-11-04, the first 20 chunks whose worker started under it, from 2026-10-28, took a mean 4.0 review rounds past each pass's first against 5.8 for the 20 before them, from 2026-10-23 to 2026-10-26; 0.20 unfinished verdicts against 0.30; 1.15 🔴 against 1.90; 11.9 🟡 against 19.4; 0.11 misread findings against 0.25; $22 against $34; and 9.6 hours against 42. Only the median dollars went up, $15.17 against $11.72: the 20 before held four chunks of $94 to $167, and the 20 after none above $76. This decision weighs all spend, so the mean is the figure that counts. The two groups also differ in projects and routing, so how much of the fall the window caused is unknown. Before the window, 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading. Hours. A chunk ran a median 0.7 hours from its first message to its last, one in ten past 12 hours, mostly waiting for the human or a usage limit. No option here changes that: a compaction takes 51 to 83 seconds, under a minute per chunk at 0.7 each, and a smaller context saves seconds per turn at most. Waiting on subagents took 66% of a worker's active time, so the hours lever is launching a round's reviewers together: larv-review §3 → "Waves" now launches each wave's reviewers in one message. diff --git a/todo.md b/todo.md index 47c6520b..4564d074 100644 --- a/todo.md +++ b/todo.md @@ -42,7 +42,6 @@ | 135 | 0.7.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 | | 171 | 0.7.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 4.0 | | 196 | 0.7.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 | -| 260 | 0.7.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 4.0 | | 68 | 0.7.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 | | 181 | 0.7.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 | | 192 | 0.7.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 | @@ -66,6 +65,7 @@ | 197 | 0.7.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 1.3 | | 170 | 0.8.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 | | 218 | 0.8.0 | 170 | | **Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines.** | 1 | 2 | 1 | 2 | 1 | code health by 2 | 14.4 | +| 260 | 0.8.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 4.0 | ## Details @@ -207,10 +207,6 @@ Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far. -### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose. - -The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log -S READING_RULE` finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend. A worker that reads less may misread more, so a rise in misread findings drops the rule too. Wait for 20 such chunks before starting. - ### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan. "Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently. @@ -340,3 +336,7 @@ The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/c ### 218. Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines. PR #357 archived the route as JSON on each `Worker:` line, and kept `LEGACY_WORKER` to read the lines an older loop-claude wrote as sentences. The routing figures still count chunks whose archive holds such lines: 51 when PR #357 shipped, every chunk finished after the reset of 2026-10-21T22:16:41Z. A chunk that changes the routing steps has a `Reset` appended to `routing-calls-raised.md`, after which the figures count only chunks whose worker lines are JSON. This item waits for item 170 whether or not 170 changes the steps, as lilleman decided on 2026-10-23. Before starting, check that `routing-calls-raised.md` holds a `Reset` stamped after PR #357's merge; where none does, ask lilleman whether to append one. Delete `LEGACY_WORKER`, `legacy_fields`, the tests that read sentences (in `bin/loop_claude/test_loop_claude.py` and `bin/routing_figures/test_routing_figures.py`), and the sentence on them in "loop-claude --help". Reword `route_from`'s docstring, and the comment at `Rung.__str__` in `bin/model_routing/ladder.py`, which gives the old lines as a reason `parse` must keep reading that spelling. + +### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose. + +Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend. -- 2.52.0 From 8a35412a0a98e56a2202211c380f7e4ee792d6de Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:25:16 +0100 Subject: [PATCH 6/6] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20keep=20Ask.?= =?UTF-8?q?asked=20in=20seconds=20and=20stamp=20it=20only=20in=20its=20fil?= =?UTF-8?q?e,=20keep=20the=20dated-heading=20rule=20in=20one=20function=20?= =?UTF-8?q?and=20the=20preflight's=20wording=20in=20chunk=5Fpreflight,=20m?= =?UTF-8?q?atch=20the=20heading=20line=20itself,=20and=20test=20a=20device?= =?UTF-8?q?=20path,=20a=20tagged=20repo=20with=20a=20dated=20heading,=20an?= =?UTF-8?q?=20untagged=20one=20without,=20and=20the=20wording=20where=20no?= =?UTF-8?q?thing=20is=20cut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_pick.py | 29 +++++++--------- bin/chunk_preflight/choices.py | 10 +++++- bin/chunk_preflight/facts.py | 6 ++-- bin/chunk_preflight/test_chunk_preflight.py | 6 ++++ bin/loop_claude/cycle/interrupt.py | 3 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_loop_claude.py | 4 +-- bin/loop_claude/waiting/ask.py | 19 ++++++----- bin/loop_claude/waiting/listing.py | 5 ++- bin/loop_inbox/inbox.py | 15 +++------ bin/loop_inbox/test_loop_inbox.py | 3 +- bin/rule_hook/test_rule_hook.py | 13 +++++--- bin/test_chunk_pick.py | 37 +++++++++++++++++++++ 13 files changed, 98 insertions(+), 54 deletions(-) diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 0e12b872..44ef3774 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -94,7 +94,7 @@ def default_plan(root: str, ref: str) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) changelog = file_at(ref, "CHANGELOG.md", root) - after = max(dated_headings(changelog), default=None) if tag is None else None + after = dated_cut(tag, changelog) since = tag if after is None else heading_commit(after, ref, root) commits = since if isinstance(since, Failure) else commits_since(since, ref, root) reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after) @@ -103,7 +103,9 @@ def default_plan(root: str, ref: str) -> DefaultPlan: def heading_commit(release: tuple[int, int, int], ref: str, cwd: str) -> str | None | Failure: """The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none.""" - added = git("log", "--reverse", "--format=%H", "-S", f"## {version(release)} - ", ref, "--", "CHANGELOG.md", cwd=cwd) + # -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count. + heading = "^## " + version(release).replace(".", "\\.") + " - [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$" + added = git("log", "--reverse", "--format=%H", "-G", heading, ref, "--", "CHANGELOG.md", cwd=cwd) return added if isinstance(added, Failure) else next(iter(added.split()), None) @@ -160,29 +162,22 @@ 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 == release and (earliest is not None or version == BEFORE_FIRST_RELEASE), landed(cut)) + nothing_cut = version == BEFORE_FIRST_RELEASE + return Upcoming(release, earliest == release and (earliest is not None or nothing_cut), landed(cut)) def cut_version(cut: LastCut) -> tuple[int, int, int] | None: """Which version is cut. It is the tag's, or None where the tag names no version. On a branch with no tag, it is the newest version under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE.""" if cut.tag is None: - return max(dated_headings(cut.changelog), default=BEFORE_FIRST_RELEASE) + return dated_cut(cut.tag, cut.changelog) or BEFORE_FIRST_RELEASE return version_of(cut.tag) -def cut_name(cut: LastCut) -> str | None: - """How the preflight names cut_version's cut: the tag, or the version under its dated heading; None where nothing is cut.""" - if cut.tag is not None: - return None if isinstance(cut.tag, Failure) else cut.tag - headed = max(dated_headings(cut.changelog), default=None) - return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" - - -def dated_headings(changelog: str | Failure) -> list[tuple[int, int, int]]: - """Each version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`, the heading a cut release takes; an undated heading is not cut.""" - if isinstance(changelog, Failure): - return [] - return [release_of(dated[1]) for heading in sections(changelog) if (dated := re.fullmatch(r"([0-9]+\.[0-9]+\.[0-9]+) - [0-9]{4}-[0-9]{2}-[0-9]{2}", heading))] +def dated_cut(tag: str | None | Failure, changelog: str | Failure) -> tuple[int, int, int] | None: + """The version a branch with no tag counts as cut: the newest CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`, the heading a cut release takes. None where the branch has a tag, or CHANGELOG.md has no such heading; an undated heading is not cut.""" + if tag is not None or isinstance(changelog, Failure): + return None + return max((release_of(dated[1]) for heading in sections(changelog) if (dated := re.fullmatch(r"([0-9]+\.[0-9]+\.[0-9]+) - [0-9]{4}-[0-9]{2}-[0-9]{2}", heading))), default=None) def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None: diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 6ffd4c5b..8d5e7ec2 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -2,7 +2,7 @@ import pathlib import re -from chunk_pick import chunk_item, Cut, cut_name, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned +from chunk_pick import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned from failure import Failure from chunk_preflight.gathered import Forge, NoItem, Plan from todo_table import item_details, items, NoItemsTable, version @@ -11,6 +11,14 @@ from todo_table import item_details, items, NoItemsTable, version PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} +def cut_name(cut: LastCut) -> str | None: + """How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut.""" + if cut.tag is not None: + return None if isinstance(cut.tag, Failure) else cut.tag + headed = dated_cut(cut.tag, cut.changelog) + return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" + + def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, chunk_pick.chunk_item's pick; else why there is none.""" where = f"{default}'s todo.md" diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index d3d80e38..f027f0a7 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,9 +1,9 @@ """The lines the preflight prints, stated from what it gathered.""" from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version -from chunk_pick import cut_name, dated_headings, LastCut, unreleased_entries +from chunk_preflight.choices import cut_name, PULLS_LIST +from chunk_pick import dated_cut, LastCut, unreleased_entries from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran -from chunk_preflight.choices import PULLS_LIST from markdown_text import quoted @@ -24,7 +24,7 @@ def last_release(default: str, release: LastCut) -> str: entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." - headed = max(dated_headings(release.changelog), default=None) if release.tag is None else None + headed = dated_cut(release.tag, release.changelog) since = f"since {release.tag}" if release.tag else f"since CHANGELOG.md dated {version(headed)}" if headed else f"on {default}" commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}" changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md" diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 925d65b6..dc7af3c9 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -454,6 +454,12 @@ class Plans(unittest.TestCase): said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main").why self.assertIn("the next release after the last cut, 0.0.1 (dated in CHANGELOG.md)", said) + def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self): + said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main").why + self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said) + self.assertIn("has landed yet.", said) + self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main").why) + def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self): named = "release 0.2.0, the next after the last cut, v0.1.0" unnamed = "the next release after the last cut, v0.1.0" diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 80482246..8798892d 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -14,7 +14,6 @@ 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 -from utc_stamp import utc ANSWER_QUESTION = "answer the question above" # ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. @@ -47,7 +46,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: P return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() - ask = Ask(effects.new_id(), str(session.id), session.root, question, utc(effects.now()), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) + ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) with listed(paths.waiting, ask, effects): answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal() if isinstance(answer, OpenOnTerminal | OpenInInbox): diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 99de204a..75c07afa 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -53,7 +53,7 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." - ask = Ask(effects.new_id(), session, checkout, question, utc(effects.now()), OpenOnTerminal()) + ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal()) with listed(paths.waiting, ask, effects): unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), effects) if unstarted: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index c83f5674..4dc81c9e 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -705,7 +705,7 @@ class Interrupts(unittest.TestCase): def ask(self, question="Which one?", state=None): """The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session.""" resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) - return Ask(ASK_ID, str(self.session.id), str(self.home), question, utc(NOW), state or 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.""" @@ -866,7 +866,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(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, utc(NOW), 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/ask.py b/bin/loop_claude/waiting/ask.py index a4ea0ec4..e67a228a 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -7,7 +7,7 @@ import pathlib import typing from loop_claude.hand_over import ClaudeCommand -from utc_stamp import seconds +from utc_stamp import seconds, utc if typing.TYPE_CHECKING: from _typeshed import DataclassInstance @@ -46,22 +46,25 @@ class Ask: # The checkout the loop runs in. root: str question: str - # When the loop asked, as utc_stamp.utc writes it: an ISO UTC datetime. - asked: str + # When the loop asked, in seconds since the epoch; its file holds it as an ISO UTC datetime, as ask_fields writes it. + asked: float state: AskState +def ask_fields(ask: Ask) -> dict[str, object]: + """ask as its file holds it, which read_ask reads back to the second.""" + return dataclasses.asdict(ask) | {"asked": utc(ask.asked), "state": tagged(ask.state)} + + def read_ask(path: pathlib.Path) -> Ask | None: """The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) - ask = Ask(**{**data, "state": ask_state(data["state"])}) - if not all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question, ask.asked)) or ask.session != path.stem: - return None - seconds(ask.asked) + ask = Ask(**{**data, "asked": seconds(data["asked"]), "state": ask_state(data["state"])}) except (OSError, ValueError, TypeError, KeyError): return None - return ask + texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question)) + return ask if texts and ask.session == path.stem else None def ask_state(data: object) -> AskState: diff --git a/bin/loop_claude/waiting/listing.py b/bin/loop_claude/waiting/listing.py index 2f0cadc7..041e3ae4 100644 --- a/bin/loop_claude/waiting/listing.py +++ b/bin/loop_claude/waiting/listing.py @@ -1,11 +1,10 @@ """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 -from loop_claude.waiting.ask import Ask, read_ask, tagged +from loop_claude.waiting.ask import Ask, ask_fields, read_ask from loop_claude.effects import Effects, say from loop_claude.session_lock import ended, running from failure import Failure @@ -21,7 +20,7 @@ def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: 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)}) + return replace_json(ask_file(folder, ask.session), ask_fields(ask)) def withdraw(folder: pathlib.Path, session: str) -> Failure | None: diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 2cb66a5c..68c6abcf 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -12,7 +12,6 @@ import typing from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal from loop_claude.running_loops import RunningLoop, Taken -from utc_stamp import seconds from loop_claude.waiting.talk import TALK ENTER = "enter" @@ -109,7 +108,7 @@ def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[floa lines = [*wrapped(head, width), ""] for number, ask in enumerate(screen.shown, 1): state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}" - lines += wrapped(f"[{number}] {ask.root}, {waiting_since(ask, now, local_time)}{state}", width) + lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width) lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES) lines.append("") lines += running_lines(screen.running, screen.shown, width) @@ -140,7 +139,7 @@ def item_line(item: Taken | None) -> str: def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]: """The question, in lines of at most width characters, and its foot, the prompt for the answer.""" ask = screen.ask - head = f"{ask.root}, {waiting_since(ask, now, local_time)}:" + head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):" return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width) @@ -169,14 +168,8 @@ def cut(lines: list[str], count: int) -> list[str]: return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown -def waiting_since(ask: Ask, now: float, local_time: typing.Callable[[float], str]) -> str: - """When ask's loop asked, in local time, and how long it has waited.""" - asked = seconds(ask.asked) - return f"waiting since {local_time(asked)} ({waited(now - asked)})" - - -def waited(span: float) -> str: - minutes = int(span // 60) +def waited(seconds: float) -> str: + minutes = int(seconds // 60) if minutes < 60: return f"{minutes} min" hours, minutes = divmod(minutes, 60) diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index d406f917..ff3a91ac 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -24,7 +24,6 @@ from loop_claude.paths import paths_from from loop_claude import running_loops, session_lock from loop_claude.running_loops import RunningLoop, Taken from loop_claude.effects import system_effects -from utc_stamp import utc ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {})) # The pid of this loop-inbox. @@ -33,7 +32,7 @@ ANSWERED_ON_TERMINAL = object() def asked(session, root, question="Which one?", at=100.0, state=ASKING): - return Ask(f"ask-{session}", session, root, question, utc(at), state) + return Ask(f"ask-{session}", session, root, question, at, state) def loops_hold(test, folder, *sessions): diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 945d8d23..87a6ad99 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -1,7 +1,9 @@ import datetime +import itertools import json import os import pathlib +import resource import subprocess import sys import tempfile @@ -659,12 +661,15 @@ class Hook(unittest.TestCase): self.assertIn("Blocked by rule image-pin: ", ran.stderr) self.assertIn("`# rule-override image-pin: `", ran.stderr) - def test_an_edit_of_a_fifo_finishes(self): + def test_an_edit_of_a_fifo_or_a_device_finishes(self): fifo = f"{self.repo}/pipe" os.mkfifo(fifo) - for tool, given in (("Write", {"content": "x\n"}), ("Edit", {"old_string": "a", "new_string": "b"}), ("MultiEdit", {"edits": [{"old_string": "a", "new_string": "b"}]})): - with self.subTest(tool=tool): - ran = hook({"cwd": self.repo, "tool_input": {"file_path": fifo, **given}, "tool_name": tool}, self.repo) + # A cap on the hook's memory, so a read of /dev/zero fails fast instead of filling the machine. + capped = lambda: resource.setrlimit(resource.RLIMIT_AS, (1 << 30, 1 << 30)) + for path, (tool, given) in itertools.product((fifo, "/dev/zero"), (("Write", {"content": "x\n"}), ("Edit", {"old_string": "a", "new_string": "b"}), ("MultiEdit", {"edits": [{"old_string": "a", "new_string": "b"}]}))): + with self.subTest(path=path, tool=tool): + call = {"cwd": self.repo, "tool_input": {"file_path": path, **given}, "tool_name": tool} + ran = subprocess.run([str(HOOK)], capture_output=True, cwd=self.repo, env=isolated_env(), input=json.dumps(call), preexec_fn=capped, text=True, timeout=10) self.assertEqual(ran.returncode, 0) def test_an_override_passes_and_is_listed_for_the_chunk(self): diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index 2a66446f..208b3aac 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -174,6 +174,43 @@ class ChunkItem(unittest.TestCase): run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0") self.assertIs(chunk_pick.default_plan(repo, "main").cut.reviewed, True) + def test_counts_from_the_commit_on_the_named_branch_that_first_added_the_dated_heading_to_changelog_md(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) + changelog = pathlib.Path(repo, "CHANGELOG.md") + run("init", "-q", "-b", "main") + pathlib.Path(repo, "notes.md").write_text("## 0.0.1 - 2026-10-01\n") + changelog.write_text("# Changelog\n\n## Unreleased\n\n- Quote `## 0.0.1 - 2026-10-02`.\n") + run("add", ".") + run("commit", "-q", "-m", "Notes and a quoted heading") + changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n") + run("commit", "-q", "-am", "Cut 0.0.1") + changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-04\n") + run("commit", "-q", "-am", "Fix 0.0.1's date") + run("commit", "-q", "--allow-empty", "-m", "Ship item 2") + run("checkout", "-q", "-b", "side") + run("commit", "-q", "--allow-empty", "-m", "Side work") + self.assertEqual(chunk_pick.default_plan(repo, "main").cut.commits, 2, "the commits after Cut 0.0.1 on main") + + def test_takes_the_tag_over_a_dated_heading_and_counts_every_commit_without_either(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") + pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.2.0")) + run("add", "todo.md") + run("commit", "-q", "-m", "Plan") + self.assertEqual(chunk_pick.default_plan(repo, "main").cut, chunk_pick.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False)) + run("tag", "v0.1.0") + pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.2.0 - 2026-10-03\n") + run("add", "CHANGELOG.md") + run("commit", "-q", "-m", "Date 0.2.0") + held = chunk_pick.default_plan(repo, "main") + self.assertEqual(held.todo, HEADER + ROW.format(id=1, release="0.2.0")) + self.assertEqual(held.cut, chunk_pick.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False)) + self.assertEqual(chunk_pick.chunk_item(plan_under((0, 2, 0)), held.cut), chunk_pick.Next((0, 2, 0), one((0, 2, 0)))) + def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self): changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", changelog, 5, [])), 2) -- 2.52.0