From 9066f477a42a6f5ffb1ce4b0bc1d7f0ef926009f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 19:52:08 +0100 Subject: [PATCH 1/7] Release review of 0.9.0 -- 2.52.0 From 5c3702704637fe3dea3ece6891d94af6380613e1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 20:05:52 +0100 Subject: [PATCH 2/7] =?UTF-8?q?Answer=20architecture=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20one=20reade?= =?UTF-8?q?r=20per=20message,=20prices=20and=20Spent=20block=20moved,=20on?= =?UTF-8?q?e=20table=20of=20larv-review=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_pr/main.py | 2 +- bin/claude_code/entries.py | 9 + bin/claude_code/test_claude_code.py | 7 + bin/larv_review/main.py | 78 ++--- bin/larv_review/scoring_setup.py | 38 +-- bin/larv_review/test_larv_review.py | 12 + bin/larv_review/test_scoring_setup.py | 20 +- bin/loop_claude/cycle/run.py | 2 +- bin/loop_claude/cycle/spend.py | 26 +- bin/loop_claude/test_loop_claude.py | 6 +- .../prices.py | 0 bin/reading_cost/measure.py | 5 +- bin/records/markdown_text.py | 30 +- bin/records/test_markdown_text.py | 11 + bin/review_replay/main.py | 267 +----------------- bin/review_replay/omit_comparison.py | 56 ++++ bin/review_replay/recall.py | 34 +++ bin/review_replay/replay.py | 179 ++++++++++++ bin/review_replay/rounds.py | 59 ++-- bin/review_replay/test_review_replay.py | 14 +- bin/review_rules/reviewer_context.py | 13 +- bin/review_rules/test_reviewer_context.py | 4 + bin/routing_figures/dollars.py | 15 +- bin/transcript_archive/outcomes.py | 18 +- docs/decisions.md | 2 +- reviewer-merge-trials/analyze_metered.py | 2 +- reviewer-merge-trials/driver.py | 4 +- skills/larv-review/SKILL.md | 2 + 28 files changed, 503 insertions(+), 412 deletions(-) rename bin/{routing_figures => model_routing}/prices.py (100%) create mode 100644 bin/review_replay/omit_comparison.py create mode 100644 bin/review_replay/replay.py diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 5d0c1e53..362db64e 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -115,7 +115,7 @@ def checkout(run: Run) -> tuple[Forge, str, str] | Failure: def default_branch(run: Run) -> str | Failure: - """origin's default branch, such as main.""" + """origin's default branch, such as main. Not git_cli's default_ref: that falls back to a local main or master and asks origin where nothing is recorded, but a pull request's base is origin's alone, and this tells the user how to record it.""" default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) if isinstance(default, Failure): return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}") diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index d7c06744..900ddb48 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -145,6 +145,15 @@ def tool_calls(entries: typing.Iterable[Entry]) -> list[tuple[AssistantTurn, Too return [(entry, part) for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, ToolCall)] +def messages(entries: typing.Iterable[Entry]) -> list[list[AssistantTurn]]: + """The assistant turns grouped by message, in the order each message first appears. A message's usage repeats in each of its entries, so read it from the first of a group: none of 1,681 multi-entry messages in the archive of 2026-10-28 differed.""" + grouped: dict[str, list[AssistantTurn]] = {} + for entry in entries: + if isinstance(entry, AssistantTurn): + grouped.setdefault(entry.message_id or entry.uuid, []).append(entry) + return list(grouped.values()) + + def field(found: dict, key: str) -> str: return value if isinstance(value := found.get(key), str) else "" diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index bb6aea1e..470ded3e 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -148,6 +148,13 @@ class EntryKinds(unittest.TestCase): uuid="u", parts=(entries.Text("Starting."), entries.ToolCall("toolu_1", "Bash", {"command": "ls"})), message_id="msg_1", model="claude-opus-5-5", usage={"input_tokens": 2}, )) + def test_messages_group_the_turns_that_share_a_message_id_and_fall_back_to_the_uuid_where_there_is_none(self): + first = entries.AssistantTurn(uuid="a", message_id="msg_1", usage={"input_tokens": 1}) + other = entries.AssistantTurn(uuid="b", message_id="msg_2") + again = entries.AssistantTurn(uuid="c", message_id="msg_1", usage={"input_tokens": 2}) + bare = entries.AssistantTurn(uuid="d") + self.assertEqual(entries.messages([first, entries.HumanTurn(text="hi"), other, again, bare]), [[first, again], [other], [bare]]) + def test_parses_tool_results_and_cost_states_and_reads_queued_notifications_and_other_kinds_as_plain_entries(self): self.assertEqual(entries.entry_from(human([{"type": "tool_result", "tool_use_id": "toolu_1", "content": "hi", "is_error": True}])), entries.ToolResults(results=(entries.ToolResult("toolu_1", "hi", True),))) self.assertEqual(entries.entry_from(queued("done", "task-notification")), entries.Entry()) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index c523b69f..b933c08e 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -1,6 +1,6 @@ """Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. -usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [...] | scoring-run-owed | record-ruling | prepare-scoring [--preloaded ] | record-scoring [...] | places | agreement | reviewer-header [--rerun] | reviewer-context +usage: larv-review {commands} The comprehension check records how hard a project is to read, two ways, and no score blocks a merge. In a paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better, @@ -167,45 +167,57 @@ from larv_review.scoring_setup import prepare_scoring from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places from larv_review.reviewer_header import reviewer_header -USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [...] | scoring-run-owed | record-ruling | prepare-scoring [--preloaded ] | record-scoring [...] | places | agreement | reviewer-header [--rerun] | reviewer-context" + +class Command(typing.NamedTuple): + """One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them.""" + shape: str + fits: typing.Callable[[list[str]], bool] + run: typing.Callable[[list[str]], Failure | None] + + +def no_arguments(given: list[str]) -> bool: + return not given + + +def are_ids(given: list[str]) -> bool: + return all(re.fullmatch(r"[0-9]+", id_) for id_ in given) + + +# One row per subcommand, in the order the usage line and the docstring above list them: main, USAGE and `--help` all read this table. +COMMANDS = { + "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), + "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)), + "round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)), + "needs-scoring-run": Command("needs-scoring-run [...]", are_ids, lambda given: with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)), + "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(owed, stale_ok=False)), + "record-ruling": Command("record-ruling ", lambda given: len(given) == 1, lambda given: record_ruling(pathlib.Path(given[0]))), + "prepare-scoring": Command("prepare-scoring [--preloaded ]", lambda given: not given or len(given) == 2 and given[0] == "--preloaded", lambda given: prepared_scoring(given[1] if given else None)), + "record-scoring": Command("record-scoring [...]", lambda given: bool(given) and are_ids(given[1:]), lambda given: with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)), + "places": Command("places", no_arguments, lambda given: show_places()), + "agreement": Command("agreement", no_arguments, lambda given: show_agreement()), + "reviewer-header": Command("reviewer-header [--rerun]", lambda given: given[:1] != [] and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]), lambda given: with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True)), + "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), +} +# The commands that take item IDs, each with the number of arguments before the IDs. +ID_COMMANDS = {"needs-scoring-run": 0, "record-scoring": 1} +SHAPES = " | ".join(command.shape for command in COMMANDS.values()) +USAGE = f"usage: larv-review {SHAPES}" def main(argv: list[str]) -> int: if argv in (["-h"], ["--help"]): - print(__doc__.strip().format(cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS)) + print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS)) return 0 - command, *given = argv or [""] - if command == "review-folder" and not given: - done = make_review_folder() - elif command == "ruling-base" and not given: - done = with_default_branch(show_ruling_base, stale_ok=False) - elif command == "round-count" and not given: - done = with_default_branch(round_count, stale_ok=True) - elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given): - done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False) - elif command == "scoring-run-owed" and not given: - done = with_default_branch(owed, stale_ok=False) - elif command == "record-ruling" and len(given) == 1: - done = record_ruling(pathlib.Path(given[0])) - elif command == "prepare-scoring" and (not given or len(given) == 2 and given[0] == "--preloaded"): - done = prepared_scoring(given[1] if given else None) - elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]): - done = with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False) - elif command == "places" and not given: - done = show_places() - elif command == "agreement" and not given: - done = show_agreement() - elif command == "reviewer-header" and given[:1] and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]): - done = with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True) - elif command == "reviewer-context" and not given: - done = printed(hook_reply(sys.stdin.read(), pathlib.Path.home())) - elif command in ("needs-scoring-run", "record-scoring") and given: - named = given[1:] if command == "record-scoring" else given - print(f"{command} takes item IDs, the numbers in todo.md's ID column, not {' '.join(id_ for id_ in named if not re.fullmatch(r'[0-9]+', id_))}; {USAGE}", file=sys.stderr) - return 1 - elif not argv: + if not argv: print(USAGE, file=sys.stderr) return 1 + name, *given = argv + command = COMMANDS.get(name) + if command and command.fits(given): + done = command.run(given) + elif command and name in ID_COMMANDS and (named := [id_ for id_ in given[ID_COMMANDS[name]:] if not re.fullmatch(r"[0-9]+", id_)]): + print(f"{name} takes item IDs, the numbers in todo.md's ID column, not {' '.join(named)}; {USAGE}", file=sys.stderr) + return 1 else: print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) return 1 diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py index efaefc69..130cddca 100644 --- a/bin/larv_review/scoring_setup.py +++ b/bin/larv_review/scoring_setup.py @@ -5,7 +5,7 @@ import re import shutil from failure import Failure -from records.markdown_text import FENCE, listed +from records.markdown_text import FENCE, listed, section from git_cli.git_repo import git from review_rules.review_folder import made_review_folder, review_folder @@ -23,26 +23,6 @@ FORBIDDEN_FILES = ("todo.md", "docs/decisions.md", "docs/comprehension-history.m FORBIDDEN = "todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' records and past chunks' reading cost)" TEST_FILE = re.compile(r"(^|/)(tests?/|test_[^/]*$|[^/]*_test\.[^/]*$|[^/]*\.(test|spec)\.[^/]*$)") TEST_FILES = "test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder" -HEADING = re.compile(r"^(#+)\s+(.*?)\s*$") - - -def section(text: str, title: str) -> list[str] | None: - """The lines under the first heading whose text fullmatches the pattern title, up to the next heading of its level or above; None where none does.""" - found: list[str] | None = None - level = 0 - fenced = False - for line in text.splitlines(): - if FENCE.match(line): - fenced = not fenced - heading = None if fenced else HEADING.match(line) - if found is None: - if heading and re.fullmatch(title, heading.group(2)): - found, level = [], len(heading.group(1)) - elif heading and len(heading.group(1)) <= level: - break - else: - found.append(line) - return found def bullets(lines: list[str]) -> list[list[str]]: @@ -62,12 +42,18 @@ def bullets(lines: list[str]) -> list[list[str]]: return groups +ANCHOR = re.compile(r"- \*\*\d+ — ") +DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency") + + def score_bullets(skill: str) -> tuple[list[str], list[str]] | Failure: - """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line.""" - groups = [[line.replace("**", "") for line in group] for group in bullets(section(skill, "The score") or [])] - if [len(group) for group in groups[:2]] != [6, 4]: - return Failure(f"{PANEL / 'SKILL.md'} → \"The score\" no longer opens with six anchor bullets and then four dimension bullets") - return groups[0], groups[1] + """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is one by how it opens, `- ** — ` or `- ****`, so other bullets and their order in the section change nothing.""" + lines = [line.replace("**", "") for group in bullets(section(skill, "The score") or []) for line in group if ANCHOR.match(line) or line.startswith(tuple(f"- **{name}**" for name in DIMENSIONS))] + anchors = [line for line in lines if line[2].isdigit()] + dimensions = [line for line in lines if not line[2].isdigit()] + if len(anchors) != 6 or [line.split(" — ")[0] for line in dimensions] != [f"- {name}" for name in DIMENSIONS]: + return Failure(f"{PANEL / 'SKILL.md'} → \"The score\" no longer holds six bullets opening `- ** — ` and four opening `- ****` for Navigation, Locality, Shape and Self-sufficiency, in that order") + return anchors, dimensions def project_values(text: str, source: str) -> dict[str, str] | Failure: diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 3c188c20..2e150352 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -872,6 +872,18 @@ class LarvReviewTool(unittest.TestCase): def test_review_folder_takes_no_arguments(self): self.assertIn("unknown arguments", self.run_tool("review-folder", "x").stderr) + def test_names_the_arguments_that_are_not_item_ids(self): + for args, named in ((("needs-scoring-run", "3", "x"), "x"), (("record-scoring", "scores.md", "4", "y1"), "y1")): + with self.subTest(args=args): + ran = self.run_tool(*args) + self.assertEqual(ran.returncode, 1) + self.assertIn(f"takes item IDs, the numbers in todo.md's ID column, not {named};", ran.stderr) + + def test_help_and_the_usage_line_list_the_same_commands(self): + listed = self.run_tool("--help").stdout.splitlines()[2].removeprefix("usage: larv-review ").split(" | ") + self.assertEqual([shape.split()[0] for shape in listed], ["review-folder", "ruling-base", "round-count", "needs-scoring-run", "scoring-run-owed", "record-ruling", "prepare-scoring", "record-scoring", "places", "agreement", "reviewer-header", "reviewer-context"]) + self.assertIn(f"usage: larv-review {' | '.join(listed)}", self.run_tool().stderr) + def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self): self.commit("Answer prose round 1: a") self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git")) diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 2e2311c3..eaace866 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -9,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from larv_review.scoring_setup import bullets, CLAUDE_MD, file_globs, preloaded_files, prepare_scoring, project_values, removed_setup, score_bullets, section +from larv_review.scoring_setup import bullets, CLAUDE_MD, file_globs, preloaded_files, prepare_scoring, project_values, removed_setup, score_bullets from failure import Failure from test_env import isolated_env @@ -27,6 +27,17 @@ class ScoreBullets(unittest.TestCase): self.assertEqual([line.split(" — ")[0] for line in dimensions], ["- Navigation", "- Locality", "- Shape", "- Self-sufficiency"]) self.assertEqual(dimensions[1], "- Locality — understanding and changing one piece without holding the rest: hidden state, order dependence, action at a distance.") + def test_reads_the_bullets_by_how_they_open_whatever_else_the_section_holds(self): + skill = SKILL.read_text() + with_extra = skill.replace("## The score\n\n", "## The score\n\n- A bullet before the anchors.\n\n", 1) + self.assertEqual(score_bullets(with_extra), score_bullets(skill)) + + def test_fails_where_an_anchor_or_a_dimension_is_missing(self): + skill = SKILL.read_text() + for dropped in ("- **10 — Duress-proof.**", "- **Shape** —"): + with self.subTest(dropped=dropped): + self.assertIsInstance(score_bullets(skill.replace(dropped, "- Dropped:", 1)), Failure) + class ProjectValues(unittest.TestCase): def test_reads_each_spelling_the_projects_use(self): @@ -56,13 +67,6 @@ class FileGlobs(unittest.TestCase): self.assertEqual(file_globs(paths), "`bin/**` except test files, `docs/**`, `README.md` and `ci.sh`, test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder") -class Section(unittest.TestCase): - def test_holds_deeper_headings_and_fenced_lines_and_ends_at_its_own_level(self): - text = "# P\n\n## Scoring run\n\na\n\n### Sub\n\n```\n## fenced\n```\n\n## Next\n\nb\n" - self.assertEqual(section(text, "Scoring run"), ["", "a", "", "### Sub", "", "```", "## fenced", "```", ""]) - self.assertIsNone(section(text, "Missing")) - - class Bullets(unittest.TestCase): def test_joins_continuations_and_splits_runs_at_other_lines(self): lines = [" stray", "- a ", " more", "Text", "- b", "", "- c"] diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 530084e3..d6dcf4af 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -181,7 +181,7 @@ def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judg if isinstance(subagents, Failure): return subagents spent = spend.spent(since, entries, subagents, judge_of(cycle).model, judged.tokens) - return outcomes.Annotation(cycle.config, spend.spent_block(since, spent), judged.reversed) + return outcomes.Annotation(cycle.config, outcomes.spent_block(since, spent), judged.reversed) def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> str: diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index e1db335a..68c125bf 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -7,16 +7,12 @@ import json import pathlib import typing -from claude_code.entries import AssistantTurn, Entry +from claude_code.entries import AssistantTurn, Entry, messages from failure import Failure -from routing_figures.prices import PRICES from claude_code.transcript import read_transcript -from transcript_archive.outcomes import SPENT +from transcript_archive.outcomes import Spender from claude_code.tokens import Tokens, tokens_of -KINDS = "input, cache write 5m, cache write 1h, cache read, output" -# Who spent, such as `worker`, `judge` or `Explore "Search the hooks"`, and the model they ran on. -Spender = tuple[str, str] WORKER = "worker" JUDGE = "judge" @@ -38,14 +34,10 @@ def spent(since: str, worker: list[Entry], subagents: list[Subagent], judge_mode def thread_spend(entries: list[Entry], since: str) -> dict[str, Tokens]: - """Each model's tokens in one transcript's messages written after since. A message's usage repeats in each entry of it, so each message counts once, by its id.""" + """Each model's tokens in one transcript's messages written after since. Each message counts once.""" start = moment(since) if since else None - counted: dict[str, AssistantTurn] = {} - for entry in entries: - if isinstance(entry, AssistantTurn) and entry.model and (start is None or later(entry.timestamp, start)): - counted.setdefault(entry.message_id or entry.uuid, entry) found: dict[str, Tokens] = {} - for turn in counted.values(): + for turn, *_ in messages(entry for entry in entries if isinstance(entry, AssistantTurn) and entry.model and (start is None or later(entry.timestamp, start))): found[turn.model] = found.get(turn.model, Tokens()).plus(tokens_of(turn.usage)) return found @@ -84,13 +76,3 @@ def subagent_name(transcript: pathlib.Path) -> str: # One line for the type, since a line break could forge an archive line such as `Config: `; json.dumps escapes the description's. kind, description = " ".join(str(meta.get("agentType") or "subagent").split()), str(meta.get("description") or "") return f"{kind} {json.dumps(description, ensure_ascii=False)}" if description else kind - - -def spent_block(since: str, found: dict[Spender, Tokens]) -> str: - """The archive's block for what the stretch spent, then the list prices in force for each model in it; empty where nothing was spent.""" - if not found: - return "" - spenders = [f"- {name}, {model}: {', '.join(map(str, (tokens.input, tokens.write_5m, tokens.write_1h, tokens.read, tokens.output)))}" for (name, model), tokens in found.items()] - priced = [f"- {model}: {price.input:g}, {price.write_5m:g}, {price.write_1h:g}, {price.read:g}, {price.output:g}" for model in dict.fromkeys(model for _, model in found) if (price := PRICES.get(model))] - prices = ["", f"List prices in dollars per million tokens of {KINDS}:", *priced] if priced else [] - return "\n".join([f"{SPENT}{since or 'the chunk began'}, in tokens of {KINDS}:", *spenders, *prices]) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 1b791e09..7232235b 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -1690,14 +1690,14 @@ class Spend(unittest.TestCase): def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self): found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)} - self.assertEqual(spend.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: + self.assertEqual(outcomes.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: - worker, claude-opus-5-5: 1, 2, 3, 4, 5 - judge, unpriced: 6, 0, 0, 0, 0 List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output: - claude-opus-5-5: 4, 5, 8, 0.2, 20""") - self.assertEqual(spend.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0") - self.assertEqual(spend.spent_block("", {}), "") + self.assertEqual(outcomes.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0") + self.assertEqual(outcomes.spent_block("", {}), "") def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self): shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name" diff --git a/bin/routing_figures/prices.py b/bin/model_routing/prices.py similarity index 100% rename from bin/routing_figures/prices.py rename to bin/model_routing/prices.py diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 9bc83e80..346b2cee 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -2,7 +2,7 @@ import collections import dataclasses import re -from claude_code.entries import AssistantTurn, Entry, parse_entry, tool_calls, ToolCall, usage_count +from claude_code.entries import AssistantTurn, Entry, messages, parse_entry, tool_calls, ToolCall, usage_count from git_cli.git_command import commits from reading_cost.shell_reads import Reads, shell_reads from command_lines.shell_command import resolved, simple_commands @@ -46,8 +46,7 @@ def commit_time(worker: list[Entry], home: str) -> str | None: def tokens_in(turns: list[AssistantTurn]) -> int: - usages = {turn.message_id or turn.uuid: turn.usage for turn in turns} - return sum(usage_count(usage, "input_tokens") + usage_count(usage, "cache_creation_input_tokens") for usage in usages.values()) + return sum(usage_count(first.usage, "input_tokens") + usage_count(first.usage, "cache_creation_input_tokens") for first, *_ in messages(turns)) def reads_of(call: ToolCall, cwd: str, home: str) -> Reads: diff --git a/bin/records/markdown_text.py b/bin/records/markdown_text.py index e9e37733..91fa97cb 100644 --- a/bin/records/markdown_text.py +++ b/bin/records/markdown_text.py @@ -2,10 +2,12 @@ import re import typing FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M) +HEADING = re.compile(r"^(#+)\s+(.*?)\s*$") -def sections(text: str) -> dict[str, list[str]]: - blocks: list[tuple[str | None, list[str]]] = [] +def fenced_lines(text: str) -> list[tuple[str, bool]]: + """Each line of text with whether a code fence holds it, the fence's own lines included. A fence closes only on a line of its own marker, as long as the opener or longer.""" + found = [] opener = "" for line in text.splitlines(): if fence := FENCE.match(line): @@ -14,7 +16,13 @@ def sections(text: str) -> dict[str, list[str]]: opener = marker elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip(): opener = "" - fenced = bool(opener or fence) + found.append((line, bool(opener or fence))) + return found + + +def sections(text: str) -> dict[str, list[str]]: + blocks: list[tuple[str | None, list[str]]] = [] + for line, fenced in fenced_lines(text): if not fenced and line.startswith("## "): blocks.append((line.strip()[3:], [])) elif not fenced and line.startswith("# "): @@ -28,6 +36,22 @@ def sections(text: str) -> dict[str, list[str]]: return found +def section(text: str, title: str) -> list[str] | None: + """The lines under the first heading whose text fullmatches the pattern title, up to the next heading of its level or above, blank lines kept; None where none does.""" + found: list[str] | None = None + level = 0 + for line, fenced in fenced_lines(text): + heading = None if fenced else HEADING.match(line) + if found is None: + if heading and re.fullmatch(title, heading.group(2)): + found, level = [], len(heading.group(1)) + elif heading and len(heading.group(1)) <= level: + break + else: + found.append(line) + return found + + # Blockquoted, so a passage holding blank lines still ends visibly where the text after it starts. def quoted(passage: str) -> str: return "\n".join(f"> {line}" for line in passage.splitlines()) diff --git a/bin/records/test_markdown_text.py b/bin/records/test_markdown_text.py index 92de02c5..d401a2be 100644 --- a/bin/records/test_markdown_text.py +++ b/bin/records/test_markdown_text.py @@ -21,6 +21,17 @@ class Sections(unittest.TestCase): self.assertEqual(markdown_text.quoted("merged\n\nPR #1"), "> merged\n> \n> PR #1") +class Section(unittest.TestCase): + def test_holds_deeper_headings_and_fenced_lines_and_ends_at_its_own_level(self): + text = "# P\n\n## Scoring run\n\na\n\n### Sub\n\n```\n## fenced\n```\n\n## Next\n\nb\n" + self.assertEqual(markdown_text.section(text, "Scoring run"), ["", "a", "", "### Sub", "", "```", "## fenced", "```", ""]) + self.assertIsNone(markdown_text.section(text, "Missing")) + + def test_a_fence_closes_only_on_its_own_marker_here_too(self): + text = "## A\n````md\n```\n## Quoted\n````\n## B\n" + self.assertEqual(markdown_text.section(text, "A"), ["````md", "```", "## Quoted", "````"]) + + class Listed(unittest.TestCase): def test_joins_names_with_commas_and_the_conjunction_before_the_last(self): self.assertEqual(markdown_text.listed(["a"], "and"), "a") diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index c05f0e16..8e422b75 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -50,47 +50,26 @@ review or match leaves its round out, except on a rung below the project's, wher nothing. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived round to replay, or a usage limit. """ -import dataclasses -import json -import os import pathlib -import shutil import sys -import tempfile import typing from transcript_archive.location import archive_root -from rung_replay.command import arguments_or_exit, failed, limited_exit, projects_on -from review_replay.rounds import authored_by, comparison, lost_inputs, reviewed_path, Round, round_from, sample, stamp_seconds -from review_replay.recall import candidates, enough, needed, Recall, recall_report, Reference, RungRecall, tried -from transcript_archive.project_key import checkout_of -from claude_code.reply import claude_reply, Limited +from review_replay.rounds import archived_rounds, Round, sample +from rung_replay.command import arguments_or_exit, failed, limited_exit +from review_replay.replay import codes_found, findings_replayed +from review_replay.omit_comparison import compared from loop_effects.effects import Effects from failure import Failure -from rung_replay.search import first_reply, replayed_on -from claude_code.transcript import first_timestamped_line, read_transcript -from claude_code.entries import parse_entry, structured_output -from review_rules.reviewer_context import principles_line, reviewer_context +from claude_code.reply import Limited from model_routing.ladder import project_rung, Rung -from review_rules.review_folder import REPORTS, review_folder +from review_replay.recall import recall_report, recalled from review_rules.review_passes import ReviewedPass, REVIEWERS TOOL = "review-replay" OMIT = "--omit-claude-md" -# Starts claude without its instruction files, as `omitClaudeMd` starts a subagent. -NO_CLAUDE_MD = ["--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})] USAGE = f"{TOOL} [{OMIT}], one of {', '.join(REVIEWERS)} and a model on the routing ladder" LATEST = 10 -MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False} - - -@dataclasses.dataclass(frozen=True) -class Code: - """Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began.""" - path: str - reviewed: str - default: str - base: str def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int: @@ -106,7 +85,11 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find") chosen = sample(list(codes), LATEST) if without: - return compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare)) + report = compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare)) + if isinstance(report, Limited): + return limited_exit(TOOL, report) + print(report) + return 0 def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited: matched = findings_replayed(found, codes[found], rung, project, home, effects, False) @@ -121,57 +104,6 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff return 0 -def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited: - """Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify.""" - runs: list[list[set[int] | Failure]] = [] - for _ in range(2): - found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what) - if isinstance(found, Limited): - return found - runs.append(found) - rounds: list[Round] = [] - reference: Reference = ([], []) - for one, first, second in zip(chosen, *runs): - if not isinstance(first, Failure) and not isinstance(second, Failure): - rounds.append(one) - reference[0].append(first) - reference[1].append(second) - recalls: list[RungRecall] = [] - lowest = None - for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []: - on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what) - if isinstance(on_rung, Limited): - return on_rung - # A failed replay on a candidate found nothing, so it lowers that rung's count and never lifts it to what a rung needs. - one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung]) - recalls.append(one) - if not one.qualifies: - break - lowest = rung - return Recall(rounds, reference, len(chosen) - len(rounds), recalls, lowest) - - -def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing.Callable[[Round, bool], set[int] | Failure | Limited]) -> int: - """Replays chosen three times with CLAUDE.md and once without, as found_on(round, bare) finds, and prints the comparison of the rounds no replay failed on.""" - runs: list[list[set[int] | Failure]] = [] - for bare in (False, False, False, True): - def replay_one(one: Round, _: Rung, bare: bool = bare) -> set[int] | Failure | Limited: - found = found_on(one, bare) - if isinstance(found, Failure): - print(f" {one.root} {one.at} {'without' if bare else 'with'} the instruction files failed, so the round is left out: {found.reason}", file=sys.stderr, flush=True) - return found - - found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {'without' if bare else 'with'} the instruction files") - if isinstance(found, Limited): - return limited_exit(TOOL, found) - runs.append(found) - # A failed replay found nothing, which would lower the bar where it had CLAUDE.md and count as misses where it had none. - kept = [(one, *found) for one, *found in zip(chosen, *runs) if not any(isinstance(each, Failure) for each in found)] - first, second, third, without = ([typing.cast(set[int], found[run]) for _, *found in kept] for run in range(4)) - print(comparison(reviewed, project, [one for one, *_ in kept], (first, second, third), without, len(chosen) - len(kept))) - return 0 - - def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None: """The pass, the project's rung of the model, and whether OMIT follows, as argv names them in ` [--omit-claude-md]`; None for any other argv.""" if argv[2:] not in ([], [OMIT]) or len(argv) < 2: @@ -179,180 +111,3 @@ def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None: reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None) project = project_rung(argv[1]) return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None - - -def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]: - """The code each round reviewed, as code_of finds it; stderr names each round left out, and why.""" - codes = {} - for found in rounds: - if isinstance(code := code_of(found, effects), Failure): - print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True) - else: - codes[found] = code - return codes - - -def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure: - projects = projects_on(model, home) - if isinstance(projects, Failure): - return projects - found = [] - try: - for key in projects: - for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()): - found += chunk_rounds(reviewer, checkout_of(key, home), chunk) - except (OSError, UnicodeDecodeError, ValueError) as failure: - return Failure(f"could not read the archive {root}: {failure}") - return found - - -def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]: - copies = sorted(chunk.glob("*.jsonl")) - began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None - if not began or not began.timestamp: - return [] - found = [] - for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")): - described = json.loads(meta.read_text(encoding="utf-8")) - if not isinstance(described, dict) or described.get("agentType") != reviewer: - continue - entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl"))) - if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began.timestamp), entries)): - found.append(one) - return found - - -def code_of(found: Round, effects: Effects) -> Code | Failure: - """Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then. - - Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess shows every rung the same wrong code: the project's rung finds fewer of that round's archived findings, which lowers the bar, and the rungs below find fewer too. - """ - if not os.path.isdir(found.root): - return Failure("the project has no checkout") - path = reviewed_path(found.prompt, found.root, os.path.exists) - if path is None: - return Failure("the prompt names neither one removed worktree nor the checkout") - default = effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=found.root) - if isinstance(default, Failure): - return default - default = default.strip().removeprefix("origin/") - log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root) - main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root) - if isinstance(log, Failure): - return log - if isinstance(main_line, Failure): - return main_line - reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began) - if reviewed is None or base is None: - return Failure("no commit was authored by then") - return Code(path, reviewed, default, base) - - -def commit_log(listed: str) -> list[tuple[str, float]]: - return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())] - - -def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> set[int] | Failure | Limited: - """The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where bare, the replay runs without CLAUDE.md, as `launch` says.""" - reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, bare)) - if isinstance(reviewed, (Failure, Limited)): - return reviewed - return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects)) - - -@dataclasses.dataclass(frozen=True) -class Copies: - """The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder.""" - clone: str - reports: str - - -# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument. -def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited: - try: - (home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports: - return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, bare) - except OSError as failure: - return Failure(f"could not prepare the replay: {failure}") - - -def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited: - """The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports; without CLAUDE.md where bare.""" - folder = pathlib.Path(review_folder(str(home), code.path)) - copy_reports(found, folder, copies.reports) - prompt = redirected(found.prompt, home, folder, code.path, copies) - if isinstance(prompt, Failure): - return prompt - if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()): - return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's") - if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure): - return cloned - launched = launch(found.reviewer, rung, prompt, copies.clone, home, bare) - if isinstance(launched, Failure): - return launched - reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude") - if isinstance(reply, Failure | Limited): - return reply - return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report") - - -def launch(reviewer: str, rung: Rung, prompt: str, clone: str, home: pathlib.Path, bare: bool) -> tuple[list[str], str] | Failure: - """claude's arguments and prompt for reviewer on rung. Where bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer.""" - args = ["--agent", reviewer, *rung.flags()] - if not bare: - return args, prompt - context = reviewer_context(home) - if isinstance(context, Failure): - return context - return [*args, *NO_CLAUDE_MD], "\n".join([f"{context}\n\n{prompt}", *([principles] if (principles := principles_line(clone)) else [])]) - - -def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None: - """Copies into reports each report written to folder after found's chunk began and before its round did.""" - # The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find. - for written in folder.iterdir() if folder.is_dir() else (): - if written.is_file() and found.began <= written.stat().st_mtime < found.seconds: - shutil.copy2(written, reports) - - -def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure: - """prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder.""" - # Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's. - prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone) - # A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it. - if REPORTS in prompt.replace(copies.reports, ""): - return Failure("the prompt names the review folder in a spelling the replay does not redirect") - return prompt - - -def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None: - """Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began.""" - for command in ( - ("clone", "--quiet", "--shared", "--no-checkout", found.root, clone), - ("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base), - ("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base), - ("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed), - ): - if isinstance(ran := effects.git(*command, cwd=found.root), Failure): - return ran - return None - - -def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited: - numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1)) - prompt = ( - "A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. " - "List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. " - "A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n" - f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}" - ) - args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""] - reply = claude_reply(effects.claude, args, root, prompt, "claude") - if isinstance(reply, Failure | Limited): - return reply - output = structured_output(reply) - numbers = output.get("found") if isinstance(output, dict) else None - if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers): - return Failure(f"the match replied: {json.dumps(reply)}") - return {n - 1 for n in numbers if 1 <= n <= len(findings)} diff --git a/bin/review_replay/omit_comparison.py b/bin/review_replay/omit_comparison.py new file mode 100644 index 00000000..5bd4ac78 --- /dev/null +++ b/bin/review_replay/omit_comparison.py @@ -0,0 +1,56 @@ +"""The experiment behind review-replay's --omit-claude-md: three replays of a pass's rounds with CLAUDE.md, one without, and the report that holds the one without to what the others found: docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed`.""" +import sys +import typing + +from failure import Failure +from claude_code.reply import Limited +from rung_replay.search import replayed_on +from review_replay.rounds import Round +from model_routing.ladder import Rung + + +def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing.Callable[[Round, bool], set[int] | Failure | Limited]) -> str | Limited: + """Replays chosen three times with CLAUDE.md and once without, as found_on(round, bare) finds, and reports the comparison of the rounds no replay failed on; the Limited where claude hit its usage limit.""" + runs: list[list[set[int] | Failure]] = [] + for bare in (False, False, False, True): + def replay_one(one: Round, _: Rung, bare: bool = bare) -> set[int] | Failure | Limited: + found = found_on(one, bare) + if isinstance(found, Failure): + print(f" {one.root} {one.at} {'without' if bare else 'with'} the instruction files failed, so the round is left out: {found.reason}", file=sys.stderr, flush=True) + return found + + found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {'without' if bare else 'with'} the instruction files") + if isinstance(found, Limited): + return found + runs.append(found) + # A failed replay found nothing, which would lower the bar where it had CLAUDE.md and count as misses where it had none. + kept = [(one, *found) for one, *found in zip(chosen, *runs) if not any(isinstance(each, Failure) for each in found)] + first, second, third, without = ([typing.cast(set[int], found[run]) for _, *found in kept] for run in range(4)) + return comparison(reviewed, project, [one for one, *_ in kept], (first, second, third), without, len(chosen) - len(kept)) + + +def comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str: + """What the three replays with CLAUDE.md and the one without found in rounds. Each replay with it missed some findings the other two found: the control, the noise of an unchanged reviewer. The one without it is held to the findings the first two found, as the third is, and passes where it missed no more than the most a replay with it did. left_out counts the rounds a replay failed on, which rounds leaves out.""" + first, second, third = with_it + + def shared(one: list[set[int]], other: list[set[int]]) -> list[set[int]]: + return [found_by_one & found_by_other for found_by_one, found_by_other in zip(one, other)] + + def missing(held: list[set[int]], run: list[set[int]]) -> list[tuple[Round, int]]: + return [(found_round, index) for found_round, held_in_round, found in zip(rounds, held, run) for index in sorted(held_in_round - found)] + + def count(run: list[set[int]]) -> int: + return sum(len(found) for found in run) + + both = shared(first, second) + missed = missing(both, without) + control = [len(missing(shared(one, other), run)) for run, one, other in ((first, second, third), (second, first, third), (third, first, second))] + passes = len(missed) <= max(control) + return "\n".join([ + f"Replayed {len(rounds)} {reviewed} rounds of {reference.model} projects, which hold {sum(len(found_round.findings) for found_round in rounds)} 🔴 and 🟡 findings, four times on {reference}: three with CLAUDE.md, one without.", + *([f"Left out {left_out} more, which a replay failed on; stderr says why."] if left_out else []), + f"With CLAUDE.md the three replays found {count(first)}, {count(second)} and {count(third)} of them, and missed {control[0]}, {control[1]} and {control[2]} of the findings that both of the other two found.", + *([f"Without CLAUDE.md it found {count(without)} of them, and missed {len(missed)} of the {count(both)} findings that both of the first two found{':' if missed else '.'}"] if count(both) else [f"Without CLAUDE.md it found {count(without)} of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to."]), + *(f" {found_round.root} {found_round.at}: {found_round.findings[index].splitlines()[0]}" for found_round, index in missed), + *([f"It {'passes' if passes else 'fails'}: {len(missed)} missed is {'no more' if passes else 'more'} than the most a replay with CLAUDE.md missed, {max(control)}."] if count(both) else []), + ]) diff --git a/bin/review_replay/recall.py b/bin/review_replay/recall.py index 0e50519f..77fe957c 100644 --- a/bin/review_replay/recall.py +++ b/bin/review_replay/recall.py @@ -1,10 +1,14 @@ """The bar review-replay holds a rung to, and its report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.""" import dataclasses from rung_replay.command import down_from +from failure import Failure from fractions import Fraction from review_replay.rounds import is_red, Round from model_routing.ladder import LADDER, Rung +from claude_code.reply import Limited import math +from rung_replay.search import replayed_on +import typing # A rung qualifies with a share of the archived findings up to this far below the project's rung's. The project's rung found 69 to 78% of its own findings again, and its two replays of the same rounds differed by up to 4 points. MARGIN = Fraction(1, 10) @@ -91,3 +95,33 @@ def recall_report(reviewed: str, project: Rung, recall: Recall) -> str: def percent(fraction: Fraction) -> str: return f"{float(fraction):.0%}" + + +def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited: + """Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify.""" + runs: list[list[set[int] | Failure]] = [] + for _ in range(2): + found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what) + if isinstance(found, Limited): + return found + runs.append(found) + rounds: list[Round] = [] + reference: Reference = ([], []) + for one, first, second in zip(chosen, *runs): + if not isinstance(first, Failure) and not isinstance(second, Failure): + rounds.append(one) + reference[0].append(first) + reference[1].append(second) + recalls: list[RungRecall] = [] + lowest = None + for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []: + on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what) + if isinstance(on_rung, Limited): + return on_rung + # A failed replay on a candidate found nothing, so it lowers that rung's count and never lifts it to what a rung needs. + one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung]) + recalls.append(one) + if not one.qualifies: + break + lowest = rung + return Recall(rounds, reference, len(chosen) - len(rounds), recalls, lowest) diff --git a/bin/review_replay/replay.py b/bin/review_replay/replay.py new file mode 100644 index 00000000..5fc68bc6 --- /dev/null +++ b/bin/review_replay/replay.py @@ -0,0 +1,179 @@ +"""Replay one archived review round on one rung: the code the round reviewed, found again in a throwaway clone, the reviewer's report on it, and the match of that report to the round's archived findings: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.""" +import dataclasses +import json +import os +import pathlib +import shutil +import sys +import tempfile + +from review_replay.rounds import authored_by, lost_inputs, reviewed_path, Round +from claude_code.reply import claude_reply, Limited +from git_cli.git_repo import default_ref +from loop_effects.effects import Effects +from failure import Failure +from rung_replay.search import first_reply +from review_rules.reviewer_context import principles_line, reviewer_context +from review_rules.review_folder import REPORTS, review_folder +from model_routing.ladder import Rung +from claude_code.entries import structured_output + +# Starts claude without its instruction files, as `omitClaudeMd` starts a subagent. +NO_CLAUDE_MD = ["--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})] +MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False} + + +@dataclasses.dataclass(frozen=True) +class Code: + """Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began.""" + path: str + reviewed: str + default: str + base: str + + +def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]: + """The code each round reviewed, as code_of finds it; stderr names each round left out, and why.""" + codes = {} + for found in rounds: + if isinstance(code := code_of(found, effects), Failure): + print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True) + else: + codes[found] = code + return codes + + +def code_of(found: Round, effects: Effects) -> Code | Failure: + """Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then. + + Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess shows every rung the same wrong code: the project's rung finds fewer of that round's archived findings, which lowers the bar, and the rungs below find fewer too. + """ + if not os.path.isdir(found.root): + return Failure("the project has no checkout") + path = reviewed_path(found.prompt, found.root, os.path.exists) + if path is None: + return Failure("the prompt names neither one removed worktree nor the checkout") + ref = default_ref(cwd=found.root, guarded=True, run=effects.git) + if isinstance(ref, Failure): + return ref + default = ref.removeprefix("origin/") + log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root) + main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root) + if isinstance(log, Failure): + return log + if isinstance(main_line, Failure): + return main_line + reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began) + if reviewed is None or base is None: + return Failure("no commit was authored by then") + return Code(path, reviewed, default, base) + + +def commit_log(listed: str) -> list[tuple[str, float]]: + return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())] + + +def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> set[int] | Failure | Limited: + """The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where bare, the replay runs without CLAUDE.md, as `launch` says.""" + reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, bare)) + if isinstance(reviewed, (Failure, Limited)): + return reviewed + return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects)) + + +@dataclasses.dataclass(frozen=True) +class Copies: + """The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder.""" + clone: str + reports: str + + +# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument. +def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited: + try: + (home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports: + return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, bare) + except OSError as failure: + return Failure(f"could not prepare the replay: {failure}") + + +def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited: + """The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports; without CLAUDE.md where bare.""" + folder = pathlib.Path(review_folder(str(home), code.path)) + copy_reports(found, folder, copies.reports) + prompt = redirected(found.prompt, home, folder, code.path, copies) + if isinstance(prompt, Failure): + return prompt + if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()): + return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's") + if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure): + return cloned + launched = launch(found.reviewer, rung, prompt, copies.clone, home, bare) + if isinstance(launched, Failure): + return launched + reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude") + if isinstance(reply, Failure | Limited): + return reply + return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report") + + +def launch(reviewer: str, rung: Rung, prompt: str, clone: str, home: pathlib.Path, bare: bool) -> tuple[list[str], str] | Failure: + """claude's arguments and prompt for reviewer on rung. Where bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer.""" + args = ["--agent", reviewer, *rung.flags()] + if not bare: + return args, prompt + context = reviewer_context(home) + if isinstance(context, Failure): + return context + return [*args, *NO_CLAUDE_MD], "\n".join([f"{context}\n\n{prompt}", *([principles] if (principles := principles_line(clone)) else [])]) + + +def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None: + """Copies into reports each report written to folder after found's chunk began and before its round did.""" + # The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find. + for written in folder.iterdir() if folder.is_dir() else (): + if written.is_file() and found.began <= written.stat().st_mtime < found.seconds: + shutil.copy2(written, reports) + + +def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure: + """prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder.""" + # Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's. + prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone) + # A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it. + if REPORTS in prompt.replace(copies.reports, ""): + return Failure("the prompt names the review folder in a spelling the replay does not redirect") + return prompt + + +def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None: + """Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began.""" + for command in ( + ("clone", "--quiet", "--shared", "--no-checkout", found.root, clone), + ("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base), + ("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base), + ("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed), + ): + if isinstance(ran := effects.git(*command, cwd=found.root), Failure): + return ran + return None + + +def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited: + numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1)) + prompt = ( + "A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. " + "List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. " + "A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n" + f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}" + ) + args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""] + reply = claude_reply(effects.claude, args, root, prompt, "claude") + if isinstance(reply, Failure | Limited): + return reply + output = structured_output(reply) + numbers = output.get("found") if isinstance(output, dict) else None + if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers): + return Failure(f"the match replied: {json.dumps(reply)}") + return {n - 1 for n in numbers if 1 <= n <= len(findings)} diff --git a/bin/review_replay/rounds.py b/bin/review_replay/rounds.py index 2d89d8b4..d2f5866b 100644 --- a/bin/review_replay/rounds.py +++ b/bin/review_replay/rounds.py @@ -1,12 +1,16 @@ -"""Which archived rounds of a review pass to replay, the code each reviewed, and the report with --omit-claude-md: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.""" +"""Which archived rounds of a review pass to replay, and the code each reviewed: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.""" import dataclasses import datetime +import json import pathlib import re import typing -from claude_code.entries import AssistantTurn, Entry, Text, UserText -from model_routing.ladder import Rung +from claude_code.entries import AssistantTurn, Entry, parse_entry, Text, UserText +from transcript_archive.project_key import checkout_of +from failure import Failure +from claude_code.transcript import first_timestamped_line, read_transcript +from rung_replay.command import projects_on # A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them. FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)") @@ -107,28 +111,31 @@ def sample(rounds: list[Round], latest: int) -> list[Round]: return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:] -def comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str: - """What the three replays with CLAUDE.md and the one without found in rounds. Each replay with it missed some findings the other two found: the control, the noise of an unchanged reviewer. The one without it is held to the findings the first two found, as the third is, and passes where it missed no more than the most a replay with it did. left_out counts the rounds a replay failed on, which rounds leaves out.""" - first, second, third = with_it +def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure: + projects = projects_on(model, home) + if isinstance(projects, Failure): + return projects + found = [] + try: + for key in projects: + for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()): + found += chunk_rounds(reviewer, checkout_of(key, home), chunk) + except (OSError, UnicodeDecodeError, ValueError) as failure: + return Failure(f"could not read the archive {root}: {failure}") + return found - def shared(one: list[set[int]], other: list[set[int]]) -> list[set[int]]: - return [found_by_one & found_by_other for found_by_one, found_by_other in zip(one, other)] - def missing(held: list[set[int]], run: list[set[int]]) -> list[tuple[Round, int]]: - return [(found_round, index) for found_round, held_in_round, found in zip(rounds, held, run) for index in sorted(held_in_round - found)] - - def count(run: list[set[int]]) -> int: - return sum(len(found) for found in run) - - both = shared(first, second) - missed = missing(both, without) - control = [len(missing(shared(one, other), run)) for run, one, other in ((first, second, third), (second, first, third), (third, first, second))] - passes = len(missed) <= max(control) - return "\n".join([ - f"Replayed {len(rounds)} {reviewed} rounds of {reference.model} projects, which hold {sum(len(found_round.findings) for found_round in rounds)} 🔴 and 🟡 findings, four times on {reference}: three with CLAUDE.md, one without.", - *([f"Left out {left_out} more, which a replay failed on; stderr says why."] if left_out else []), - f"With CLAUDE.md the three replays found {count(first)}, {count(second)} and {count(third)} of them, and missed {control[0]}, {control[1]} and {control[2]} of the findings that both of the other two found.", - *([f"Without CLAUDE.md it found {count(without)} of them, and missed {len(missed)} of the {count(both)} findings that both of the first two found{':' if missed else '.'}"] if count(both) else [f"Without CLAUDE.md it found {count(without)} of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to."]), - *(f" {found_round.root} {found_round.at}: {found_round.findings[index].splitlines()[0]}" for found_round, index in missed), - *([f"It {'passes' if passes else 'fails'}: {len(missed)} missed is {'no more' if passes else 'more'} than the most a replay with CLAUDE.md missed, {max(control)}."] if count(both) else []), - ]) +def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]: + copies = sorted(chunk.glob("*.jsonl")) + began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None + if not began or not began.timestamp: + return [] + found = [] + for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")): + described = json.loads(meta.read_text(encoding="utf-8")) + if not isinstance(described, dict) or described.get("agentType") != reviewer: + continue + entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl"))) + if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began.timestamp), entries)): + found.append(one) + return found diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 4c95f8cd..a7df700a 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -18,7 +18,7 @@ from review_replay.rounds import authored_by, lost_inputs, recorded_findings, re from loop_effects.effects import Effects, system_effects from claude_code.entries import entry_from from failure import Failure -from review_replay import main, recall +from review_replay import main, recall, replay from review_rules.reviewer_context import reviewer_context from review_rules.review_passes import REVIEWERS from model_routing.ladder import Rung @@ -124,17 +124,17 @@ class Launch(unittest.TestCase): self.clone.mkdir() def test_runs_the_reviewer_as_archived_with_claude_md(self): - self.assertEqual(main.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, False), (["--agent", "prose-reviewer", *REFERENCE.flags()], "Review it.")) + self.assertEqual(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, False), (["--agent", "prose-reviewer", *REFERENCE.flags()], "Review it.")) def test_drops_claude_md_and_hands_the_reviewer_what_the_hook_and_the_header_would(self): (self.clone / "AGENTS.md").write_text("") - args, prompt = main.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True) + args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True) self.assertEqual(args, ["--agent", "prose-reviewer", *REFERENCE.flags(), "--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})]) self.assertEqual(prompt, f"{reviewer_context(self.home)}\n\nReview it.\nPrinciples: read {self.clone}/AGENTS.md first, for the project principles and the decision titles.") def test_fails_without_the_sections_to_hand_over(self): (self.home / ".claude" / "CLAUDE.md").write_text("") - self.assertIsInstance(main.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True), Failure) + self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True), Failure) class Match(unittest.TestCase): @@ -145,14 +145,14 @@ class Match(unittest.TestCase): self.asked.append((args, cwd, prompt)) return subprocess.CompletedProcess(args, 0, stdout, "") - return main.match(("🔴 a", "🟡 b"), "the other report", "/code/p", REFERENCE, dataclasses.replace(system_effects(), claude=claude)) + return replay.match(("🔴 a", "🟡 b"), "the other report", "/code/p", REFERENCE, dataclasses.replace(system_effects(), claude=claude)) def test_asks_for_the_numbered_findings_the_other_report_raises_as_json_with_no_tools(self): self.run_match("{}") [(args, cwd, prompt)] = self.asked self.assertEqual(cwd, "/code/p") self.assertIn("1. 🔴 a\n\n2. 🟡 b\n\nThe other report:\nthe other report", prompt) - self.assertEqual(json.loads(args[args.index("--json-schema") + 1]), main.MATCH_SCHEMA) + self.assertEqual(json.loads(args[args.index("--json-schema") + 1]), replay.MATCH_SCHEMA) self.assertEqual(args[args.index("--tools") + 1], "") self.assertEqual(args[args.index("--model"):args.index("--model") + 4], REFERENCE.flags()) @@ -498,7 +498,7 @@ class Main(unittest.TestCase): def test_leaves_out_a_round_whose_checkout_names_no_default_branch(self): run_git(self.checkout, "remote", "set-head", "origin", "-d") - self.assert_left_out("git symbolic-ref --short refs/remotes/origin/HEAD: ") + self.assert_left_out("origin records no default branch") def test_leaves_out_a_round_whose_checkout_is_gone(self): shutil.rmtree(self.checkout) diff --git a/bin/review_rules/reviewer_context.py b/bin/review_rules/reviewer_context.py index 39d31ed3..46df0598 100644 --- a/bin/review_rules/reviewer_context.py +++ b/bin/review_rules/reviewer_context.py @@ -1,9 +1,11 @@ """What a reviewer under agents/ is handed in place of the instruction files: `omitClaudeMd` starts it without them, and most of `~/.claude/CLAUDE.md` is the worker's. docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed` says why, and which reviewers.""" import json import pathlib +import re from failure import Failure from review_rules.review_passes import REVIEWERS +from records.markdown_text import section # The sections of ~/.claude/CLAUDE.md a reviewer needs, in the file's order: the code-health goal the agents cite, the bar its own prose meets, and the words its reports use. SECTIONS = ("Shared goal", "Prose", "Vocabulary") @@ -16,15 +18,10 @@ def reviewer_context(home: pathlib.Path) -> str | Failure: text = path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {path}: {failure}") - found: dict[str, list[str]] = {} - lines: list[str] = [] - for line in text.splitlines(): - if line.startswith("## "): - lines = found.setdefault(line[3:].strip(), []) - lines.append(line) - if missing := [name for name in SECTIONS if name not in found]: + found = {name: section(text, re.escape(name)) for name in SECTIONS} + if missing := [name for name, lines in found.items() if lines is None]: return Failure(f"{path} holds no section {', '.join(missing)}") - return "\n\n".join(["You start without `~/.claude/CLAUDE.md`. These sections of it hold for you:", *("\n".join(found[name]).strip() for name in SECTIONS)]) + return "\n\n".join(["You start without `~/.claude/CLAUDE.md`. These sections of it hold for you:", *("\n".join([f"## {name}", *lines]).strip() for name, lines in found.items() if lines is not None)]) def starts_bare(agent: str, home: pathlib.Path) -> bool: diff --git a/bin/review_rules/test_reviewer_context.py b/bin/review_rules/test_reviewer_context.py index c6b8f8bf..318d3761 100644 --- a/bin/review_rules/test_reviewer_context.py +++ b/bin/review_rules/test_reviewer_context.py @@ -26,6 +26,10 @@ class ReviewerContext(unittest.TestCase): def test_holds_the_shared_goal_prose_and_vocabulary_sections_and_none_of_the_workers(self): self.assertEqual(reviewer_context(self.home), "You start without `~/.claude/CLAUDE.md`. These sections of it hold for you:\n\n## Shared goal\n\nCode health.\n\n## Prose\n\nWrite short.\n\n## Vocabulary\n\n- **chunk** — a unit.") + def test_a_heading_inside_a_code_fence_does_not_end_a_section(self): + (self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose\n\np\n\n## Vocabulary\n\nv\n") + self.assertIn("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose", reviewer_context(self.home)) + def test_fails_on_a_missing_section_or_file(self): (self.home / ".claude" / "CLAUDE.md").write_text("## Prose\n\nWrite short.\n") self.assertEqual(reviewer_context(self.home), Failure(f"{self.home / '.claude' / 'CLAUDE.md'} holds no section Shared goal, Vocabulary")) diff --git a/bin/routing_figures/dollars.py b/bin/routing_figures/dollars.py index f360efcd..ea1aa429 100644 --- a/bin/routing_figures/dollars.py +++ b/bin/routing_figures/dollars.py @@ -3,8 +3,8 @@ import collections import dataclasses import typing -from claude_code.entries import AssistantTurn, CostState, Entry, ToolCall -from routing_figures.prices import listed +from claude_code.entries import messages as claude_messages, CostState, Entry, ToolCall +from model_routing.prices import listed DIMENSIONS = ("project", "subagent type", "rung", "tool") # Each of DIMENSIONS to its labels' dollars. @@ -33,17 +33,12 @@ class Spent(typing.NamedTuple): def messages(entries: list[Entry]) -> list[Message]: """The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in.""" - # A message's usage is the same in each of its entries (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last. - kept: dict[str, tuple[AssistantTurn, list[str]]] = {} - for entry in entries: - if isinstance(entry, AssistantTurn): - found = kept.setdefault(entry.message_id or entry.uuid, (entry, [])) - found[1].extend(part.name for part in entry.parts if isinstance(part, ToolCall)) counted = [] before = [PROMPT] - for turn, called in kept.values(): + for turns in claude_messages(entries): + turn = turns[0] counted.append(Message(turn.timestamp, before, turn.model, listed(turn.model, turn.usage))) - before = called or [PROMPT] + before = [part.name for each in turns for part in each.parts if isinstance(part, ToolCall)] or [PROMPT] return counted diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index cef18a3b..41f8f3de 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -1,8 +1,10 @@ import re import typing +from model_routing.prices import PRICES from records.markdown_text import quoted from records.utc_stamp import STAMPED +from claude_code.tokens import Tokens from model_routing.route import WorkerLine TASK = "Task: " @@ -33,6 +35,9 @@ JUDGE_COST_AT = re.compile(rf"^{re.escape(JUDGE)}(.+)\n{re.escape(JUDGE_COST)}([ CONFIG = "Config: " # Opens the block of what the work since the previous outcome that recorded a spend spent; an outcome that spent nothing has none. SPENT = "Spent since " +KINDS = "input, cache write 5m, cache write 1h, cache read, output" +# Who spent, such as `worker`, `judge` or `Explore "Search the hooks"`, and the model they ran on. +Spender = tuple[str, str] # Opens the quote of a typed answer of the human's that reversed a choice the worker took on its own recommendation. REVERSED = "Reversed:" REVERSED_AT = re.compile(rf"^{re.escape(REVERSED)}\n((?:> .*\n)*> .*)", re.MULTILINE) @@ -41,7 +46,7 @@ REVERSED_AT = re.compile(rf"^{re.escape(REVERSED)}\n((?:> .*\n)*> .*)", re.MULTI class Annotation(typing.NamedTuple): """What a verdict, an interrupt or a quoted answer records beside its judge lines, so a change to the setup can be judged before and after: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`. Each part is left out where empty; the cycle always gives config.""" config: str = "" - # The block spend.spent_block renders. + # The block spent_block renders. spent: str = "" # The human's whole typed answer that holds the judge's quote of the reversal, as loop-claude checked it. reversed: str = "" @@ -54,6 +59,17 @@ def annotation_lines(annotation: Annotation) -> str: return f"{reversed_block}{spent_block}{config_line}" +# Nothing reads a Spent block yet: the first tool that derives dollars from one adds its parser here, beside this writer. +def spent_block(since: str, found: dict[Spender, Tokens]) -> str: + """The archive's block for what the stretch spent, then the list prices in force for each model in it; empty where nothing was spent.""" + if not found: + return "" + spenders = [f"- {name}, {model}: {', '.join(map(str, (tokens.input, tokens.write_5m, tokens.write_1h, tokens.read, tokens.output)))}" for (name, model), tokens in found.items()] + priced = [f"- {model}: {price.input:g}, {price.write_5m:g}, {price.write_1h:g}, {price.read:g}, {price.output:g}" for model in dict.fromkeys(model for _, model in found) if (price := PRICES.get(model))] + prices = ["", f"List prices in dollars per million tokens of {KINDS}:", *priced] if priced else [] + return "\n".join([f"{SPENT}{since or 'the chunk began'}, in tokens of {KINDS}:", *spenders, *prices]) + + def reversals(outcomes: str) -> list[str]: """Each reversing answer the outcomes quote, unquoted, in the order they were written.""" return [unquoted(found[1]) for found in REVERSED_AT.finditer(outcomes)] diff --git a/docs/decisions.md b/docs/decisions.md index 73600a8a..2e82f00b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -144,7 +144,7 @@ Valid while `~/.claude` is a checkout of this repo. 2026-11-12, lilleman, todo item 305. Serves goals 1, 1.2 and 1.4. A change to the setup can be judged only by comparing chunks run before it with chunks run after, so each verdict, interrupt and quoted answer in loop-claude's archive records three things beside its judge lines. - `Config: ()`: `git describe` and the commit of `~/.claude`, so outcomes group by the setup that produced them. Where git can't tell, it records `unknown` and why, on one line. -- A `Spent since` block: the raw tokens each thread spent, by model and by kind (input, cache write 5m, cache write 1h, cache read, output), then the list prices in force, from `bin/routing_figures/prices.py`. The threads are the worker's main thread, each subagent by its agent type and description, and the judge run that ruled. Each message counts once, by its id. The stretch runs from the previous outcome that recorded a spend, so what a `/talk` or a stopped run spent between rulings is counted once. It keeps tokens, since prices change. The prices recorded beside them give what the stretch cost when it ran. Claude Code doesn't report thinking apart from output, so it is left in output. The judge's tokens come from its json reply's `usage`, until item 303 archives the judge's own transcript. +- A `Spent since` block: the raw tokens each thread spent, by model and by kind (input, cache write 5m, cache write 1h, cache read, output), then the list prices in force, from `bin/model_routing/prices.py`. The threads are the worker's main thread, each subagent by its agent type and description, and the judge run that ruled. Each message counts once, by its id. The stretch runs from the previous outcome that recorded a spend, so what a `/talk` or a stopped run spent between rulings is counted once. It keeps tokens, since prices change. The prices recorded beside them give what the stretch cost when it ran. Claude Code doesn't report thinking apart from output, so it is left in output. The judge's tokens come from its json reply's `usage`, until item 303 archives the judge's own transcript. - A `Reversed:` quote: the human's typed answer that overrides a choice the worker took on its own recommendation and recorded. The judge quotes the latest such `[human]` line; loop-claude keeps the whole typed answer that holds the quote verbatim, and drops a quote no typed answer holds. `score-outcomes` counts the distinct answers per finished chunk. That count is goal 1.2's counter-signal, and the 2026-11-08 entry of `loop-claude: a judge decides each interrupt…` is valid only while it stays low. It counts only chunks that record a Config line, since earlier judges didn't look for reversals. Valid while score-outcomes reads the reversals from the archive. diff --git a/reviewer-merge-trials/analyze_metered.py b/reviewer-merge-trials/analyze_metered.py index cf6718df..9eadf409 100644 --- a/reviewer-merge-trials/analyze_metered.py +++ b/reviewer-merge-trials/analyze_metered.py @@ -1,7 +1,7 @@ """Run analyze.py's matching and new-finding count, and also sum what those calls cost. Usage: [BASELINE=] analyze_metered.py -... [case ids...]""" import pathlib, runpy, sys, threading sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -import analyze, review_replay.main as rm +import analyze, review_replay.replay as rm from claude_code.reply import claude_reply SPENT = [0.0]; LOCK = threading.Lock() def metered(*a, **k): diff --git a/reviewer-merge-trials/driver.py b/reviewer-merge-trials/driver.py index 9dfccb36..b6edc462 100644 --- a/reviewer-merge-trials/driver.py +++ b/reviewer-merge-trials/driver.py @@ -2,11 +2,11 @@ import concurrent.futures, json, os, pathlib, pickle, re, shutil, sys, tempfile sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin")) from claude_code.reply import claude_reply, Limited -from review_replay.main import clone_reviewed, Copies, copy_reports, match, redirected +from review_replay.replay import clone_reviewed, Copies, copy_reports, match, redirected from failure import Failure from review_replay.rounds import lost_inputs, Round from review_rules.review_folder import REPORTS, review_folder -from review_replay import main as rm +from review_replay import replay as rm from model_routing.ladder import Rung from loop_effects.effects import system_effects diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 33d6b73d..e75b0b57 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -47,6 +47,8 @@ A pass is one kind of review, a row of the table, named by its first column. Its | Product-owner | product-owner-reviewer | changes an external surface or contract: API routes and request/response shapes, events, webhooks, published file formats, CLI flags and exit codes, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | changes prose a reader reads, such as docs, comments, help or error text, or the plan's text for an item the chunk ships, splits or answers; one round | +The table's first two columns are also code: `PASS_AGENTS` in `bin/review_rules/review_passes.py`, which `bin/repo_checks/test_reviewer_launches.py` holds to the table. Change a row in both. + A comment is prose, not code, in any file, and so is a docstring. A change to config is one that changes what runs, so a comment in a workflow or compose file fires only the prose pass. Markdown an agent follows is config: `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md`, and files under `agents/`, `principles/`, `rules/` or `skills/`. **Plan rows.** A `todo.md` row or detail that the chunk files from a finding, re-scores or moves between releases gets no review: the chunk that ships the item reads it. -- 2.52.0 From 95fb0d03cfee3da5fdd9f244765163b7a41fc7b9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 20:10:55 +0100 Subject: [PATCH 3/7] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20score=5Fbul?= =?UTF-8?q?lets=20reads=20the=20shared=20dimension=20names,=20every=20ladd?= =?UTF-8?q?er=20model=20has=20a=20price?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/larv_review/main.py | 11 +++++------ bin/larv_review/scoring_setup.py | 19 +++++++++++-------- bin/larv_review/test_scoring_setup.py | 4 ++++ bin/model_routing/test_prices.py | 17 +++++++++++++++++ bin/review_replay/replay.py | 2 +- 5 files changed, 38 insertions(+), 15 deletions(-) create mode 100644 bin/model_routing/test_prices.py diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index b933c08e..3a136718 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -169,10 +169,11 @@ from larv_review.reviewer_header import reviewer_header class Command(typing.NamedTuple): - """One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them.""" + """One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them. Where it ends in item IDs, ids_from is the number of arguments before them, so main can name the ones that aren't.""" shape: str fits: typing.Callable[[list[str]], bool] run: typing.Callable[[list[str]], Failure | None] + ids_from: int | None = None def no_arguments(given: list[str]) -> bool: @@ -188,18 +189,16 @@ COMMANDS = { "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)), "round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)), - "needs-scoring-run": Command("needs-scoring-run [...]", are_ids, lambda given: with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)), + "needs-scoring-run": Command("needs-scoring-run [...]", are_ids, lambda given: with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False), ids_from=0), "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(owed, stale_ok=False)), "record-ruling": Command("record-ruling ", lambda given: len(given) == 1, lambda given: record_ruling(pathlib.Path(given[0]))), "prepare-scoring": Command("prepare-scoring [--preloaded ]", lambda given: not given or len(given) == 2 and given[0] == "--preloaded", lambda given: prepared_scoring(given[1] if given else None)), - "record-scoring": Command("record-scoring [...]", lambda given: bool(given) and are_ids(given[1:]), lambda given: with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)), + "record-scoring": Command("record-scoring [...]", lambda given: bool(given) and are_ids(given[1:]), lambda given: with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False), ids_from=1), "places": Command("places", no_arguments, lambda given: show_places()), "agreement": Command("agreement", no_arguments, lambda given: show_agreement()), "reviewer-header": Command("reviewer-header [--rerun]", lambda given: given[:1] != [] and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]), lambda given: with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True)), "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), } -# The commands that take item IDs, each with the number of arguments before the IDs. -ID_COMMANDS = {"needs-scoring-run": 0, "record-scoring": 1} SHAPES = " | ".join(command.shape for command in COMMANDS.values()) USAGE = f"usage: larv-review {SHAPES}" @@ -215,7 +214,7 @@ def main(argv: list[str]) -> int: command = COMMANDS.get(name) if command and command.fits(given): done = command.run(given) - elif command and name in ID_COMMANDS and (named := [id_ for id_ in given[ID_COMMANDS[name]:] if not re.fullmatch(r"[0-9]+", id_)]): + elif command and command.ids_from is not None and (named := [id_ for id_ in given[command.ids_from:] if not re.fullmatch(r"[0-9]+", id_)]): print(f"{name} takes item IDs, the numbers in todo.md's ID column, not {' '.join(named)}; {USAGE}", file=sys.stderr) return 1 else: diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py index 130cddca..32d7af49 100644 --- a/bin/larv_review/scoring_setup.py +++ b/bin/larv_review/scoring_setup.py @@ -4,6 +4,7 @@ import pathlib import re import shutil +from review_rules.comprehension_history import DIMENSIONS from failure import Failure from records.markdown_text import FENCE, listed, section from git_cli.git_repo import git @@ -18,6 +19,8 @@ SEATS = ( ("maintainability-senior", "Senior, maintainability", "Report: Junior A, Mid A and the maintainability senior"), ("inherited-architect", "Architect, inherited", "Report: the inherited architect"), ) +# The dimensions a seat scores beside the overall, which comes last in DIMENSIONS. +PANEL_DIMENSIONS = DIMENSIONS[:-1] VALUE_NAMES = ("language", "kind", "domain", "domain docs", "3am question") FORBIDDEN_FILES = ("todo.md", "docs/decisions.md", "docs/comprehension-history.md", "docs/reading-cost.md") FORBIDDEN = "todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' records and past chunks' reading cost)" @@ -43,17 +46,17 @@ def bullets(lines: list[str]) -> list[list[str]]: ANCHOR = re.compile(r"- \*\*\d+ — ") -DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency") +DIMENSION = re.compile(r"- \*\*([^*]+)\*\* — ") def score_bullets(skill: str) -> tuple[list[str], list[str]] | Failure: - """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is one by how it opens, `- ** — ` or `- ****`, so other bullets and their order in the section change nothing.""" - lines = [line.replace("**", "") for group in bullets(section(skill, "The score") or []) for line in group if ANCHOR.match(line) or line.startswith(tuple(f"- **{name}**" for name in DIMENSIONS))] - anchors = [line for line in lines if line[2].isdigit()] - dimensions = [line for line in lines if not line[2].isdigit()] - if len(anchors) != 6 or [line.split(" — ")[0] for line in dimensions] != [f"- {name}" for name in DIMENSIONS]: - return Failure(f"{PANEL / 'SKILL.md'} → \"The score\" no longer holds six bullets opening `- ** — ` and four opening `- ****` for Navigation, Locality, Shape and Self-sufficiency, in that order") - return anchors, dimensions + """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is one by how it opens, `- ** — ` or `- **** — `, so other bullets and their order in the section change nothing.""" + lines = [line for group in bullets(section(skill, "The score") or []) for line in group] + anchors = [line.replace("**", "") for line in lines if ANCHOR.match(line)] + dimensions = [(match[1], line) for line in lines if (match := DIMENSION.match(line))] + if len(anchors) != 6 or tuple(name for name, _ in dimensions) != PANEL_DIMENSIONS: + return Failure(f"{PANEL / 'SKILL.md'} → \"The score\" no longer holds six bullets opening `- ** — ` and one opening `- **** — ` for each of {listed(list(PANEL_DIMENSIONS), 'and')}, in that order") + return anchors, [line.replace("**", "") for _, line in dimensions] def project_values(text: str, source: str) -> dict[str, str] | Failure: diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index eaace866..313c52ad 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -38,6 +38,10 @@ class ScoreBullets(unittest.TestCase): with self.subTest(dropped=dropped): self.assertIsInstance(score_bullets(skill.replace(dropped, "- Dropped:", 1)), Failure) + def test_fails_where_a_fifth_dimension_is_added(self): + skill = SKILL.read_text() + self.assertIsInstance(score_bullets(skill.replace("- **Shape** —", "- **Extra** — a new one.\n- **Shape** —", 1)), Failure) + class ProjectValues(unittest.TestCase): def test_reads_each_spelling_the_projects_use(self): diff --git a/bin/model_routing/test_prices.py b/bin/model_routing/test_prices.py new file mode 100644 index 00000000..5999e34b --- /dev/null +++ b/bin/model_routing/test_prices.py @@ -0,0 +1,17 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from model_routing.ladder import LADDER +from model_routing.prices import PRICES + + +class Prices(unittest.TestCase): + def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_costs_nothing_in_a_figure(self): + self.assertEqual(sorted({rung.model for rung in LADDER} - set(PRICES)), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/review_replay/replay.py b/bin/review_replay/replay.py index 5fc68bc6..3e1707ae 100644 --- a/bin/review_replay/replay.py +++ b/bin/review_replay/replay.py @@ -88,7 +88,7 @@ class Copies: reports: str -# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument. +# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is. def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited: try: (home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True) -- 2.52.0 From 7e29dc0014cd26d06eb2c77984b1cc83e348e5a5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 20:18:54 +0100 Subject: [PATCH 4/7] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20drop=20typi?= =?UTF-8?q?ng.cast=20and=20subTest=20loops=20from=20new=20code,=20state=20?= =?UTF-8?q?the=20price=20list's=20two=20uses,=20record=20the=20subTest=20d?= =?UTF-8?q?ecision?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/larv_review/main.py | 35 ++++++++++++++++++++++----- bin/larv_review/test_larv_review.py | 19 +++++++++------ bin/larv_review/test_scoring_setup.py | 10 ++++---- bin/loop_claude/cycle/spend.py | 2 +- bin/loop_claude/loop/main.py | 1 - bin/model_routing/prices.py | 4 +-- bin/reading_cost/measure.py | 2 -- bin/repo_checks/__init__.py | 2 ++ bin/review_replay/omit_comparison.py | 16 +++++++++--- bin/transcript_archive/outcomes.py | 2 +- docs/decisions.md | 5 ++++ 12 files changed, 71 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index dbf87d0e..a604923d 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`. -- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. +- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `transcript_archive` and `routing_figures` read. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new. - `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`. diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 3a136718..a45535cb 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -176,12 +176,35 @@ class Command(typing.NamedTuple): ids_from: int | None = None +ITEM_ID = re.compile(r"[0-9]+") + + def no_arguments(given: list[str]) -> bool: return not given def are_ids(given: list[str]) -> bool: - return all(re.fullmatch(r"[0-9]+", id_) for id_ in given) + return all(ITEM_ID.fullmatch(id_) for id_ in given) + + +def run_needs_scoring_run(given: list[str]) -> Failure | None: + return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False) + + +def fits_prepare_scoring(given: list[str]) -> bool: + return not given or len(given) == 2 and given[0] == "--preloaded" + + +def run_record_scoring(given: list[str]) -> Failure | None: + return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False) + + +def fits_reviewer_header(given: list[str]) -> bool: + return bool(given) and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]) + + +def run_reviewer_header(given: list[str]) -> Failure | None: + return with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True) # One row per subcommand, in the order the usage line and the docstring above list them: main, USAGE and `--help` all read this table. @@ -189,14 +212,14 @@ COMMANDS = { "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)), "round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)), - "needs-scoring-run": Command("needs-scoring-run [...]", are_ids, lambda given: with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False), ids_from=0), + "needs-scoring-run": Command("needs-scoring-run [...]", are_ids, run_needs_scoring_run, ids_from=0), "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(owed, stale_ok=False)), "record-ruling": Command("record-ruling ", lambda given: len(given) == 1, lambda given: record_ruling(pathlib.Path(given[0]))), - "prepare-scoring": Command("prepare-scoring [--preloaded ]", lambda given: not given or len(given) == 2 and given[0] == "--preloaded", lambda given: prepared_scoring(given[1] if given else None)), - "record-scoring": Command("record-scoring [...]", lambda given: bool(given) and are_ids(given[1:]), lambda given: with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False), ids_from=1), + "prepare-scoring": Command("prepare-scoring [--preloaded ]", fits_prepare_scoring, lambda given: prepared_scoring(given[1] if given else None)), + "record-scoring": Command("record-scoring [...]", lambda given: bool(given) and are_ids(given[1:]), run_record_scoring, ids_from=1), "places": Command("places", no_arguments, lambda given: show_places()), "agreement": Command("agreement", no_arguments, lambda given: show_agreement()), - "reviewer-header": Command("reviewer-header [--rerun]", lambda given: given[:1] != [] and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]), lambda given: with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True)), + "reviewer-header": Command("reviewer-header [--rerun]", fits_reviewer_header, run_reviewer_header), "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), } SHAPES = " | ".join(command.shape for command in COMMANDS.values()) @@ -214,7 +237,7 @@ def main(argv: list[str]) -> int: command = COMMANDS.get(name) if command and command.fits(given): done = command.run(given) - elif command and command.ids_from is not None and (named := [id_ for id_ in given[command.ids_from:] if not re.fullmatch(r"[0-9]+", id_)]): + elif command and command.ids_from is not None and (named := [id_ for id_ in given[command.ids_from:] if not ITEM_ID.fullmatch(id_)]): print(f"{name} takes item IDs, the numbers in todo.md's ID column, not {' '.join(named)}; {USAGE}", file=sys.stderr) return 1 else: diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 2e150352..663c4043 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -872,15 +872,20 @@ class LarvReviewTool(unittest.TestCase): def test_review_folder_takes_no_arguments(self): self.assertIn("unknown arguments", self.run_tool("review-folder", "x").stderr) - def test_names_the_arguments_that_are_not_item_ids(self): - for args, named in ((("needs-scoring-run", "3", "x"), "x"), (("record-scoring", "scores.md", "4", "y1"), "y1")): - with self.subTest(args=args): - ran = self.run_tool(*args) - self.assertEqual(ran.returncode, 1) - self.assertIn(f"takes item IDs, the numbers in todo.md's ID column, not {named};", ran.stderr) + def assert_names_the_non_id(self, named, *args): + ran = self.run_tool(*args) + self.assertEqual(ran.returncode, 1) + self.assertIn(f"takes item IDs, the numbers in todo.md's ID column, not {named};", ran.stderr) + + def test_needs_scoring_run_names_the_argument_that_is_not_an_item_id(self): + self.assert_names_the_non_id("x", "needs-scoring-run", "3", "x") + + def test_record_scoring_names_the_argument_after_its_file_that_is_not_an_item_id(self): + self.assert_names_the_non_id("y1", "record-scoring", "scores.md", "4", "y1") def test_help_and_the_usage_line_list_the_same_commands(self): - listed = self.run_tool("--help").stdout.splitlines()[2].removeprefix("usage: larv-review ").split(" | ") + usage = next(line for line in self.run_tool("--help").stdout.splitlines() if line.startswith("usage: larv-review ")) + listed = usage.removeprefix("usage: larv-review ").split(" | ") self.assertEqual([shape.split()[0] for shape in listed], ["review-folder", "ruling-base", "round-count", "needs-scoring-run", "scoring-run-owed", "record-ruling", "prepare-scoring", "record-scoring", "places", "agreement", "reviewer-header", "reviewer-context"]) self.assertIn(f"usage: larv-review {' | '.join(listed)}", self.run_tool().stderr) diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 313c52ad..1e4f9fef 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -32,11 +32,11 @@ class ScoreBullets(unittest.TestCase): with_extra = skill.replace("## The score\n\n", "## The score\n\n- A bullet before the anchors.\n\n", 1) self.assertEqual(score_bullets(with_extra), score_bullets(skill)) - def test_fails_where_an_anchor_or_a_dimension_is_missing(self): - skill = SKILL.read_text() - for dropped in ("- **10 — Duress-proof.**", "- **Shape** —"): - with self.subTest(dropped=dropped): - self.assertIsInstance(score_bullets(skill.replace(dropped, "- Dropped:", 1)), Failure) + def test_fails_where_an_anchor_is_missing(self): + self.assertIsInstance(score_bullets(SKILL.read_text().replace("- **10 — Duress-proof.**", "- Dropped:", 1)), Failure) + + def test_fails_where_a_dimension_is_missing(self): + self.assertIsInstance(score_bullets(SKILL.read_text().replace("- **Shape** —", "- Dropped:", 1)), Failure) def test_fails_where_a_fifth_dimension_is_added(self): skill = SKILL.read_text() diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 68c125bf..23941832 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -46,7 +46,7 @@ def moment(stamp: str) -> datetime.datetime: return datetime.datetime.fromisoformat(stamp) -# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. In practice none is, since the judge runs for seconds after the worker's last message. +# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. The worker writes none then, since the judge runs for seconds after its last message; a subagent or a /talk session still running may, which overcounts that message once. def later(timestamp: str, start: datetime.datetime) -> bool: """Whether timestamp is after start; False where it is no time, or names no time zone to compare by.""" try: diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index ce60da0d..04018d71 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -26,7 +26,6 @@ from loop_claude.stop import Stop from loop_claude.direct_message import tell - def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: try: stop = run_loop(argv, env, paths, launcher, cwd, effects) diff --git a/bin/model_routing/prices.py b/bin/model_routing/prices.py index 3110a831..e3526621 100644 --- a/bin/model_routing/prices.py +++ b/bin/model_routing/prices.py @@ -1,4 +1,4 @@ -"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages.""" +"""What a message costs at list prices. The weights that split a chunk's recorded cost between its messages, and the prices a Spent block records beside what a stretch spent, so a price wrong here stays wrong in every outcome written after it.""" import dataclasses from claude_code.tokens import tokens_of @@ -20,7 +20,7 @@ class Price: return self.input * 2 -# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off. +# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Keep each price current with that list: the prices are archived as the ones in force. PRICES = { # Archived chunks that ran on Fable 5.1 are still priced from here. "claude-fable-5-1": Price(10, 0.25, 50), diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 346b2cee..47f4a810 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -8,8 +8,6 @@ from reading_cost.shell_reads import Reads, shell_reads from command_lines.shell_command import resolved, simple_commands - - @dataclasses.dataclass(frozen=True) class Reading: """What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout.""" diff --git a/bin/repo_checks/__init__.py b/bin/repo_checks/__init__.py index 021d23d6..5a1d5fec 100644 --- a/bin/repo_checks/__init__.py +++ b/bin/repo_checks/__init__.py @@ -1,4 +1,6 @@ import pathlib +# Each module here checks a convention of the repo's files, as a linter does: import order, citations, CI, settings. So it reads source or Markdown, which technical-principles.md bans in a test of a unit's behaviour. + # The checkout root. ROOT = pathlib.Path(__file__).resolve().parents[2] diff --git a/bin/review_replay/omit_comparison.py b/bin/review_replay/omit_comparison.py index 5bd4ac78..05911adf 100644 --- a/bin/review_replay/omit_comparison.py +++ b/bin/review_replay/omit_comparison.py @@ -24,9 +24,19 @@ def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing return found runs.append(found) # A failed replay found nothing, which would lower the bar where it had CLAUDE.md and count as misses where it had none. - kept = [(one, *found) for one, *found in zip(chosen, *runs) if not any(isinstance(each, Failure) for each in found)] - first, second, third, without = ([typing.cast(set[int], found[run]) for _, *found in kept] for run in range(4)) - return comparison(reviewed, project, [one for one, *_ in kept], (first, second, third), without, len(chosen) - len(kept)) + kept = rounds_without_failure(chosen, runs) + first, second, third, without = ([found[run] for _, found in kept] for run in range(4)) + return comparison(reviewed, project, [one for one, _ in kept], (first, second, third), without, len(chosen) - len(kept)) + + +def rounds_without_failure(chosen: list[Round], runs: list[list[set[int] | Failure]]) -> list[tuple[Round, list[set[int]]]]: + """Each round of chosen that no run failed on, with what each run found in it.""" + kept = [] + for one, *found in zip(chosen, *runs): + finds = [each for each in found if not isinstance(each, Failure)] + if len(finds) == len(found): + kept.append((one, finds)) + return kept def comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str: diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index 41f8f3de..bf633cc0 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -61,7 +61,7 @@ def annotation_lines(annotation: Annotation) -> str: # Nothing reads a Spent block yet: the first tool that derives dollars from one adds its parser here, beside this writer. def spent_block(since: str, found: dict[Spender, Tokens]) -> str: - """The archive's block for what the stretch spent, then the list prices in force for each model in it; empty where nothing was spent.""" + """The archive's block for what the stretch spent, then the list prices in force for each model in it that has one; empty where nothing was spent.""" if not found: return "" spenders = [f"- {name}, {model}: {', '.join(map(str, (tokens.input, tokens.write_5m, tokens.write_1h, tokens.read, tokens.output)))}" for (name, model), tokens in found.items()] diff --git a/docs/decisions.md b/docs/decisions.md index 2e82f00b..c523e55a 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -12,6 +12,7 @@ Each project principle states one rule that the decisions below apply; their ent # Decisions no project principle covers +- bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase` - bin/: the tools run on the host's Python, with no container, and so do their tests outside CI - bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers - deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md` @@ -49,6 +50,10 @@ Settling a call is the human's. The chunk that settles the calls cites, in `docs # Decisions +## bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase` + +2026-11-12, lilleman, from the release review of 0.9.0. Applies `principles/technical-principles.md` → "Most code should have automated tests", whose "parametrize the cases" asks for one reported result per case. The tests are plain unittest, run by pytest, and pytest's `parametrize` doesn't work on a `TestCase` method; `subTest` is the unittest mechanism that does: each case reports and fails on its own, with its parameters named. A test body that loops over its cases for another reason, or holds a branch, is still a breach. Valid while the tests stay in plain unittest. + ## bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names 2026-10-23, larv-review, through PR #367. Serves code health: a reader can trust that one word names one thing in every tool. Before, "record" and "outcome" each named different things in three modules, and "place" in two. Each word kept the meaning it already had where renaming costs most: -- 2.52.0 From 14e6756a53bb61cd9cc85dfe60ae48fa9b62f39c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 12 Nov 2026 20:33:32 +0100 Subject: [PATCH 5/7] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(0=20misread);=20rewrite=20e?= =?UTF-8?q?ach=20=20nothing=20to=20the=20negation=20rule,=20tighten?= =?UTF-8?q?=20the=20new=20docstrings=20and=20comments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++--- bin/chunk_pr/main.py | 8 +++--- bin/chunk_preflight/facts.py | 2 +- bin/chunk_preflight/test_chunk_preflight.py | 2 +- bin/claude_code/entries.py | 4 +-- bin/command_lines/shell_command.py | 2 +- bin/deploy_release/deploy.py | 2 +- bin/deploy_release/main.py | 2 +- bin/git_cli/test_git_repo.py | 2 +- bin/larv_review/main.py | 8 +++--- bin/larv_review/owed.py | 2 +- bin/larv_review/scoring_setup.py | 2 +- bin/larv_review/test_larv_review.py | 4 +-- bin/larv_review/unmeasured.py | 2 +- bin/loop_claude/cycle/interrupt.py | 6 ++--- bin/loop_claude/cycle/judge.py | 2 +- bin/loop_claude/cycle/spend.py | 2 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/loop/usage.py | 4 +-- bin/loop_claude/project/premises.py | 2 +- bin/loop_claude/test_black_box.py | 4 +-- bin/loop_claude/test_loop_claude.py | 12 ++++----- bin/loop_inbox/main.py | 2 +- bin/loop_state/__init__.py | 2 +- bin/model_routing/prices.py | 2 +- bin/model_routing/test_prices.py | 2 +- bin/rank_todo.py | 4 +-- bin/release_plan/formula.py | 2 +- bin/release_plan/todo_table.py | 2 +- bin/repo_checks/__init__.py | 2 +- bin/review_replay/main.py | 4 +-- bin/review_replay/omit_comparison.py | 2 +- bin/review_replay/recall.py | 4 +-- bin/review_rules/comprehension_history.py | 2 +- bin/review_rules/reviewer_context.py | 2 +- bin/routing_figures/archive.py | 2 +- bin/rule_hook/main.py | 2 +- bin/rule_hook/rules.py | 2 +- bin/rule_hook/test_rule_hook.py | 6 ++--- bin/rule_hook/todo_check.py | 2 +- bin/run_heavy/main.py | 2 +- bin/rung_replay/search.py | 2 +- bin/score_outcomes/main.py | 2 +- bin/score_outcomes/results.py | 2 +- bin/score_outcomes/test_score_outcomes.py | 2 +- bin/subagent_rung/main.py | 2 +- bin/todo_item/main.py | 8 +++--- bin/transcript_archive/outcomes.py | 2 +- bin/wait_for/main.py | 2 +- bin/wait_for/test_wait_for.py | 2 +- docs/decisions.md | 28 ++++++++++----------- docs/scoring-and-goals-research.md | 2 +- presentation/README.md | 2 +- principles/technical-principles.md | 4 +-- reviewer-merge-trials/README.md | 2 +- skills/comprehension-panel/SKILL.md | 4 +-- skills/comprehension-panel/seat-prompts.md | 2 +- skills/larv-review/standards/comments.md | 2 +- todo.md | 2 +- workflow-bench/compare-prompt.md | 2 +- workflow-bench/run-prompt.md | 4 +-- 61 files changed, 104 insertions(+), 104 deletions(-) diff --git a/README.md b/README.md index a604923d..88d4a717 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `mutate-changes [--base ] [--prefix ] [--jobs ]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. - `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure. -- `review-replay ` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. The rungs tried start with the project's model at a lower effort. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host. +- `review-replay ` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host. - `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override. - `run-heavy ` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit. - `run-tests [...]` runs this repo's test suite, as Test says. @@ -134,7 +134,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`. -- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `transcript_archive` and `routing_figures` read. +- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new. - `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`. @@ -149,7 +149,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t Test on the host with `bin/run-tests`, which runs pytest through `uvx`, pinned in `bin/run_tests/main.py`. It prints each failing test with its error and pytest's summary line, and saves the whole output to a file whose path it prints. It passes on any test paths or pytest options it is given, such as `bin/run-tests bin/chunk_pr -x`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in one worker per CPU of a heavy slot (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's scripts with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`. -CI runs `ci.sh` on every pull request, and `main` merges nothing until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`. +CI runs `ci.sh` on every pull request, and `main` doesn't merge anything until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`. To mutation-test the lines a branch changes, run `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"'` in its checkout. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 362db64e..b6ed4408 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -12,7 +12,7 @@ pull request only while its head is the commit checked out, so push before you r open pushes the branch, setting its upstream, and opens a draft pull request into origin's default branch. is one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs" says, and <body> is the pull request's summary. Where the branch's pull request is open - already, it opens no second one. On origin's default branch it refuses, pushing nothing. + already, it opens no second one. On origin's default branch it refuses without pushing anything. sync fetches origin and merges its default branch into the branch checked out, where the branch does not hold it already, and prints which it did. Then, where the worktree's root holds a todo.md, it runs `rank_todo.py --check` on it and prints the result, failing where @@ -35,7 +35,7 @@ clean acts once the forge reports the branch's pull request merged at the com by any merge method. It fetches origin, fast-forwards the main checkout to origin's default branch, removes the chunk's worktree, then deletes the local branch; origin's branch stays. Where the worktree has uncommitted or untracked files, it refuses and - touches nothing. Where the main checkout has uncommitted or untracked files, another + doesn't touch anything. Where the main checkout has uncommitted or untracked files, another branch checked out, or commits origin's default branch lacks, it leaves that as it was, still removes the worktree and the branch, and fails saying why. @@ -79,7 +79,7 @@ def main(argv: list[str]) -> int: def step(argv: list[str], run: Run) -> str | Failure: - """Run the step argv names: the line to print, or a Failure. A malformed argv runs nothing.""" + """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything.""" match argv: case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"): return Failure("give a title of one line") if not one_line(title) else opened(title, body[0] if body else "", run) @@ -115,7 +115,7 @@ def checkout(run: Run) -> tuple[Forge, str, str] | Failure: def default_branch(run: Run) -> str | Failure: - """origin's default branch, such as main. Not git_cli's default_ref: that falls back to a local main or master and asks origin where nothing is recorded, but a pull request's base is origin's alone, and this tells the user how to record it.""" + """origin's default branch, such as main. It differs from git_cli's default_ref, which falls back to a local main or master and asks origin where nothing is recorded. A pull request's base is origin's alone, so this fails instead, and says how to record it.""" default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) if isinstance(default, Failure): return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}") diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 4c1f5019..604890a7 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -117,7 +117,7 @@ def printed(shown: str, done: Ran | Failure) -> str: if isinstance(done, Failure): return f"`{shown}` {done.reason}" output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip()) - return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing nothing." + return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing no output." def levels(item: Item) -> str: diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index c077f1bf..98c36d34 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -443,7 +443,7 @@ class Render(unittest.TestCase): said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))])) self.assertIn("`rank_todo.py --check todo.md` exited 0", said) self.assertIn("> ranked", said) - self.assertIn("`reading-cost` exited 1, printing nothing", said) + self.assertIn("`reading-cost` exited 1, printing no output", said) self.assertIn("> out\n> err", said) self.assertIn("`larv-review places` could not finish: timed out", said) diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 900ddb48..e87a9450 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -231,7 +231,7 @@ def tool_result(part: object) -> ToolResult | None: def result_text(content: object) -> str: if isinstance(content, str): return content - # Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them. + # Claude Code may split one text across blocks, even inside a line, so the blocks join without anything between them. return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else "" @@ -265,7 +265,7 @@ def rejected_until(event: dict) -> int | None: return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None -# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of a figure standing. +# A count Claude Code left out or wrote as another type doesn't add anything, so one odd entry leaves the rest of a figure standing. def usage_count(usage: dict, field: str) -> int: """One token count of a message's usage: {"input_tokens": 2, "cache_creation_input_tokens": 14541, "output_tokens": 8, ...}""" value = usage.get(field) diff --git a/bin/command_lines/shell_command.py b/bin/command_lines/shell_command.py index 21314041..dff5d807 100644 --- a/bin/command_lines/shell_command.py +++ b/bin/command_lines/shell_command.py @@ -52,7 +52,7 @@ def segments(command: str) -> list[list[str]]: - a file descriptor before a redirect, as in `2>&1`, stays a word; - a heredoc's body is dropped; - variables, aliases and functions are not expanded; - - a line with an unbalanced quote yields nothing.""" + - a line with an unbalanced quote doesn't yield anything.""" text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command)) tokens = lexed(text) if tokens is None: diff --git a/bin/deploy_release/deploy.py b/bin/deploy_release/deploy.py index e1d96342..77610c1f 100644 --- a/bin/deploy_release/deploy.py +++ b/bin/deploy_release/deploy.py @@ -34,7 +34,7 @@ def deploy(checkout: str) -> str | Failure: if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure): return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first") settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure) - # The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy. + # The tag holds each uncommitted change, so undoing them doesn't lose anything, and lets the checkout below take the tag's copy. # A settings.json the clean filter shows unchanged may still differ on disk, by a model pick or Claude Code's key order, which checkout refuses to overwrite; the pick is asked for again below. tracked = git("ls-files", "--", "settings.json", cwd=checkout) if isinstance(tracked, Failure): diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index cd85a141..2742fc9f 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -17,7 +17,7 @@ the move would drop work no release holds. Untracked files, such as Claude Code' memory, stay as they are. --cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and -refuses, changing nothing, unless that release holds no item in todo.md, its release review has +refuses without changing anything, unless that release holds no item in todo.md, its release review has landed and changes are unreleased. The release names the version; the tool doesn't choose one. 1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own diff --git a/bin/git_cli/test_git_repo.py b/bin/git_cli/test_git_repo.py index 7921e0a0..5ad51a55 100644 --- a/bin/git_cli/test_git_repo.py +++ b/bin/git_cli/test_git_repo.py @@ -76,7 +76,7 @@ class Guarded(unittest.TestCase): class StalledOrigin(unittest.TestCase): - """A checkout whose origin, run through git's ext transport, answers nothing for 10 s, and which records no default branch for it.""" + """A checkout whose origin, run through git's ext transport, doesn't answer for 10 s, and which records no default branch for it.""" def setUp(self): temp = tempfile.TemporaryDirectory() diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index a45535cb..f718c06e 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -43,7 +43,7 @@ docs/decisions.md opts out of the comprehension check is never due one. scoring-run-owed prints `No scoring run owed.` or exits 1 naming the runs the chunk owes and has not recorded. chunk-pr merge runs it and refuses to merge on exit 1, so a due line read earlier in the chunk can't stand in for it. It applies needs-scoring-run's rule to the checkout's todo.md and the committed history, against the -merge base with the default branch, so a default branch that has moved on adds nothing: the items +merge base with the default branch, so a default branch that has moved on doesn't add anything: the items the merge base's todo.md holds and the checkout's does not count as shipped. A chunk that empties a release owes two runs, any other due chunk one. The chunk has recorded the scoring runs that its committed docs/comprehension-history.md holds beyond the merge base's. A project that opts out or @@ -78,7 +78,7 @@ better, same or worse. Each place opens with the names from the seat's line that `, ` and followed by `: `. A dimension's vote counts as same unless one of the seat's places opens with that dimension and holds a `path:line` in backticks; the overall vote counts as same unless any place holds one. The printed votes say so. When the two counted overall votes differ, it appends -nothing and prints `Split:`, saying to add the maintainability senior's and Junior A's lines. +no line and prints `Split:`, saying to add the maintainability senior's and Junior A's lines. Otherwise the ruling is the overall vote that leads each other vote by two or more, else same. It prints `Ruling:` and appends the ruling. @@ -169,7 +169,7 @@ from larv_review.reviewer_header import reviewer_header class Command(typing.NamedTuple): - """One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them. Where it ends in item IDs, ids_from is the number of arguments before them, so main can name the ones that aren't.""" + """One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them. Where it ends in item IDs, ids_from is the number of arguments before them, so main can name the arguments that aren't IDs.""" shape: str fits: typing.Callable[[list[str]], bool] run: typing.Callable[[list[str]], Failure | None] @@ -207,7 +207,7 @@ def run_reviewer_header(given: list[str]) -> Failure | None: return with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True) -# One row per subcommand, in the order the usage line and the docstring above list them: main, USAGE and `--help` all read this table. +# One row per subcommand: main, USAGE and `--help` all read this table. COMMANDS = { "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)), diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index 85d562f6..acc1455c 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -10,7 +10,7 @@ from release_plan.todo_table import items, NoItemsTable def owed_scoring_run(default: str) -> Failure | None: """A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none. - The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began counts for nothing. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking. + The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking. """ checkout = top() if isinstance(checkout, Failure): diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py index 32d7af49..11335911 100644 --- a/bin/larv_review/scoring_setup.py +++ b/bin/larv_review/scoring_setup.py @@ -50,7 +50,7 @@ DIMENSION = re.compile(r"- \*\*([^*]+)\*\* — ") def score_bullets(skill: str) -> tuple[list[str], list[str]] | Failure: - """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is one by how it opens, `- **<n> — ` or `- **<name>** — `, so other bullets and their order in the section change nothing.""" + """The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is an anchor or a dimension by how it opens, `- **<n> — ` or `- **<name>** — `; the other bullets in the section are skipped, and the dimensions must come in the panel's order.""" lines = [line for group in bullets(section(skill, "The score") or []) for line in group] anchors = [line.replace("**", "") for line in lines if ANCHOR.match(line)] dimensions = [(match[1], line) for line in lines if (match := DIMENSION.match(line))] diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 663c4043..09d7ec06 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -621,9 +621,9 @@ class LarvReviewTool(unittest.TestCase): history = "# Comprehension history\n\n" due = "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n" self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": history + paired("2026-10-21T12:00:00Z", "better") + "\n" + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-09T12:00:00Z")}) - self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, end nothing") + self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, don't end anything") self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": history + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-30")}) - self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse ends nothing") + self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse doesn't end anything") def test_an_unmeasured_release_is_judged_by_the_default_branch_alone_and_names_a_release_over_its_candidate(self): self.release("v0.0.1", "2026-10-09T12:00:00Z") diff --git a/bin/larv_review/unmeasured.py b/bin/larv_review/unmeasured.py index f20d32c0..f61b1bbd 100644 --- a/bin/larv_review/unmeasured.py +++ b/bin/larv_review/unmeasured.py @@ -10,7 +10,7 @@ def unmeasured_cut(default: str, checkout: str) -> str | None | Failure: The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run. - A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse counts for nothing, so the run is asked for again. + A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse doesn't count, so the run is asked for again. """ # Sorts v1.0.0-rc.1 below v1.0.0, as release.newest_tag does. tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname", cwd=checkout) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 0b710a40..1f14d89c 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -41,7 +41,7 @@ class Talked: def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop: - """Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" + """Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends.""" say(f"\n{question}", effects) on_terminal = effects.on_terminal() if on_terminal: @@ -60,7 +60,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, question def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop: - """The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends.""" + """The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type no answer, or the input ends.""" try: # Annotated since mypy infers input_or's T as object from the lambda. answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, ask)) @@ -110,4 +110,4 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") - return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed") + return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended without anything typed") diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index e80fbef0..524c232d 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -76,7 +76,7 @@ class Reply: answered_before: str = dataclasses.field(metadata={"description": "With interrupt true, a [human] line from earlier in the chunk that answered the question the worker asks now, quoted verbatim, without elisions. Empty otherwise."}) left_open: str = dataclasses.field(metadata={"description": "With answered_before set, the words of that line that leave open what the question asks, quoted verbatim; the question ends with them. Empty otherwise."}) question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."}) - # True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed. + # True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it without typing anything. release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."}) # Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by. reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."}) diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 23941832..805d2546 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -46,7 +46,7 @@ def moment(stamp: str) -> datetime.datetime: return datetime.datetime.fromisoformat(stamp) -# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. The worker writes none then, since the judge runs for seconds after its last message; a subagent or a /talk session still running may, which overcounts that message once. +# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. The worker writes none then, since the judge runs for seconds after its last message. A subagent or a /talk session still running may write one, and that message is then counted twice. def later(timestamp: str, start: datetime.datetime) -> bool: """Whether timestamp is after start; False where it is no time, or names no time zone to compare by.""" try: diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 8e69abf7..b842244a 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -59,7 +59,7 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> if not loop.effects.on_terminal(): say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects) return None - prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and 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 in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." + prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." ask = Ask(loop.effects.new_id(), str(loop.session.id), loop.root, question, loop.effects.now(), OpenOnTerminal()) with listed(loop.listed.folder, ask, loop.effects): unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects) diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index b9627d6e..e6c3ae30 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -122,7 +122,7 @@ Exit 2, when the human is needed to go on: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered - the input ends while a model is picked - an interrupt's answer is empty, or the input ends before one is typed -- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with - nothing typed +- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends without + anything typed - the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more Rerunning resumes any open session.""" diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index c1ca72db..6f7d7cb8 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -16,5 +16,5 @@ def read_premises(root: str) -> str | Failure: if len(bodies) > 1: return Failure(f"README.md has ## {name} more than once - no premises.") if not bodies[0]: - return Failure(f"README.md has nothing under ## {name} - no premises.") + return Failure(f"README.md has no text under ## {name} - no premises.") return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index ded13e00..73a01f94 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -342,7 +342,7 @@ class Premises(unittest.TestCase): b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.", b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.", b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.", - b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.", + b"# P\n## Goals\n\n## Audience\nme\n": "README.md has no text under ## Goals - no premises.", b"# P\n## Goals\n1. g\n## Audience\nme\n## Audience\nyou\n": "README.md has ## Audience more than once - no premises.", } (checkout.root / "sub").mkdir() @@ -801,7 +801,7 @@ class Interrupt(unittest.TestCase): transcript.unlink() run = checkout.run([*asked, interrupt()], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended without anything typed")) run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 7232235b..eb87d941 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -862,7 +862,7 @@ class Interrupts(unittest.TestCase): self.assertEqual(answer, "Use B.") self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said) stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0])) - self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed")) def test_makes_way_only_warns_where_loop_inbox_cannot_list_the_open_claude(self): self.paths.waiting.parent.mkdir(parents=True) @@ -892,7 +892,7 @@ class Interrupts(unittest.TestCase): send(self.paths.waiting, self.ask(), ClaudeEnded()) fake = FakeEffects(inputs=[self.opening]) stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended)) - self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX], [POLL_SECONDS])) + self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX], [POLL_SECONDS])) def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self): looked = [] @@ -902,7 +902,7 @@ class Interrupts(unittest.TestCase): return pid == INBOX and len(looked) == 1 fake = FakeEffects(inputs=[self.opening]) stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive)) - self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX, INBOX], [POLL_SECONDS])) + self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX, INBOX], [POLL_SECONDS])) def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self): for typed, answer_here in (([" /talk "], True), ([], False)): @@ -919,7 +919,7 @@ class Interrupts(unittest.TestCase): fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) stop, _ = self.put(fake) self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"]) - self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed")) def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) @@ -994,7 +994,7 @@ class RoutingCheck(unittest.TestCase): self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text()) ((args),) = fake.made("claude_on_terminal") self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"]) - self.assertIn(f"change nothing until they answer:\n- {call}", args[6]) + self.assertIn(f"don't change anything until they answer:\n- {call}", args[6]) self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}]) self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release") self.assertIn("Record what they decide in this checkout, the development clone", args[6]) @@ -1051,7 +1051,7 @@ class RoutingCheck(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")): self.assertIsNone(routing_check.raise_calls(self.root, new, Rung("m", "high"), self.loop(fake))) ((args),) = fake.made("claude_on_terminal") - self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6]) + self.assertIn(f"don't change anything until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6]) self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue()) self.assertIn("routing figures: full", said.getvalue()) [sent] = fake.dms diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index b943cc85..d4f3cb9c 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -12,7 +12,7 @@ of its question as fits; the loop's terminal shows it whole. Answer as on the lo line is sent, and the rest is dropped; a longer answer goes through /talk. - /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what - you typed; if you typed nothing, the loop stops. + you typed; if you typed no answer, the loop stops. - Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop. The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no diff --git a/bin/loop_state/__init__.py b/bin/loop_state/__init__.py index 7b9ce122..0042036c 100644 --- a/bin/loop_state/__init__.py +++ b/bin/loop_state/__init__.py @@ -1,4 +1,4 @@ """The files loop-claude and loop-inbox share: a running loop lists itself (running_loops.py, session_lock.py) and its question (waiting/), and both read the same paths (paths.py) and open claude for the human the same way (hand_over.py). -A change here changes both tools. It imports nothing from loop_claude/. +A change here changes both tools. It doesn't import anything from loop_claude/. """ diff --git a/bin/model_routing/prices.py b/bin/model_routing/prices.py index e3526621..e073d29c 100644 --- a/bin/model_routing/prices.py +++ b/bin/model_routing/prices.py @@ -1,4 +1,4 @@ -"""What a message costs at list prices. The weights that split a chunk's recorded cost between its messages, and the prices a Spent block records beside what a stretch spent, so a price wrong here stays wrong in every outcome written after it.""" +"""What a message costs at list prices. They weight how a chunk's recorded cost splits between its messages, and a Spent block records them beside what a stretch spent, so a wrong price stays wrong in every outcome written after it.""" import dataclasses from claude_code.tokens import tokens_of diff --git a/bin/model_routing/test_prices.py b/bin/model_routing/test_prices.py index 5999e34b..bd627c5a 100644 --- a/bin/model_routing/test_prices.py +++ b/bin/model_routing/test_prices.py @@ -9,7 +9,7 @@ from model_routing.prices import PRICES class Prices(unittest.TestCase): - def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_costs_nothing_in_a_figure(self): + def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_is_left_out_of_every_figure(self): self.assertEqual(sorted({rung.model for rung in LADDER} - set(PRICES)), []) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index be98ae95..e6602cee 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -9,7 +9,7 @@ sorts the items by release; within a release, question rows come first, then sec the rest, each group by score from highest, then by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below an item it blocks to just above the first such item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a -table without them. --check writes nothing and fails when the file is not ranked as it would be. +table without them. --check doesn't write anything and fails when the file is not ranked as it would be. A valid todo.md; ## Details and each item's detail are optional: @@ -69,7 +69,7 @@ A valid todo.md; ## Details and each item's detail are optional: item starts, so no blocker may sit in a later release, and no item may block itself or form a loop. An ID at or above Next ID fails; one below it that the table no longer holds was finished or deleted, and is dropped. -- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column. +- ## Items holds only the table: an order goes in the scores or the Blocked by column. - The table holds the columns above. One missing L, E or I fails, and so does one with a column this version does not know, since writing it would drop that column. - A table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still diff --git a/bin/release_plan/formula.py b/bin/release_plan/formula.py index f700d5b9..413da602 100644 --- a/bin/release_plan/formula.py +++ b/bin/release_plan/formula.py @@ -1,4 +1,4 @@ -"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can hold nothing else, and evaluated to a float.""" +"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can't hold anything else, and evaluated to a float.""" import ast import math diff --git a/bin/release_plan/todo_table.py b/bin/release_plan/todo_table.py index 43b0f8a1..eb9e4992 100644 --- a/bin/release_plan/todo_table.py +++ b/bin/release_plan/todo_table.py @@ -37,7 +37,7 @@ class Shape: """A shape of the items table: its columns, and how its goals cell reads and writes.""" # The score columns, in the order the table holds them. score_columns: tuple[str, ...] - # The columns a reader does without: a missing BLOCKED_BY reads as blocked by nothing, a missing score column as that score unset, and a missing Score column as not yet ranked. + # The columns a reader does without: a missing BLOCKED_BY reads as not blocked, a missing score column as that score unset, and a missing Score column as not yet ranked. optional: tuple[str, ...] # The columns rank_todo.py needs to rank a row, so no chunk starts on an item whose risk is unscored. risk_columns: tuple[str, ...] diff --git a/bin/repo_checks/__init__.py b/bin/repo_checks/__init__.py index 5a1d5fec..ef6f24c1 100644 --- a/bin/repo_checks/__init__.py +++ b/bin/repo_checks/__init__.py @@ -1,6 +1,6 @@ import pathlib -# Each module here checks a convention of the repo's files, as a linter does: import order, citations, CI, settings. So it reads source or Markdown, which technical-principles.md bans in a test of a unit's behaviour. +# Each module here checks a convention of the repo's own files, as a linter does, so it reads source or Markdown. technical-principles.md bans scanning source only in a test of a unit's behaviour. # The checkout root. ROOT = pathlib.Path(__file__).resolve().parents[2] diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 8e422b75..92bf885c 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -24,7 +24,7 @@ then replays the rounds on each rung below, highest first: the project's model a effort, which the ladder leaves out, then each ladder rung down to the ladder's lowest. It stops at the first rung that doesn't qualify. A rung qualifies where it finds as many findings as reach the bar and misses no 🔴 that both replays on the project's rung found; a replay that failed on it -finds nothing. For +finds none. For each replay, claude on the project's rung matches the report to the archived findings, and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each rung's count, each 🔴 it missed, and the lowest rung that, like each rung above it, qualifies. That rung is the evidence @@ -47,7 +47,7 @@ closes it with the header's line on the project principles. Like the loop, it tries claude three times running before it counts a reply as failed. A failed review or match leaves its round out, except on a rung below the project's, where it finds -nothing. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived +none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived round to replay, or a usage limit. """ import pathlib diff --git a/bin/review_replay/omit_comparison.py b/bin/review_replay/omit_comparison.py index 05911adf..8814492e 100644 --- a/bin/review_replay/omit_comparison.py +++ b/bin/review_replay/omit_comparison.py @@ -23,7 +23,7 @@ def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing if isinstance(found, Limited): return found runs.append(found) - # A failed replay found nothing, which would lower the bar where it had CLAUDE.md and count as misses where it had none. + # A failed replay found no findings, which would lower the bar where it had CLAUDE.md and count as misses where it had none. kept = rounds_without_failure(chosen, runs) first, second, third, without = ([found[run] for _, found in kept] for run in range(4)) return comparison(reviewed, project, [one for one, _ in kept], (first, second, third), without, len(chosen) - len(kept)) diff --git a/bin/review_replay/recall.py b/bin/review_replay/recall.py index 77fe957c..9b75b889 100644 --- a/bin/review_replay/recall.py +++ b/bin/review_replay/recall.py @@ -64,7 +64,7 @@ def mean_share(rounds: list[Round], reference: Reference) -> Fraction: def needed(rounds: list[Round], reference: Reference) -> int: - """How many of rounds' findings a rung needs to find: the fewest that reach the project's rung's mean share less MARGIN. Zero or below, no rung is tried, since a rung that found nothing would qualify.""" + """How many of rounds' findings a rung needs to find: the fewest that reach the project's rung's mean share less MARGIN. Zero or below, no rung is tried, since a rung that found none would qualify.""" return math.ceil((mean_share(rounds, reference) - MARGIN) * held(rounds)) @@ -118,7 +118,7 @@ def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Ro on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what) if isinstance(on_rung, Limited): return on_rung - # A failed replay on a candidate found nothing, so it lowers that rung's count and never lifts it to what a rung needs. + # A failed replay on a candidate found none, so it lowers that rung's count and never lifts it to what a rung needs. one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung]) recalls.append(one) if not one.qualifies: diff --git a/bin/review_rules/comprehension_history.py b/bin/review_rules/comprehension_history.py index 83b467bd..e6990312 100644 --- a/bin/review_rules/comprehension_history.py +++ b/bin/review_rules/comprehension_history.py @@ -9,7 +9,7 @@ from records.utc_stamp import utc ARCHITECT = "Inherited architect" DECIDED_BY = "decided by" DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") -# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing. +# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything. FLOOR = decimal.Decimal("7.0") HARDEST_FIRST = "hardest first" HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$") diff --git a/bin/review_rules/reviewer_context.py b/bin/review_rules/reviewer_context.py index 46df0598..eadcd3f0 100644 --- a/bin/review_rules/reviewer_context.py +++ b/bin/review_rules/reviewer_context.py @@ -37,7 +37,7 @@ def starts_bare(agent: str, home: pathlib.Path) -> bool: def hook_reply(given: str, home: pathlib.Path) -> str: - """What the SubagentStart hook prints for its input given: the context for a reviewer that starts without the instruction files, nothing for any other agent.""" + """What the SubagentStart hook prints for its input given: the context for a reviewer that starts without the instruction files, and no text for any other agent.""" try: read = json.loads(given) except ValueError: diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index 602324ed..fcbce7f8 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -110,7 +110,7 @@ def entries(path: pathlib.Path) -> list[Entry]: def subagent(transcript: pathlib.Path) -> Subagent: - """The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable names nothing.""" + """The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable doesn't name anything.""" path = transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json") try: meta = json.loads(path.read_text(encoding="utf-8")) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index b15401e5..23a814bd 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -102,7 +102,7 @@ def answer(checked: Checked, what: str, now: float) -> int: if checked.blocked: return 2 logs = [(breach, reason, log_path(breach.directory)) for breach, reason in checked.overridden] - # Resolve every log before writing any, so a call that ends blocked has logged nothing. + # Resolve every log before writing any, so a call that ends blocked hasn't logged anything. unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)] if not unloggable: for breach, reason, log in logs: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index b72397e8..9d3fee37 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -55,7 +55,7 @@ RULES: dict[RuleName, Rule] = { ), # A reviewer only reports, so no marker waives it. "reviewer-report": Rule( - f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/", + f"a reviewer writes only its report, with Write, into a file under ~/{REPORTS}/", "a Write, Edit or MultiEdit call from inside an agent under agents/", overridable=False, ), diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index befdf7e1..0522f917 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -860,9 +860,9 @@ class Hook(unittest.TestCase): for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]: with self.subTest(rule): self.assertIn(f" {rule}\n The rule: ", helped) - self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped) + self.assertIn("reviewer-report\n The rule: a reviewer writes only its report", helped) self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n") - self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives says nothing of overrides") + self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives doesn't say anything of overrides") class TodoRankCheck(unittest.TestCase): @@ -900,7 +900,7 @@ class TodoRankCheck(unittest.TestCase): def test_its_own_rank_todo_failing_silently_names_the_script_and_exit(self): checkout = self.changed_plan(f"{self.folder}/clone", "import sys\nsys.exit(3)\n") - self.assertEqual(self.details(checkout), [f"{checkout}/bin/rank_todo.py --check failed with exit 3 and printed nothing"]) + self.assertEqual(self.details(checkout), [f"{checkout}/bin/rank_todo.py --check failed with exit 3 and printed no output"]) def test_its_own_rank_todo_running_past_the_limit_is_named(self): checkout = self.changed_plan(f"{self.folder}/clone", "import signal\nsignal.pause()\n") diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index c5c67e82..42f47b67 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -36,7 +36,7 @@ def check_failures(top: str, todo: pathlib.Path, own: pathlib.Path) -> list[str] return [f"{script} --check could not run: {failure}"] if ran.returncode == 0: return [] - return ran.stderr.splitlines() or [f"{script} --check failed with exit {ran.returncode} and printed nothing"] + return ran.stderr.splitlines() or [f"{script} --check failed with exit {ran.returncode} and printed no output"] def same_repo(top: str, own: pathlib.Path) -> bool: diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 929005fb..175cc767 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -61,7 +61,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]: - """What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux, or where PATH finds no docker to cap.""" + """What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; none where the memory is unknown, as off Linux, or where PATH finds no docker to cap.""" path = env.get("PATH", "") if memory is None or shutil.which("docker", path=without_path_entry(path)) is None: return {} diff --git a/bin/rung_replay/search.py b/bin/rung_replay/search.py index 02b77fcc..719d0c84 100644 --- a/bin/rung_replay/search.py +++ b/bin/rung_replay/search.py @@ -61,7 +61,7 @@ def replayed( if isinstance(on_reference, Limited): return on_reference held = [(case, aim) for case, reply in zip(cases, on_reference) if (aim := reproduced(case, reply))] - # With nothing to hold a rung to, no rung would miss anything. + # Without anything to hold a rung to, no rung would miss anything. if not held: return Replay(on_reference, [], None) climbed: list[Tried[Case, Aim, Answer]] = [] diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index 14e85039..f0653215 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -111,7 +111,7 @@ UNMERGED = [ "Chunks that left no merge commit:", "", "- Each is the run of commits on the default branch that share one commit time, since a rebase merge replays a pull request's commits at once. Its guesses come from the todo.md before its first commit.", - "- Two pull requests merged in the same second read as one chunk, so a pull request that shipped nothing adds its lines, files and rounds to the chunk it shares a time with.", + "- Two pull requests merged in the same second read as one chunk, so a pull request that shipped no item adds its lines, files and rounds to the chunk it shares a time with.", "- A run whose commits all kept their author time was never replayed: it was pushed or fast-forwarded as committed. It may hold only part of its pull request, so the medians and the rank correlations leave it out.", "- Rebase drops a round's commit that changed no file, so their rounds and findings are at least what history shows, and the medians count the rebased ones as shown.", ] diff --git a/bin/score_outcomes/results.py b/bin/score_outcomes/results.py index a6fc4670..b526f07e 100644 --- a/bin/score_outcomes/results.py +++ b/bin/score_outcomes/results.py @@ -48,7 +48,7 @@ SHOWN = ("L", "E", "I", "R", "S", "C") def results_of(chunk: BranchChunk, numstat: str, details: dict[int, str], tree: dict[str, int]) -> list[Result]: - """What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed nothing but the plan and the records. details holds each item's detail in the todo.md the chunk started from, and tree each file's lines before the chunk, as file_lines reads them.""" + """What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed only the plan and the records. details holds each item's detail in the todo.md the chunk started from, and tree each file's lines before the chunk, as file_lines reads them.""" changed = [row.split("\t", 2) for row in numstat.splitlines()] work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK] if not work: diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index 50d8507d..10fafde1 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -244,7 +244,7 @@ Reversals: the human's typed answers that reversed a choice the worker took on i def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self): text = report_text([result(1, 5, 3, None, landing="rebase")], [], None, []) self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1]) - self.assertIn("a pull request that shipped nothing adds its lines, files and rounds", text) + self.assertIn("a pull request that shipped no item adds its lines, files and rounds", text) self.assertIn("at least what history shows, and the medians count the rebased ones as shown.", text) self.assertIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None, landing="push")], [], None, [])) self.assertNotIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None)], [], None, [])) diff --git a/bin/subagent_rung/main.py b/bin/subagent_rung/main.py index f76f6ff1..b101f7e9 100644 --- a/bin/subagent_rung/main.py +++ b/bin/subagent_rung/main.py @@ -7,7 +7,7 @@ a defect, a level from 1 to 4 scored as for a todo.md item. It prints the rung t the model's cheapest rung, the project's rung, in the Agent tool's words, such as `model sonnet, effort high`. --plan, for a task that files or scores todo.md items, prints the project's rung where that L picks a lower one, as ~/.claude/rules/todo-items.md lets only the project's rung or above -plan. For a model off the routing ladder, the tool prints nothing on stdout, says so on stderr and +plan. For a model off the routing ladder, the tool doesn't print anything on stdout, says so on stderr and exits 0; launch the subagent with no model or effort. Exit 1, saying why, on bad arguments. diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 1c007441..eff414da 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -12,20 +12,20 @@ The cells take the format rank_todo.py --help states; the letter flags take uppe add takes Next ID as the item's ID and raises Next ID by one. It writes the row, with the tagline in bold and each | in it escaped, and the detail it reads from stdin, if any, under ## Details. The detail may hold no ## or ### heading. -It prints `Filed item <ID>.` It writes nothing where ranking fails or scores the item under the bar. +It prints `Filed item <ID>.` It doesn't write anything where ranking fails or scores the item under the bar. finish removes the item's row and its detail. With --changelog it adds the bullet first under CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the file, where missing. It refuses where that section holds ### subsections: add the bullet by hand. Where CHANGELOG.md exists, finish needs --changelog or --no-changelog, so no bullet is left out by -mistake. It prints `Finished item <ID>.` It writes nothing while docs/decisions.md cites the item. +mistake. It prints `Finished item <ID>.` It doesn't write anything while docs/decisions.md cites the item. show reads only todo.md. It prints the items table's header and divider, item <ID>'s row, and its detail from its ### heading to the next item's, sub-headings included. It fails, saying so, where todo.md has no row for <ID>. Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:` -or `not finished:` means it wrote nothing. +or `not finished:` means it didn't write anything. """ import argparse import pathlib @@ -127,7 +127,7 @@ def finish(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure: def finish_texts(args: argparse.Namespace, todo: pathlib.Path, changelog: pathlib.Path) -> tuple[ranking.Ranked, str | None] | Failure: """What finish writes: todo ranked without item args.id, and changelog's new text, None where finish leaves it as is.""" if changelog.exists() and args.changelog is None and not args.no_changelog: - return Failure("CHANGELOG.md exists beside todo.md; pass --changelog <bullet>, or --no-changelog where the repo publishes nothing") + return Failure("CHANGELOG.md exists beside todo.md; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything") texts = plan_file.read_all(todo) if isinstance(texts, Failure): return texts diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index bf633cc0..3afce2e5 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -33,7 +33,7 @@ JUDGE_COST_AT = re.compile(rf"^{re.escape(JUDGE)}(.+)\n{re.escape(JUDGE_COST)}([ # The claude-config release and commit that ran the cycle, on the line before JUDGE, such as `Config: v0.8.0 (<sha>)`. CONFIG = "Config: " -# Opens the block of what the work since the previous outcome that recorded a spend spent; an outcome that spent nothing has none. +# Opens the block of what the work since the previous outcome that recorded a spend spent; an outcome that didn't spend anything has none. SPENT = "Spent since " KINDS = "input, cache write 5m, cache write 1h, cache read, output" # Who spent, such as `worker`, `judge` or `Explore "Search the hooks"`, and the model they ran on. diff --git a/bin/wait_for/main.py b/bin/wait_for/main.py index dc042dac..9023f106 100644 --- a/bin/wait_for/main.py +++ b/bin/wait_for/main.py @@ -67,7 +67,7 @@ def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) if text is None: return Failure(f"{file} did not appear in {timeout:g} s") last = line_in(text, None) - wanted = f"no line matching `{pattern}`" if pattern is not None else "nothing" + wanted = f"no line matching `{pattern}`" if pattern is not None else "no text" return Failure(f"{file} held {wanted} after {timeout:g} s" + (f"; its last line: {last}" if last is not None else "")) clock.sleep(min(POLL_SECONDS, left)) diff --git a/bin/wait_for/test_wait_for.py b/bin/wait_for/test_wait_for.py index 08d880b4..57a77f3e 100644 --- a/bin/wait_for/test_wait_for.py +++ b/bin/wait_for/test_wait_for.py @@ -90,7 +90,7 @@ class WaitFor(unittest.TestCase): def test_an_empty_file_gives_up_saying_it_held_nothing_and_no_last_line(self): self.file.write_text("") clock = Clock() - self.assertEqual(main.waited(str(self.file), None, 3, clock), Failure(f"{self.file} held nothing after 3 s")) + self.assertEqual(main.waited(str(self.file), None, 3, clock), Failure(f"{self.file} held no text after 3 s")) self.assertEqual(clock.now, 3) def test_sleeps_only_the_time_left_before_the_timeout(self): diff --git a/docs/decisions.md b/docs/decisions.md index c523e55a..ca5246d0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -52,7 +52,7 @@ Settling a call is the human's. The chunk that settles the calls cites, in `docs ## bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase` -2026-11-12, lilleman, from the release review of 0.9.0. Applies `principles/technical-principles.md` → "Most code should have automated tests", whose "parametrize the cases" asks for one reported result per case. The tests are plain unittest, run by pytest, and pytest's `parametrize` doesn't work on a `TestCase` method; `subTest` is the unittest mechanism that does: each case reports and fails on its own, with its parameters named. A test body that loops over its cases for another reason, or holds a branch, is still a breach. Valid while the tests stay in plain unittest. +2026-11-12, lilleman, from the release review of 0.9.0. Applies `principles/technical-principles.md` → "Most code should have automated tests", whose "parametrize the cases" asks for one reported result per case. The tests are plain unittest, run by pytest, and pytest's `parametrize` doesn't work on a `TestCase` method; `subTest` is the unittest mechanism that does: each case reports and fails on its own, with its parameters named. A test that loops over its cases itself, outside `subTest`, or holds a branch, is still a breach. Valid while the tests stay in plain unittest. ## bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names @@ -80,7 +80,7 @@ The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same c ## comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor blocks nothing, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor doesn't block anything, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats. ## deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's @@ -116,7 +116,7 @@ Valid while `~/.claude` is a checkout of this repo. 2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file under `~/.claude/skills/larv-review/standards/` whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current. -2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/` does not count: the judge reads the live `~/.claude`, which holds the write only once it merges and the checkout is pulled. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" holds nothing open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it. +2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/` does not count: the judge reads the live `~/.claude`, which holds the write only once it merges and the checkout is pulled. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" doesn't hold anything open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it. 2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude. @@ -244,13 +244,13 @@ Valid while no published standard sets either number, the reading-cost window st ## review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none; the stability pass doesn't rerun on a round's fixes where every 🔴 and 🟡 of that round asked only that a named mutant be killed or a named failing test pass, and the tests and the mutation command run clean on the fixes -2026-10-08, lilleman. Serves goal 1.4. An audit of the four costliest archived chunks found nearly every finding that mattered in a pass's first round; when every fix, a nit's included, re-entered review, later rounds mostly re-checked the last fix, reworded what an earlier round wrote, or contradicted another round on the same line. A round 2 caught real bugs only where a fix changed behaviour, so stability still reruns on every fix that does, and security on every fix that opens an untrusted-input boundary or touches authn/authz, secrets or crypto. Valid while round-2 reviews of nit and prose fixes keep changing nothing a user would notice. +2026-10-08, lilleman. Serves goal 1.4. An audit of the four costliest archived chunks found nearly every finding that mattered in a pass's first round; when every fix, a nit's included, re-entered review, later rounds mostly re-checked the last fix, reworded what an earlier round wrote, or contradicted another round on the same line. A round 2 caught real bugs only where a fix changed behaviour, so stability still reruns on every fix that does, and security on every fix that opens an untrusted-input boundary or touches authn/authz, secrets or crypto. Valid while round-2 reviews of nit and prose fixes change only what a user wouldn't notice. -2026-10-13, lilleman through todo item 97. Serves goals 1.4 and 1.5. From round 2 a pass reviews only how the chunk answered its previous round, each fix and each dismissal with its reason, and reports only one that is plainly wrong or worse than the change it answered. A fix from another pass that re-enters it is still reviewed as a first round would review it, limited to its lines. Reviewing all that changed had a reviewer find new gaps in each round's fixes, so a pass ran to its cap. Valid while round-2 findings outside a round's answers keep changing nothing a user would notice. +2026-10-13, lilleman through todo item 97. Serves goals 1.4 and 1.5. From round 2 a pass reviews only how the chunk answered its previous round, each fix and each dismissal with its reason, and reports only one that is plainly wrong or worse than the change it answered. A fix from another pass that re-enters it is still reviewed as a first round would review it, limited to its lines. Reviewing all that changed had a reviewer find new gaps in each round's fixes, so a pass ran to its cap. Valid while round-2 findings outside a round's answers change only what a user wouldn't notice. 2026-10-29, lilleman. Serves goals 1.4 and 1.5. A 🟡 fix no longer reruns its pass. One project's chunk on 2026-10-29, a README paragraph and plan rows, took 10 review rounds in 45 minutes, and three of its four second rounds answered only 🟡 findings, such as the wording of a question's options. Round 2 found 12 🔴 in about 200 runs since 2026-10-21, mostly in round 1's fixes of 🔴 findings, so a 🔴 fix still reruns its pass. A 🟡 fix that breaks something merges unreviewed by its pass; another pass whose row it meets for a 🔴 fix in the same round still reviews it. Valid while 🔴 findings in later chunks, fixing code a 🟡 fix wrote, stay rare. -2026-11-12, lilleman through todo item 308. Serves goal 1.4. Since the worker runs the mutation command before each stability round, a finding that asks only that a named mutant be killed or a named failing test pass has an answer a run can check. The archive from 2026-09-30 to 2026-11-12 holds 326 stability reports of round 2 or later, from 13 projects, and 81 of those reports open with BLOCK (`stability-skip-count/`). For each of the 326, the 🔴 and 🟡 lines of the report before it were matched on mutant and test-failure wording. Every such line matched in 5 of those earlier reports. Read by hand, 1 of the 5 asked only that a failing test pass, and the round 2 after each of the 5 approved. So none of the 81 BLOCKs fell in a round this skips. The skip needs every 🟡 to be of that kind too: in one chunk on 2026-11-12, round 1's only 🔴 was a red suite, and round 2 blocked on a 🟡 whose answer was wrong, which no test or mutant showed. A fix may not edit the named failing test, since a test made to pass that way shows nothing. Fixes from such a round still rerun every other pass whose row they meet. Valid while code that such a skipped round's fixes wrote is rarely what a later chunk's 🔴 findings fix. +2026-11-12, lilleman through todo item 308. Serves goal 1.4. Since the worker runs the mutation command before each stability round, a finding that asks only that a named mutant be killed or a named failing test pass has an answer a run can check. The archive from 2026-09-30 to 2026-11-12 holds 326 stability reports of round 2 or later, from 13 projects, and 81 of those reports open with BLOCK (`stability-skip-count/`). For each of the 326, the 🔴 and 🟡 lines of the report before it were matched on mutant and test-failure wording. Every such line matched in 5 of those earlier reports. Read by hand, 1 of the 5 asked only that a failing test pass, and the round 2 after each of the 5 approved. So none of the 81 BLOCKs fell in a round this skips. The skip needs every 🟡 to be of that kind too: in one chunk on 2026-11-12, round 1's only 🔴 was a red suite, and round 2 blocked on a 🟡 whose answer was wrong, which no test or mutant showed. A fix may not edit the named failing test, since a test made to pass that way doesn't show anything. Fixes from such a round still rerun every other pass whose row they meet. Valid while code that such a skipped round's fixes wrote is rarely what a later chunk's 🔴 findings fix. ## review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review @@ -272,11 +272,11 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r ## review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health -2026-10-11, lilleman. Serves goal 1.4. A research repo's PR, in a repo with no consumer for the product-owner pass and no product for the architect, spent rounds of both, and of the comprehension check, on a probe. The opt-out is the project's to make, and only an entry titled `review opt-out:` makes it, so a project without one is reviewed as before (goal 1.3). No opted-out reviewer works against a goal or a technical principle: the principles audit, which has no opt-out, still judges KISS and every other principle, so the entry names no plan item that ends it. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor blocks nothing. 2026-10-18, lilleman, answering the review of PR #324: a project that opts out of the comprehension check voids code health in its README too: without the check the goal has no signal, and, never measured, it would weigh four times its weight forever. `rank_todo.py` refuses the plan of such a project until its README voids it. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers. +2026-10-11, lilleman. Serves goal 1.4. A research repo's PR, in a repo with no consumer for the product-owner pass and no product for the architect, spent rounds of both, and of the comprehension check, on a probe. The opt-out is the project's to make, and only an entry titled `review opt-out:` makes it, so a project without one is reviewed as before (goal 1.3). No opted-out reviewer works against a goal or a technical principle: the principles audit, which has no opt-out, still judges KISS and every other principle, so the entry names no plan item that ends it. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor doesn't block anything. 2026-10-18, lilleman, answering the review of PR #324: a project that opts out of the comprehension check voids code health in its README too: without the check the goal has no signal, and, never measured, it would weigh four times its weight forever. `rank_todo.py` refuses the plan of such a project until its README voids it. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers. ## review: a project decision may suspend the comprehension check for the plan items it names -2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it. +2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet doesn't say anything about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check doesn't block anything now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it. ## review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds @@ -318,17 +318,17 @@ Claude Code's own subagent prompt tells a subagent to return findings rather tha Before this change, reports took a median 19k tokens per chunk, 8% of the worker's peak context, and lines carrying a severity mark were 9–24% of a report (2026-10-08, over 68 archived transcripts). `review-replay` still counts each 🔴 and 🟡 by its line in the reviewer's reply, now a one-line summary. todo.md item 187 is to measure what the worker reads of the reports instead. -Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without it, the rule refuses nothing, and a reviewer may write anywhere. +Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without it, the rule doesn't refuse anything, and a reviewer may write anywhere. ## review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose -2026-10-13, lilleman through todo item 97, implemented by claude. Serves goals 1.4 and 1.5. Anthropic's Claude Code best practices: "A reviewer prompted to find gaps will usually report some, even when the work is sound… Chasing every finding leads to over-engineering." 320 of this repo's 876 commits answered a review round. So stability and product-owner drop a finding that is none of these, and stability leaves the style of comments to prose, which reads every comment a chunk touches. An architect finding that names no later change it makes harder cannot be checked, so it is dropped. The architecture pass and the comprehension check keep their whole-project view, which guards goal 1.1 as a project grows. Valid while the findings these rules drop keep changing nothing a user would notice. +2026-10-13, lilleman through todo item 97, implemented by claude. Serves goals 1.4 and 1.5. Anthropic's Claude Code best practices: "A reviewer prompted to find gaps will usually report some, even when the work is sound… Chasing every finding leads to over-engineering." 320 of this repo's 876 commits answered a review round. So stability and product-owner drop a finding that is none of these, and stability leaves the style of comments to prose, which reads every comment a chunk touches. An architect finding that names no later change it makes harder cannot be checked, so it is dropped. The architecture pass and the comprehension check keep their whole-project view, which guards goal 1.1 as a project grows. Valid while the findings these rules drop change only what a user wouldn't notice. 2026-10-28, lilleman: prose findings stay, since Claude's prose needs them, though prose's 105 first rounds since 2026-10-21 raised 498 🟡 and only 3 🔴. ## review: the comprehension check records how hard a project is to read, and no score blocks a merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out -2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that changed nothing (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/release_plan/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do. +2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that didn't change anything (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/release_plan/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do. 2026-10-13, lilleman. No published study validates simulated reader panels as a measure of how easy code is to understand, and no test of whether the panel's signal beats its noise has run. So no ruling, score or floor blocks a merge. The runs go on, so the history keeps the scores and the places the seats found hard, for later measurement. The architect, the stability reviewer and a session filing an item read the newest places: the newest scoring run's and each later ruling's places a seat voted worse. Those are the places a chunk can improve. The check runs once per chunk, on the branch as review left it. A chunk that leaves a touched place as hard says why in its PR summary, not in a decline's record, which would outlive the place. @@ -507,7 +507,7 @@ Valid while the archived verdicts show what a judge should return, and until a n The rungs, least competent first: Sonnet 5.5 at high; Opus 5.5 at medium; Fable 5.2 at low and medium; Opus 5.5 at xhigh; Fable 5.2 at high and max. The 2026-11-11 note below put them so. Before it they were Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max, after the 2026-10-29 note took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). The first cut, from the index read 2026-10-14, dropped Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index fell among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scored it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. Fable 5.2 at max tops the index outright, so that exception has ended. -A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the steps on 2026-10-16 as a guess. `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings. A change to the ladder or the steps is lilleman's. +A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder doesn't route anything: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the steps on 2026-10-16 as a guess. `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings. A change to the ladder or the steps is lilleman's. 2026-10-21, lilleman, settling the routing calls stamped 2026-10-21T20:33:29Z: L 1 steps one rung down, not two as before, so an Opus 5.5 project runs no worker on Haiku 5.5. A delegated subagent takes the same steps, so an L 1 search moves off Haiku 5.5 too: lilleman chose one set of steps for chunk workers and subagents alike, so loop-claude, `subagent-rung` and rule-hook read one table (code health). No figure yet shows whether Sonnet 5.5 searches better than Haiku 5.5, so this costs more per search for a gain nobody has measured (goal 1.4). The calls came from loop-claude's routing figures, measured at cycle 165 over 46 chunks. Chunks started on Haiku 5.5 at max took a mean 7.8 review rounds past each pass's first, against 2.8 on Sonnet 5.5 at high, and 0.2 unfinished verdicts, against 0.1. The figures also called for moving workers off Sonnet 5.5 at high, whose chunks took 0.1 unfinished verdicts against 0.0 on Opus 5.5 at medium. lilleman kept L 2 on Sonnet 5.5, since that gap rests on one or two verdicts. @@ -599,7 +599,7 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc 2026-11-09, larv-review, through todo item 12. Serves goal 1.1: a merge no longer rests on the worker's word. larv-review's gate was the local run alone, which it skips when the last stability round left the suite green, so an unattended chunk could merge on the worker's own report. gitea.larvit.se's runners labelled `docker-host` run `.gitea/workflows/ci.yml`, which runs `ci.sh` on the committed HEAD in a pinned Python container; the script's header says how. A run takes about 3 minutes. -The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override. Whoever adds a rule check to CI must also let it read the PR body's `rule-override`. Valid while gitea.larvit.se runs a runner labelled `docker-host`. +The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body doesn't have anything to override. Whoever adds a rule check to CI must also let it read the PR body's `rule-override`. Valid while gitea.larvit.se runs a runner labelled `docker-host`. ## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code @@ -633,7 +633,7 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the 2026-10-02, lilleman, on the `principle` exemption. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. -2026-10-15, lilleman: the scores follow a researched method, built by `todo.md` items 149 and 151 after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R is L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. A task's L and E + I pick its rungs in place of R (2026-10-16, lilleman), as `routing: one ladder` records. There is no C column: what it scored beyond size, spread and novelty, which L already holds, is complexity, and that adds almost nothing once size is accounted for. There is no A column either, since the Audience says whose value the goals serve. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals mark them. Two parts are not built yet and hold once their items ship: each release fills by priority up to a capacity it states (item 149), and each project keeps 10 to 20 settled decisions to test its goals against (item 151). +2026-10-15, lilleman: the scores follow a researched method, built by `todo.md` items 149 and 151 after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R is L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. A task's L and E + I pick its rungs in place of R (2026-10-16, lilleman), as `routing: one ladder` records. There is no C column: what it scored beyond size, spread and novelty, which L already holds, is complexity, and that adds almost no information once size is accounted for. There is no A column either, since the Audience says whose value the goals serve. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals mark them. Two parts are not built yet and hold once their items ship: each release fills by priority up to a capacity it states (item 149), and each project keeps 10 to 20 settled decisions to test its goals against (item 151). 2026-10-16, PR #283: items rank by `Score = 100 * V / (2**S + F)`. The 100 lets a score read to one decimal. 2**S is the cost. V sums, over the goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. A Moves column holds `1.1 by 8, 1.2 by 5`. An item names a maintain goal only as a defect restoring it, or by the confidence a test, gate leg or probe adds to it, as the defect paragraph below and the 2026-11-09 paragraph after it say. diff --git a/docs/scoring-and-goals-research.md b/docs/scoring-and-goals-research.md index 41626f39..e2f93ecf 100644 --- a/docs/scoring-and-goals-research.md +++ b/docs/scoring-and-goals-research.md @@ -22,7 +22,7 @@ Every study below predicts from the diff or history, none from a description, so 6. **Live config or infrastructure as code.** About 70% of Google's outages come from changes to a live system (sre.google/sre-book/introduction). Syntax and configuration defects were 36.5–62.7% of IaC defects at four organisations (Rahman et al. 2018, arXiv:1809.07937). 7. **New technology or AI-written code**, with mixed evidence (Pearce et al. 2022, S&P†; Perry et al. 2023, CCS†; Spracklen et al. 2025, USENIX Security). -Complexity metrics add almost nothing once size is accounted for (El Emam et al. 2001, TSE, doi:10.1109/32.935855†). So a separate difficulty score beside size, spread and novelty measures nothing new. +Complexity metrics add almost no information once size is accounted for (El Emam et al. 2001, TSE, doi:10.1109/32.935855†). So a separate difficulty score beside size, spread and novelty measures nothing new. ## Value per cost, not a sum diff --git a/presentation/README.md b/presentation/README.md index a0111ad3..06c66ec9 100644 --- a/presentation/README.md +++ b/presentation/README.md @@ -18,7 +18,7 @@ The page lives at https://claude.ai/artifact/RJJwgRAke3viuqTYEgu1a9. To update i ## Who it is for -People in tech who want to build software factories, work with AI tools more efficiently, and stop fighting their agents. They know git, pull requests and the shell, and nothing about agent loops. Write for a tired reader on a Monday morning without coffee: one fact per sentence, each term explained before it is used, and no filler. +People in tech who want to build software factories, work with AI tools more efficiently, and stop fighting their agents. They know git, pull requests and the shell, and don't know anything about agent loops. Write for a tired reader on a Monday morning without coffee: one fact per sentence, each term explained before it is used, and no filler. ## How the pages are built diff --git a/principles/technical-principles.md b/principles/technical-principles.md index cf74d2c1..0bc7b932 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -20,7 +20,7 @@ * Prefer deep modules: a small, intuitive interface in front of a lot of hidden work. - A caller should know what a call does and what it returns, without knowing how it does it. `fs.writeFile("notes.txt", data)` hides opening the file, encoding, buffering, permissions and the disk itself. Yet anyone reading that line knows the outcome: the data is written, or the call fails and says why. - A module hides how it works, never what it depends on: what "Functional core, imperative shell" injects stays injected. - - A shallow module costs more to learn than it saves. BANNED: a wrapper that only renames the function it calls; a module whose callers must make three calls in an order nothing but their memory enforces. GOOD: one call that does the whole job and handles the order itself. + - A shallow module costs more to learn than it saves. BANNED: a wrapper that only renames the function it calls; a module whose callers must make three calls in an order only their memory enforces. GOOD: one call that does the whole job and handles the order itself. - When this pulls against "Explicit over implicit", the deep module wins, unless hiding the work makes it harder for someone new to the project to tell what the call does. * Make invalid states unrepresentable. - Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors. @@ -30,7 +30,7 @@ * One owner per value; a reader can name every writer. - At every scale, from a variable to a table, file or volume: two components writing the same one are one component with a seam nobody declared. - The test: from the code in front of them, can a reader list every writer to this value, and the order those writers run in? - - BANNED: a record passed to 24 functions, 13 of which mutate it and return nothing. GOOD: one type owns the value, the rest call it and take a result. + - BANNED: a record passed to 24 functions, 13 of which mutate it and don't return anything. GOOD: one type owns the value, the rest call it and take a result. - BANNED: `fill(set)` then `adjust(set)`, where swapping the two lines changes the output. GOOD: `const filled = fill(); const adjusted = adjust(filled);` - BANNED: `stack` and `edges`, two arrays a comment says must stay in step. GOOD: `edges` derived from `stack`, or one array whose element type holds both. - Allowed, never flag: mutation that never leaves the function that made it; a loop counter; data shared and never written; a state machine with named states and one transition function. diff --git a/reviewer-merge-trials/README.md b/reviewer-merge-trials/README.md index d193aac5..a5bedccb 100644 --- a/reviewer-merge-trials/README.md +++ b/reviewer-merge-trials/README.md @@ -123,7 +123,7 @@ The 5 release reviews hold 64 archived findings: architecture 47, principles 17. ## Candidate 3: override-reviewer folded into stability -The archive holds 38 override-reviewer runs. None has a 🔴 or 🟡, so there is nothing to recover. Nothing was replayed. +The archive holds 38 override-reviewer runs. None has a 🔴 or 🟡, so there isn't anything to recover. Nothing was replayed. **Verdict: no data.** diff --git a/skills/comprehension-panel/SKILL.md b/skills/comprehension-panel/SKILL.md index 4d6f7a6b..ab93428c 100644 --- a/skills/comprehension-panel/SKILL.md +++ b/skills/comprehension-panel/SKILL.md @@ -23,7 +23,7 @@ Hold all of these or the comparison doesn't prove anything. one. Seats that read different amounts produce numbers nothing can compare. - **Blind.** Deny the project's own conclusions — the plan, a decision log, prior review output — and never show a panelist the metric under test. An anchored reader is a wasted one. -- **Check what the harness pre-loads, before launching.** `CLAUDE.md` may be nothing but +- **Check what the harness pre-loads, before launching.** `CLAUDE.md` may hold only `@AGENTS.md`, and an `@file` import lands in a subagent's context ahead of its first tool call. That is harmless for a reader who was going to read the charter anyway, and fatal to the architects' README-and-tree-only step. Read the project's `CLAUDE.md` and resolve its imports @@ -121,7 +121,7 @@ Identical shape for all seven: 2. The single unit they would least want to be asked to modify, and why. 3. What they expected to be hard and found easy. 4. Prose debt: which documentation they needed, what it cost to find, and — separately — which - prose they read that told them nothing the code was not already saying. Both halves matter. + prose they read that didn't tell them anything the code wasn't already saying. Both halves matter. Panels reliably find that the answers exist and are unfindable, which is a different defect from prose that should not exist at all, and the fixes are opposite: index the first, delete the second. diff --git a/skills/comprehension-panel/seat-prompts.md b/skills/comprehension-panel/seat-prompts.md index 632a4a1b..4bbe9c5c 100644 --- a/skills/comprehension-panel/seat-prompts.md +++ b/skills/comprehension-panel/seat-prompts.md @@ -51,7 +51,7 @@ Report, in this shape: 1. Ranked 5–8 hardest places, hardest first. Each: path:line and the unit's name, one to three sentences on what specifically defeated you (branches held at once, length, a misleading name, missing context, state mutated out of sight, a rule you had to hunt for elsewhere) and whether anything resolved it (a comment, the charter, a test) or it stayed opaque. 2. The single unit you would least want to be asked to modify, and why. 3. What you expected to be hard and found easy. -4. Prose debt: documentation you needed and what it cost to find; separately, prose you read that told you nothing the code was not already saying. +4. Prose debt: documentation you needed and what it cost to find; separately, prose you read that didn't tell you anything the code wasn't already saying. 5. Navigation, Locality, Shape, Self-sufficiency, overall — each with one sentence naming the anchor it sits against and the concrete thing that holds it there. A score with no named cause is discarded. ``` diff --git a/skills/larv-review/standards/comments.md b/skills/larv-review/standards/comments.md index b7daa444..adc31d98 100644 --- a/skills/larv-review/standards/comments.md +++ b/skills/larv-review/standards/comments.md @@ -24,7 +24,7 @@ Default to NO comment. Delete one that is any of: ## Negation, history and limitations: name the action, or leave it out -Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. +Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation without a step to take instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. ## Links and pointers diff --git a/todo.md b/todo.md index c6a56cff..18f4bd07 100644 --- a/todo.md +++ b/todo.md @@ -365,7 +365,7 @@ Weigh the widely used tmux-resurrect and tmux-continuum plugins against a script ### 267. Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop. -11 runs in the archive ended with "Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed", each leaving its chunk open until the human restarted the loop. That stop comes from `human_typed` in `bin/loop_claude/cycle/interrupt.py`, after the claude opened for `/talk` or for a release ready to cut ends with no human turn. An empty line at the terminal stops the loop the same way, in `first_answer`. Item 268 removes one of the cases that opens claude. +11 runs in the archive ended with "Stopped: the human is needed to answer the question above, but the interrupt ended without anything typed", each leaving its chunk open until the human restarted the loop. That stop comes from `human_typed` in `bin/loop_claude/cycle/interrupt.py`, after the claude opened for `/talk` or for a release ready to cut ends with no human turn. An empty line at the terminal stops the loop the same way, in `first_answer`. Item 268 removes one of the cases that opens claude. ### 4. Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran. diff --git a/workflow-bench/compare-prompt.md b/workflow-bench/compare-prompt.md index 2b015c2c..2a198062 100644 --- a/workflow-bench/compare-prompt.md +++ b/workflow-bench/compare-prompt.md @@ -1,6 +1,6 @@ You compare two code-review processes, A and B, on one real chunk of work. Each process reviewed the same chunk three times, independently: runs A1–A3 and B1–B3. Rule whether B reviews at least as well as A, and whether A reviews at least as well as B. -Everything is under `{dir}`; read nothing outside it: +Everything is under `{dir}`; don't read anything outside it: - `truth-issues.md`: what the chunk's real review found and fixed, one row per issue. - `truth.diff`: the real review's fixes. diff --git a/workflow-bench/run-prompt.md b/workflow-bench/run-prompt.md index a482232f..1fbab8db 100644 --- a/workflow-bench/run-prompt.md +++ b/workflow-bench/run-prompt.md @@ -9,7 +9,7 @@ Report: write it to `{report}`. - `VERSION_DIR/skills/larv-review/SKILL.md` is larv-review. Do not invoke the installed `larv-review` skill. - Wherever a text cites `~/.claude/<path>`, read `VERSION_DIR/<path>` instead. `VERSION_DIR/CLAUDE.md` replaces `~/.claude/CLAUDE.md`, which you already have loaded: where the two differ, VERSION_DIR's wins. - Launch every reviewer named `<name>` under `~/.claude/agents/` as a `general-purpose` agent whose prompt opens with the body of `VERSION_DIR/agents/<name>.md` (frontmatter dropped), then the task. A reviewer the process names that has no file there gets the process's own description of it as its prompt. -- `/security-review`: launch a `general-purpose` agent that invokes the Skill tool's `security-review`, edits nothing, and replies with the skill's report, or that the skill is unavailable. Where that skill is unavailable, emulate it with a `general-purpose` agent, told to review the branch diff for exploitable vulnerabilities and report only those at ≥0.8 confidence. +- `/security-review`: launch a `general-purpose` agent that invokes the Skill tool's `security-review`, doesn't edit anything, and replies with the skill's report, or that the skill is unavailable. Where that skill is unavailable, emulate it with a `general-purpose` agent, told to review the branch diff for exploitable vulnerabilities and report only those at ≥0.8 confidence. ## Bench rules @@ -18,7 +18,7 @@ Report: write it to `{report}`. - Run every git command through `python3 {review_git} <subcommand> <args>`, never bare `git`: that wrapper is the only shell command allowed. It runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit`. Where the process asks for another git command, do without it and list it under Ambiguities. Run no other code or test suite. Where the process asks for a run, such as the stability pass's mutation test, review by reading and list the skipped run under Ambiguities. - Skip the comprehension check; say so in the report. - No human is reachable. Where the process names a no-human branch, take it; where it names none, take your recommendation and list the question in the report. -- Commit each round's fixes on `chunk` with `python3 {review_git} commit -m <message>`, messages prefixed `{case} - review: `. Touch nothing outside this repository except the report. +- Commit each round's fixes on `chunk` with `python3 {review_git} commit -m <message>`, messages prefixed `{case} - review: `. Don't touch anything outside this repository except the report. ## Report -- 2.52.0 From 9a260d22c04721bde8f842db331a86e8bf8d0ec1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 12 Nov 2026 20:39:25 +0100 Subject: [PATCH 6/7] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20test=20the?= =?UTF-8?q?=20larv-review=20command=20table's=20stale-fetch=20refusals,=20?= =?UTF-8?q?--preloaded=20parsing=20and=20usage=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/larv_review/test_larv_review.py | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 09d7ec06..f6f70e5c 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -779,6 +779,41 @@ class LarvReviewTool(unittest.TestCase): self.assertFalse((self.checkout.parent / ".local" / "state" / "larv-review" / "proj" / "scoring").exists()) self.assertEqual(len(self.git("worktree", "list").splitlines()), 1) + VALUES = {"AGENTS.md": "## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n"} + + def test_prepare_scoring_puts_the_preloaded_text_it_is_given_in_the_seats_prompts(self): + self.commit("Values", self.VALUES) + prepared = self.run_tool("prepare-scoring", "--preloaded", "the files the harness loaded") + self.assertEqual(prepared.returncode, 0, prepared.stderr) + prompts = [path.read_text() for path in (self.checkout.parent / ".local" / "state" / "larv-review").rglob("*.md") if "scoring" in path.parts] + self.assertTrue(any("the files the harness loaded" in prompt for prompt in prompts), prepared.stdout) + + def test_prepare_scoring_refuses_a_preloaded_flag_without_its_text_and_any_other_arguments(self): + self.commit("Values", self.VALUES) + for given in (["--preloaded"], ["text"], ["text", "--preloaded"], ["--preloaded", "text", "more"], ["--other", "text"]): + with self.subTest(given=given): + ran = self.run_tool("prepare-scoring", *given) + self.assertEqual((ran.returncode, ran.stdout), (1, "")) + self.assertTrue(ran.stderr.startswith("unknown arguments prepare-scoring"), ran.stderr) + + def test_record_scoring_without_a_scores_file_and_an_empty_item_ID_print_the_usage_line(self): + bare = self.run_tool("record-scoring") + self.assertEqual(bare.returncode, 1) + self.assertTrue(bare.stderr.startswith("unknown arguments record-scoring; usage: larv-review "), bare.stderr) + empty = self.run_tool("needs-scoring-run", "") + self.assertEqual(empty.returncode, 1) + self.assertIn("takes item IDs", empty.stderr) + + def test_the_commands_that_judge_a_branch_refuse_a_failed_fetch_instead_of_reading_origin_as_last_fetched(self): + self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git")) + seats = self.seats_file(f"PR #2 at {self.start}\n") + for given in (["ruling-base"], ["needs-scoring-run"], ["needs-scoring-run", "1"], ["scoring-run-owed"], ["record-scoring", seats], ["record-scoring", seats, "1"]): + with self.subTest(given=given): + ran = self.run_tool(*given) + self.assertEqual(ran.returncode, 1) + self.assertNotIn("reading origin as last fetched", ran.stderr) + self.assertEqual(ran.stdout, "") + def test_reports_a_plan_it_cannot_read_yet_keeps_the_run(self): # This checkout has no README.md beside its todo.md. ran = self.record_sevens() -- 2.52.0 From 0a26bcb80784f4d5a402ba50fa05e5cb9b09e8a5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 12 Nov 2026 20:51:32 +0100 Subject: [PATCH 7/7] Record the comprehension check: PR #511 paired ruling is better --- docs/comprehension-history.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 540dbbf7..c4a26120 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -3630,3 +3630,30 @@ Inherited architect, would restructure first: - Shape: `bin/larv_review/main.py:173` `main`: a 145-line docstring doubles as help beside an elif chain - Shape: `bin/rule_hook/rules.py:14` `RuleName`: a Literal that repeats the keys of `RULES`, as `ReviewedPass` repeats `PASS_AGENTS` - Self-sufficiency: `bin/loop_claude/loop/chunk_start.py:83` `fetched_plan`: a comment cites a plan item that is deleted when finished + +## 2026-11-12T19:51:29Z, PR #511 at 9a260d2, against 913accf + +Ruling: better + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | better | better | better | better | better | +| Inherited architect | better | better | better | same | better | + +Mid A, decided by: + +- Navigation, Shape, Overall: `bin/review_replay/main.py:75` `main`: the file is now CLI only, and each job sits in its own module under a docstring stating it; at 913accf one 359-line file mixed them +- Locality, Shape, Overall: `bin/larv_review/main.py:211` `COMMANDS`: one table row per subcommand feeds dispatch, usage and `--help`, where 913accf had a 12-arm if/elif chain and a hand-written usage string +- Locality, Navigation: `bin/transcript_archive/outcomes.py:63` `spent_block`: the Spent block's writer now sits beside its marker and kinds, not in another package +- Locality: `bin/claude_code/entries.py:148` `messages`: one reader groups assistant turns by message, where three callers each deduplicated by hand with different keep-first and keep-last rules +- Shape, Self-sufficiency: `bin/model_routing/prices.py:23` `PRICES`: the docstring states both uses of the price list and the comment says prices are archived as in force +- Self-sufficiency, Locality: `bin/larv_review/scoring_setup.py:52` `score_bullets`: picks anchors and dimensions by how each bullet opens, and the docstring says so; 913accf took them by position and count +- Shape: `bin/review_replay/omit_comparison.py:12` `compared`: returns the report and leaves printing to `main`, where 913accf printed, returned an exit code and needed a cast + +Inherited architect, decided by: + +- Navigation, Shape, Overall: `bin/review_replay/replay.py:1` `replay`: a failed clone or bad match leads to one file whose docstring names that job; `main.py` shrank from 359 to 114 lines of wiring +- Locality, Shape: `bin/claude_code/entries.py:148` `messages`: one reader groups a message's entries, and the keep-first versus keep-last trap the old comment warned about is gone +- Navigation, Locality: `bin/larv_review/main.py:211` `COMMANDS`: each subcommand's spelling, argument check and action sit in one row that usage and `--help` are built from +- Locality: `bin/transcript_archive/outcomes.py:63` `spent_block`: the writer sits beside the marker and parser, and the loop no longer depends on the measuring package for an archive format +- Shape: `bin/model_routing/prices.py:1` `prices`: the price list moved out of `routing_figures` once it gained a second reader, and its docstring states both uses -- 2.52.0