diff --git a/.gitignore b/.gitignore index ede04b76..57d40f6e 100644 --- a/.gitignore +++ b/.gitignore @@ -96,10 +96,13 @@ !bin/rule_hook/ !bin/rule_hook/*.py !bin/run-heavy +!bin/run-tests !bin/run_heavy/ !bin/run_heavy/*.py !bin/run_heavy/path_entry/ !bin/run_heavy/path_entry/docker +!bin/run_tests/ +!bin/run_tests/*.py !bin/rung_replay/ !bin/rung_replay/*.py !bin/score-outcomes @@ -117,6 +120,9 @@ !bin/todo_item/*.py !bin/transcript_archive/ !bin/transcript_archive/*.py +!bin/wait-for +!bin/wait_for/ +!bin/wait_for/*.py !docs/ !docs/*.md !judge-field-trials/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 26ba4e83..2abde8d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `larv-review prepare-scoring` makes a scoring run's worktree and writes each seat's prompt; `record-scoring` removes both once it has recorded the run. +- `deploy-release` moves a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes, and then says to pick the model again. +- `chunk-pr merge` waits for the pull request's checks itself, allowing a minute for them to report, and no longer takes `--gate-passed`. `wait-for []` waits for a line in a background job's log or report. +- `chunk-pr sync` merges origin's default branch into the chunk's branch, unless the branch already holds it, then runs the rank check on `todo.md`. +- `chunk-pr ready ` sets the pull request's final title as it marks the pull request ready. +- `bin/run-tests` runs this repo's test suite as README.md β†’ Test says, prints each failing test with its error and pytest's summary line, and saves the whole log to a file whose path it prints. - `command-patterns [<version>] --calls <file>` saves each Bash call of the release's chunks as a JSON line, with its chunk, pattern, seconds, sizes and text. - `todo-item show <ID>` prints an item's table row and detail from `todo.md`. - A reviewer under `agents/` can start without `CLAUDE.md`: `omitClaudeMd: true` in its frontmatter drops the file, a `SubagentStart` hook hands it the "Shared goal", "Prose" and "Vocabulary" sections, and `larv-review reviewer-header` names the project's principles file. `review-replay <pass> <model> --omit-claude-md` tests whether a pass's reviewer finds as much without it; principles-auditor is the first to pass. diff --git a/CLAUDE.md b/CLAUDE.md index af7e65f8..68f99eaa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,7 +66,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`. - Tear down test containers after a run. - Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands. -- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run it in the background, since the wait can outlast the Bash tool's timeout. +- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run the command in the background, since run-heavy's wait can outlast the Bash tool's timeout; `~/.claude/bin/wait-for <file> [<pattern>]` waits for a line in a log the command writes. - Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits: 1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model. 2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher. diff --git a/README.md b/README.md index e1bfcc66..f38692cb 100644 --- a/README.md +++ b/README.md @@ -97,12 +97,12 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. -- `chunk-pr open|ready|merge|clean` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps. +- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps. - `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts. - `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys. - `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says. - `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. -- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` β†’ `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. +- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` β†’ `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. - `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. - `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how. - `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; `~/.claude/.env` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one. @@ -113,11 +113,13 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `review-replay <pass> <model>` 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, finds every πŸ”΄ and 🟑 the project's rung finds again; `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 twice as archived and once without the instruction files, and prints each finding the last replay missed that both of the others found. 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 <command>` 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 [<pytest args>...]` runs this repo's test suite, as Test says. - `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by, and code health's two counter-signals per chunk, misread findings and later fixes; `score-outcomes --help` states the report. - `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter. - `statusline.py` renders Claude Code's status line; `settings.json` β†’ `statusLine` runs it. - `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. - `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file. `todo-item show <ID>` prints an item's row and detail. `todo-item --help` states the flags. +- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it. `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool. @@ -145,7 +147,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t ## Test -Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`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'`. +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`. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index f39efc9c..5d0c1e53 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -1,8 +1,9 @@ -"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch. +"""Open the chunk's pull request as a draft, bring its branch level with origin's default branch, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch. usage: chunk-pr open <title> [<body>] - chunk-pr ready - chunk-pr merge --gate-passed + chunk-pr sync + chunk-pr ready [<title>] + chunk-pr merge chunk-pr clean Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open @@ -12,15 +13,24 @@ open pushes the branch, setting its upstream, and opens a draft pull request default branch. <title> 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. +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 + the check fails. On a merge conflict it names the conflicted files and leaves the merge in + progress, to resolve and commit. On origin's default branch it refuses and doesn't fetch anything. ready marks the pull request ready for review. On Gitea a draft is a pull request whose title - starts with `WIP: `, so there it drops that prefix. -merge merges the pull request, and only while its head is still the commit checked out, so a - push after the gate is never merged. It takes the first method the repository allows of: - a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash. - GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the - merge gate passed on that commit; without it, chunk-pr refuses. It also refuses where - `larv-review scoring-run-owed` exits 1, because the chunk owes a scoring run it has not - recorded; no flag waives that. + starts with `WIP: `, so there it drops that prefix. Given <title>, one line, it sets that + as the pull request's title first; where that fails, the pull request stays a draft. +merge waits for the pull request's checks, and those origin's default branch requires, to pass + on the head, then merges the pull request, and only while its head is still the commit + checked out, so a push after the gate is never merged. Where no check reports within a + minute, it takes the pull request as having none. It refuses where a check fails, or, on + Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them + until they end. Run it in the background. + It takes the first merge method the repository allows of: a merge commit, fast-forward + only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the + merge commit, the rebase and the squash. It also refuses where `larv-review + scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded. clean acts once the forge reports the branch's pull request merged at the commit checked out, 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 @@ -36,15 +46,18 @@ import json import os import pathlib import sys +import time import typing +from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner from failure import Failure from chunk_preflight.gathered import Forge from chunk_preflight.choices import forge_of -from deploy_release.forge import gitea, merged_pull, open_pull, Run, runner BIN = pathlib.Path(__file__).resolve().parents[1] -USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean" +# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one. +NO_CHECKS_SECONDS = 60 +USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean" # Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them. METHODS: dict[Forge, tuple[tuple[str, str], ...]] = { @@ -68,21 +81,23 @@ 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.""" match argv: - case ["open", title, *body] if len(body) <= 1: - if not title.strip() or "\n" in title: - return Failure("give a title of one line") - return opened(title, body[0] if body else "", run) - case ["ready"]: - return marked_ready(run) - case ["merge", "--gate-passed"]: - return merged(run) + 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) + case ["sync"]: + return synced(run) + case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title): + return Failure("give a title of one line") if title and not one_line(title[0]) else marked_ready(run, title[0] if title else None) case ["merge"]: - return Failure("merge only once the gate has passed, and say so with --gate-passed") + return merged(run) case ["clean"]: return cleaned(run) return Failure(USAGE) +def one_line(title: str) -> bool: + return bool(title.strip()) and "\n" not in title + + def answers(run: Run, *commands: list[str]) -> list[str] | Failure: """What each git command printed, stripped, or the first Failure.""" answered = [run(["git", *args]) for args in commands] @@ -147,16 +162,60 @@ def opened(title: str, body: str, run: Run) -> str | Failure: return number if isinstance(number, Failure) else f"Opened draft pull request #{number}." -def marked_ready(run: Run) -> str | Failure: +def synced(run: Run) -> str | Failure: + found = checkout(run) + if isinstance(found, Failure): + return found + _, branch, _ = found + base = default_branch(run) + if isinstance(base, Failure): + return base + if branch == base: + return Failure(f"{branch} is origin's default branch; sync the chunk's branch") + fetched = run(["git", "fetch", "--quiet", "origin"]) + if isinstance(fetched, Failure): + return fetched + behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"]) + if isinstance(behind, Failure): + return behind + count, root = behind + if count == "0": + done = f"{branch} already holds origin/{base}." + else: + merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"]) + if isinstance(merged, Failure): + conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"]) + if isinstance(conflicted, Failure) or not conflicted[0]: + return merged + return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit") + done = f"Merged origin/{base} into {branch}." + todo = pathlib.Path(root, "todo.md") + if not todo.is_file(): + return done + ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)]) + if isinstance(ranked, Failure): + return Failure(f"{done.removesuffix('.')}, but rank_todo.py --check todo.md failed: {ranked.reason}") + return f"{done}\nrank_todo.py --check todo.md passed." + + +def marked_ready(run: Run, title: str | None) -> str | Failure: found = pull(run) if isinstance(found, Failure): return found forge, number, _ = found - ready = run(["gh", "pr", "ready", number] if forge == "gh" else ["tea", "pulls", "edit", number, "--ready"]) - return ready if isinstance(ready, Failure) else f"Marked pull request #{number} ready." + retitle = ["--title", title] if title is not None else [] + if forge == "gh": + # gh marks a pull request ready only with `gh pr ready`, which takes no title. + titled = run(["gh", "pr", "edit", number, *retitle]) if retitle else "" + ready = titled if isinstance(titled, Failure) else run(["gh", "pr", "ready", number]) + else: + ready = run(["tea", "pulls", "edit", number, *retitle, "--ready"]) + if isinstance(ready, Failure): + return ready + return f"Marked pull request #{number} ready, titled β€œ{title}”." if title is not None else f"Marked pull request #{number} ready." -def merged(run: Run) -> str | Failure: +def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure: found = pull(run) if isinstance(found, Failure): return found @@ -167,6 +226,11 @@ def merged(run: Run) -> str | Failure: method = merge_method(forge, run) if isinstance(method, Failure): return method + base = default_branch(run) + required = base if isinstance(base, Failure) else required_checks(forge, base, run) + checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS) + if isinstance(checked, Failure): + return checked if forge == "gh": done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head]) else: diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index 1dcc022c..d41631d7 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from chunk_pr.main import cleaned, step +from chunk_pr.main import cleaned, merged, step, USAGE from failure import Failure from test_env import isolated_env from deploy_release.forge import Run @@ -21,6 +21,9 @@ GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid, TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"] GH_SETTINGS = ["gh", "repo", "view", "--json", "mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed"] TEA_SETTINGS = ["tea", "api", "repos/{owner}/{repo}"] +GH_CHECKS = ["gh", "pr", "checks", "12", "--watch", "--fail-fast"] +TEA_BRANCH = ["tea", "api", "repos/{owner}/{repo}/branches/main"] +TEA_STATUS = ["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{HEAD}/status"] OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scoring-run-owed"] @@ -33,6 +36,7 @@ class Checkout: self.github = origin == GITHUB self.open = open self.allowed = allowed + self.statuses: list[str] = [] self.ran: list[list[str]] = [] self.answers: dict[tuple[str, ...], str | Failure] = { ("git", "remote", "get-url", "origin"): f"{origin}\n", @@ -53,13 +57,17 @@ class Checkout: return f"12\t{HEAD}\tfalse\n" if self.open else "" if command == TEA_LIST: return json.dumps([{"number": 12, "head": {"ref": "item-7", "label": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else []) + if command == TEA_STATUS: + return self.statuses.pop(0) if self.statuses else json.dumps({"total_count": 1, "state": "success", "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]}) + if command == TEA_BRANCH: + return json.dumps({"enable_status_check": False}) if command in (GH_SETTINGS, TEA_SETTINGS): return json.dumps({setting: True for setting in self.allowed}) return "" def acted(self) -> list[list[str]]: """What it ran beyond reading the checkout, the pull requests and the repository's settings.""" - reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED] + reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS] return [command for command in self.ran if tuple(command) not in self.answers and command not in reads] @@ -87,10 +95,10 @@ class Open(unittest.TestCase): self.assertEqual(checkout.acted(), []) def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self): - for argv in (["open", "Do it\nand more"], ["open", " "], ["open", "Do it", "Body", "More"]): + for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)): with self.subTest(argv): checkout = Checkout(GITHUB, open=False) - self.assertIsInstance(step(argv, checkout), Failure) + self.assertEqual(step(argv, checkout), Failure(refusal)) self.assertEqual(checkout.ran, []) def test_a_failed_listing_after_the_create_is_returned(self): @@ -115,6 +123,29 @@ class Ready(unittest.TestCase): self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.") self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]]) + def test_github_sets_a_given_title_then_marks_it_ready(self): + checkout = Checkout(GITHUB, open=True) + self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled β€œShip it”.") + self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]]) + + def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self): + checkout = Checkout(GITEA, open=True) + self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled β€œShip it”.") + self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]]) + + def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self): + for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)): + with self.subTest(argv=argv): + checkout = Checkout(GITHUB, open=True) + self.assertEqual(step(argv, checkout), Failure(refusal)) + self.assertEqual(checkout.ran, []) + + def test_a_failed_title_edit_on_github_leaves_it_a_draft(self): + checkout = Checkout(GITHUB, open=True) + checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied") + self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied")) + self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran) + def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self): checkout = Checkout(GITHUB, open=False) ready = step(["ready"], checkout) @@ -132,54 +163,195 @@ class Ready(unittest.TestCase): self.assertEqual(checkout.acted(), []) +FETCH = ["git", "fetch", "--quiet", "origin"] +BEHIND = ("git", "rev-list", "--count", "HEAD..origin/main") +MERGE = ["git", "merge", "--quiet", "--no-edit", "origin/main"] +CONFLICTED = ("git", "diff", "--name-only", "--diff-filter=U") +RANK = str(pathlib.Path(__file__).resolve().parents[1] / "rank_todo.py") + + +class Sync(unittest.TestCase): + def checkout(self, behind: int, todo: bool = False) -> Checkout: + """A Checkout behind origin/main by behind commits, at a worktree root holding a todo.md where todo is True.""" + checkout = Checkout(GITEA, open=True) + root = self.enterContext(tempfile.TemporaryDirectory()) + if todo: + pathlib.Path(root, "todo.md").write_text("") + checkout.answers[("git", "rev-parse", "--show-toplevel")] = f"{root}\n" + checkout.answers[BEHIND] = f"{behind}\n" + self.todo = str(pathlib.Path(root, "todo.md")) + return checkout + + def test_a_branch_behind_the_default_branch_merges_it(self): + checkout = self.checkout(behind=3) + self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.") + self.assertEqual(checkout.acted(), [FETCH, MERGE]) + + def test_a_branch_that_holds_the_default_branch_merges_nothing(self): + checkout = self.checkout(behind=0) + self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.") + self.assertEqual(checkout.acted(), [FETCH]) + + def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self): + checkout = self.checkout(behind=1, todo=True) + self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.") + self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]]) + + def test_a_failing_rank_check_fails_naming_what_it_did(self): + checkout = self.checkout(behind=0, todo=True) + checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order") + self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order")) + + def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self): + checkout = self.checkout(behind=2, todo=True) + checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT") + checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n" + self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit")) + self.assertNotIn([RANK, "--check", self.todo], checkout.ran) + self.assertNotIn(["git", "merge", "--abort"], checkout.ran) + + def test_a_merge_failing_without_a_conflict_is_returned(self): + checkout = self.checkout(behind=2) + checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten") + checkout.answers[CONFLICTED] = "" + self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten")) + + def test_on_the_default_branch_it_refuses_and_fetches_nothing(self): + checkout = self.checkout(behind=0) + checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n" + self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch")) + self.assertNotIn(FETCH, checkout.ran) + + def test_a_failed_fetch_is_returned(self): + checkout = self.checkout(behind=0) + checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote") + self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote")) + + class Merge(unittest.TestCase): - def test_without_the_gate_passed_it_refuses_before_anything_runs(self): + def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self): checkout = Checkout(GITHUB, open=True) - self.assertIsInstance(step(["merge"], checkout), Failure) + self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure) self.assertEqual(checkout.ran, []) + def test_an_option_given_as_a_title_runs_nothing(self): + for argv in (["ready", "--help"], ["open", "-h"]): + checkout = Checkout(GITHUB, open=True) + self.assertEqual(step(argv, checkout), Failure(USAGE)) + self.assertEqual(checkout.ran, []) + + def test_github_waits_for_the_checks_before_merging(self): + checkout = Checkout(GITHUB, open=True) + self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) + + def test_a_failed_check_on_github_leaves_it_unmerged(self): + checkout = Checkout(GITHUB, open=True) + checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail") + self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail")) + self.assertEqual(checkout.acted(), []) + + def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self): + checkout = Checkout(GITHUB, open=True) + checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch") + slept: list[float] = [] + self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(sum(slept), 60) + self.assertEqual(checkout.ran.count(GH_CHECKS), 7) + + def test_gitea_waits_a_minute_for_a_status_before_taking_none_as_passed_where_main_requires_none(self): + checkout = Checkout(GITEA, open=True) + checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7 + slept: list[float] = [] + self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(sum(slept), 60) + + def protected(self, *reads: list[tuple[str, str]]) -> Checkout: + """A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn.""" + checkout = Checkout(GITEA, open=True) + checkout.answers[tuple(TEA_BRANCH)] = json.dumps({"enable_status_check": True, "status_check_contexts": ["CI / tests*"]}) + def combined(read: list[tuple[str, str]]) -> str: + states = {state for _, state in read} + state = "failure" if "failure" in states else "pending" if "pending" in states or not read else "success" + return json.dumps({"total_count": len(read), "state": state, "statuses": [{"context": context, "status": status} for context, status in read]}) + checkout.statuses = [combined(read) for read in reads] + return checkout + + def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self): + checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")]) + slept: list[float] = [] + self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(len(slept), 2) + self.assertEqual(checkout.ran.count(TEA_STATUS), 3) + + def test_a_failed_check_on_gitea_leaves_it_unmerged(self): + checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")]) + self.assertIsInstance(merged(checkout, lambda _: None), Failure) + self.assertEqual(checkout.acted(), []) + + def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self): + checkout = Checkout(GITEA, open=True) + checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500") + self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500")) + self.assertNotIn(TEA_STATUS, checkout.ran) + self.assertEqual(checkout.acted(), []) + + def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self): + checkout = Checkout(GITEA, open=True) + checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref") + self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref")) + self.assertNotIn(TEA_STATUS, checkout.ran) + self.assertEqual(checkout.acted(), []) + + def test_gitea_checks_that_never_pass_leave_it_unmerged(self): + checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000) + failed = merged(checkout, lambda _: None) + self.assertIsInstance(failed, Failure) + self.assertIn("gave up on pull request 12", failed.reason) + self.assertEqual(checkout.acted(), []) + def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self): for origin in (GITHUB, GITEA): with self.subTest(origin=origin): checkout = Checkout(origin, open=True) checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs") - self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")) + self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")) self.assertEqual(checkout.acted(), []) def test_github_merges_with_a_merge_commit_pinned_to_the_head(self): checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed")) - self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_github_without_merge_commits_rebases(self): checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed")) - step(["merge", "--gate-passed"], checkout) + step(["merge"], checkout) self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]]) def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self): checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge")) - self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (fast-forward-only).") + self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).") self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]]) def test_a_repository_allowing_no_known_method_is_refused_unmerged(self): checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",)) - self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure) + self.assertIsInstance(step(["merge"], checkout), Failure) self.assertEqual(checkout.acted(), []) def test_a_forge_failure_is_returned(self): checkout = Checkout(GITHUB, open=True) checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved") - self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("gh pr merge: head moved")) + self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved")) checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(GH_SETTINGS)] = "not json" - self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure) + self.assertIsInstance(step(["merge"], checkout), Failure) def test_a_failed_settings_read_is_returned_unmerged(self): for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)): with self.subTest(origin): checkout = Checkout(origin, open=True) checkout.answers[tuple(settings)] = Failure("settings: denied") - self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("settings: denied")) + self.assertEqual(step(["merge"], checkout), Failure("settings: denied")) self.assertEqual(checkout.acted(), []) diff --git a/bin/deploy_release/deploy.py b/bin/deploy_release/deploy.py index f6fdbcc8..e1d96342 100644 --- a/bin/deploy_release/deploy.py +++ b/bin/deploy_release/deploy.py @@ -35,8 +35,13 @@ def deploy(checkout: str) -> str | 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. - if changed.split(): - restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout) + # 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): + return tracked + set_aside = sorted({*changed.split(), *tracked.split()} if settings_changed else set(changed.split())) + if set_aside: + restored = git("checkout", "--quiet", "HEAD", "--", *set_aside, cwd=checkout) if isinstance(restored, Failure): return restored moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout) diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 7aa44caa..047a5ae1 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -98,15 +98,20 @@ def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure: return Failure(f"tea api answered branch {base} in a shape that can't be read: {str(branch)[:200]}") -def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: - """None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. +def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None: + """None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. On Gitea it also waits for a passed check to match each of required: a check CI has yet to queue is no status at all. """ if forge == "gh": - watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"]) - if isinstance(watched, Failure) and "no checks reported" not in watched.reason: - return watched + for waited in range(0, settle + 1, POLL_SECONDS): + watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"]) + if not isinstance(watched, Failure): + return None + if "no checks reported" not in watched.reason: + return watched + if waited < settle: + sleep(POLL_SECONDS) return None for _ in range(WAIT_SECONDS // POLL_SECONDS + 1): status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") @@ -121,7 +126,7 @@ def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: return Failure(f"a check on pull request {number} ended in {state}") # Gitea matches a required context as a glob, and reads a commit with no status as pending, with total_count 0. missing = sorted(pattern for pattern in required if not fnmatch.filter(passed, pattern)) - if (count == 0 or state == "success") and not missing: + if (count == 0 and _ * POLL_SECONDS >= settle or state == "success") and not missing: return None if _ < WAIT_SECONDS // POLL_SECONDS: sleep(POLL_SECONDS) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 4c12e95c..e91321c3 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -122,6 +122,20 @@ class DeployRelease(unittest.TestCase): self.assertEqual(self.head(), "v0.3.0") self.assertIn('"model"', (self.target / "settings.json").read_text(), "a release that leaves settings.json as it was keeps the pick") + def test_moves_a_settings_json_that_differs_only_by_a_model_pick_and_key_order_where_the_release_changes_it(self): + self.release("0.2.0", "- Second.\n", '{\n "permissions": {},\n "theme": "dark"\n}\n') + self.git(self.target, "fetch", "-q", "--tags", "origin") + self.git(self.target, "checkout", "-q", "--detach", "v0.2.0") + (self.target / ".gitattributes").write_text("/settings.json filter=settings\n") + self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {TOOL.parent / 'settings_filter.py'}") + (self.target / "settings.json").write_text('{\n "theme": "dark",\n "model": "opus",\n "permissions": {}\n}\n') + self.release("0.3.0", "- Third.\n", '{\n "permissions": {},\n "theme": "light"\n}\n') + ran = self.deploy() + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertEqual(self.head(), "v0.3.0") + self.assertEqual((self.target / "settings.json").read_text(), '{\n "permissions": {},\n "theme": "light"\n}\n') + self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout) + def test_asks_for_the_model_again_where_the_release_changes_settings_json(self): self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n') ran = self.deploy() diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index 45511db4..8b6b5c66 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -11,6 +11,7 @@ from failure import Failure from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile from larv_review.scoring import floor_step, means, under_floor from release_plan import plan_file +from larv_review.scoring_setup import removed_setup from records.file_writes import replace_file @@ -61,7 +62,9 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F print(floor_step(scoring.means, plan, ids)) if unrecorded := append(given.read, scoring_entry(named.title, scoring)): return unrecorded - return rerank() + reranked = rerank() + removed = removed_setup(checkout) + return reranked or (removed and Failure(f"recorded the run, but {removed.reason}")) def rerank() -> Failure | None: diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index b0347500..c523b69f 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; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. +"""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 [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun] | reviewer-context +usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | prepare-scoring [--preloaded <text>] | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun] | reviewer-context 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, @@ -82,6 +82,17 @@ nothing and prints `Split:`, saying to add the maintainability senior's and Juni 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. +prepare-scoring sets up a scoring run in the chunk's review folder: a detached worktree of the +checkout's HEAD, which the seats read, and one prompt file per seat beside it, as +skills/comprehension-panel/seat-prompts.md builds them. It prints the worktree's path and each +prompt's. It takes {{language}}, {{kind}}, {{domain}}, {{domain docs}} and {{3am question}} from the +checkout's AGENTS.md β†’ "Scoring run". claude-config keeps no AGENTS.md, so there it takes them from +seat-prompts.md β†’ "claude-config's values". It fills the other placeholders from the worktree and +the panel's SKILL.md. --preloaded replaces {{preloaded}}, which by default names each CLAUDE.md the main checkout's claudeMdExcludes doesn't exclude, its +imports and each rule file without `paths:` that Claude Code loads into a seat. Where any one of +the five values is missing, it exits 1 and doesn't write anything. Where a setup that +record-scoring never removed is still there, it removes it first and says so. + record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no `, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores and their means, rounded half up to two decimals, prints the means and, when a mean is under the @@ -90,7 +101,8 @@ says to file a floor item, one whose tagline holds `comprehension floor`, aimed four dimensions. Where the checkout's todo.md holds such an item other than those given, it says to refresh that item instead. Then it ranks the checkout's todo.md as rank_todo.py does, since the overall sets the weight of code health, the goal every project shares, and exits 1 where -rank_todo.py would, with the run recorded. +rank_todo.py would, with the run recorded. Last, it removes what prepare-scoring set up, so a +second run of one head runs prepare-scoring again. record-ruling and record-scoring append each entry to the history, created when missing, under a heading of the current UTC time and the seats file's first line. Each commit that line names must be @@ -151,10 +163,11 @@ from larv_review.agreement import MIN_PAIRS from larv_review.owed import owed_scoring_run from review_rules.review_passes import PASSES, REVIEWERS from larv_review.plan import plan_reasons +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 [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun] | reviewer-context" +USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | prepare-scoring [--preloaded <text>] | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun] | reviewer-context" def main(argv: list[str]) -> int: @@ -174,6 +187,8 @@ def main(argv: list[str]) -> int: 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: @@ -218,6 +233,11 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o return command(branch) +def prepared_scoring(preloaded: str | None) -> Failure | None: + worktree = top() + return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, preloaded)) + + def make_review_folder() -> Failure | None: worktree = top() if isinstance(worktree, Failure): diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py new file mode 100644 index 00000000..efaefc69 --- /dev/null +++ b/bin/larv_review/scoring_setup.py @@ -0,0 +1,226 @@ +"""Set up a scoring run: the worktree its seats read and each seat's prompt, filled from skills/comprehension-panel/seat-prompts.md.""" +import json +import pathlib +import re +import shutil + +from failure import Failure +from records.markdown_text import FENCE, listed +from git_cli.git_repo import git +from review_rules.review_folder import made_review_folder, review_folder + +CLAUDE_MD = "CLAUDE.md" +PANEL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel" +# The file name of each seat's prompt, its label in seat-prompts.md β†’ "Backgrounds", and the heading of its report there. +SEATS = ( + ("junior-a", "Junior A", "Report: Junior A, Mid A and the maintainability senior"), + ("mid-a", "Mid A", "Report: Junior A, Mid A and the maintainability senior"), + ("maintainability-senior", "Senior, maintainability", "Report: Junior A, Mid A and the maintainability senior"), + ("inherited-architect", "Architect, inherited", "Report: the inherited architect"), +) +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)" +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]]: + """Each run of `- ` bullets in lines, each bullet joined onto one line with its indented continuation lines.""" + groups: list[list[str]] = [] + inside = False + for line in lines: + if line.startswith("- "): + if not inside: + groups.append([]) + groups[-1].append(line.rstrip()) + inside = True + elif inside and line.startswith(" ") and line.strip(): + groups[-1][-1] += " " + line.strip() + else: + inside = False + return groups + + +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] + + +def project_values(text: str, source: str) -> dict[str, str] | Failure: + """Each value seat-prompts.md fills from the project, from the section of text, read from source, headed `Scoring run` or `<name>'s values`.""" + lines = section(text, r"(\d+\.\s+)?Scoring run|.+'s values") + if lines is None: + return Failure(f"{source} has no \"Scoring run\" section to fill the seats' prompts from; add one with {listed([f'{{{name}}}' for name in VALUE_NAMES], 'and')}") + values = {} + for bullet in (line for group in bullets(lines) for line in group): + key, colon, value = bullet[2:].partition(":") + name = key.strip(" `*{}").lower() + if colon and name in VALUE_NAMES: + value = value.strip(" *") + values[name] = value[:-1] if value.endswith(".") and not value.endswith("..") else value + if missing := [name for name in VALUE_NAMES if name not in values]: + return Failure(f"{source} β†’ \"Scoring run\" gives no {listed([f'{{{name}}}' for name in missing], 'or')}; add them as seat-prompts.md lists them") + return {name: values[name] for name in VALUE_NAMES} + + +def file_globs(paths: list[str]) -> str: + """Every tracked file of paths a seat reads, as one glob per top-level folder and each top-level file, with the test files the globs leave out.""" + read = [path for path in paths if path not in FORBIDDEN_FILES and not TEST_FILE.search(path)] + folders = sorted({path.split("/")[0] for path in read if "/" in path}) + tested = {path.split("/")[0] for path in paths if "/" in path and TEST_FILE.search(path)} + globs = [f"`{folder}/**`" + (" except test files" if folder in tested else "") for folder in folders] + return listed(globs + sorted(f"`{path}`" for path in read if "/" not in path), "and") + (f", {TEST_FILES}" if tested & set(folders) else "") + + +def preloaded_files(main: pathlib.Path, home: pathlib.Path) -> str: + """The files Claude Code loads into a seat started in main before its first tool call: each CLAUDE.md, the files it imports, and each rule file without `paths:`, leaving out those `claudeMdExcludes` names.""" + excludes = claude_md_excludes(main, home) + found = [] + + def kept(path: pathlib.Path) -> bool: + return not any(path.full_match(pattern) for pattern in excludes) + + for shown, claude_md, rules in (("~/.claude/", home / ".claude" / CLAUDE_MD, home / ".claude" / "rules"), ("", main / CLAUDE_MD, main / ".claude" / "rules")): + if claude_md.is_file() and kept(claude_md): + found.append(f"`{shown}{CLAUDE_MD}`") + found += [f"`{shown}{name}`, which it imports" for name in re.findall(r"^@(\S+)", claude_md.read_text(), re.M)] + found += [f"`{shown}{rule.relative_to(claude_md.parent)}`" for rule in sorted(rules.glob("*.md")) if kept(rule) and not re.search(r"^paths:", rule.read_text(), re.M)] + return listed(found, "and") if found else "none" + + +def claude_md_excludes(main: pathlib.Path, home: pathlib.Path) -> list[str]: + """The `claudeMdExcludes` globs of the user's settings and main's project and local settings, merged as Claude Code merges them across layers. + + Managed settings are left out, since they may come from the claude.ai console or an MDM policy, where no file shows them.""" + globs = [] + for path in (home / ".claude" / "settings.json", main / ".claude" / "settings.json", main / ".claude" / "settings.local.json"): + try: + settings = json.loads(path.read_text()) + except (OSError, ValueError): + continue + excludes = settings.get("claudeMdExcludes") if isinstance(settings, dict) else None + globs += [glob for glob in excludes if isinstance(glob, str)] if isinstance(excludes, list) else [] + return globs + + +def prompt_parts() -> dict[str, str] | Failure: + """seat-prompts.md's opening, shared brief and each report as their fenced text, and each seat's background, keyed by heading or label.""" + path = PANEL / "seat-prompts.md" + try: + text = path.read_text() + except OSError as failure: + return Failure(f"cannot read {path}: {failure}") + parts = {} + for title in ("Opening", "Shared brief", *{report for _, _, report in SEATS}): + lines = section(text, re.escape(title)) or [] + fences = [at for at, line in enumerate(lines) if FENCE.match(line)] + if len(fences) < 2: + return Failure(f"{path} β†’ \"{title}\" holds no fenced prompt text") + parts[title] = "\n".join(lines[fences[0] + 1:fences[1]]) + for line in (line for group in bullets(section(text, "Backgrounds") or []) for line in group): + label, _, background = line[2:].partition(": ") + parts[label] = background.strip("`") + if missing := [label for _, label, _ in SEATS if label not in parts]: + return Failure(f"{path} β†’ \"Backgrounds\" names no {listed(missing, 'or')}") + return parts + + +def scoring_folder(worktree: str, home: pathlib.Path) -> pathlib.Path: + return pathlib.Path(review_folder(str(home), worktree)) / "scoring" + + +def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure: + """Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it.""" + home = pathlib.Path.home() + folder = scoring_folder(worktree, home) + # A setup record-scoring never removed, as where the seats failed, would otherwise block every later run. + replaced = folder.exists() + if replaced and isinstance(removed := removed_setup(worktree), Failure): + return removed + # Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md. + source = pathlib.Path(worktree) / "AGENTS.md" + if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file(): + source = own + values = project_values(source.read_text() if source.is_file() else "", source.name) + if isinstance(values, Failure): + return values + parts = prompt_parts() + if isinstance(parts, Failure): + return parts + score = score_bullets((PANEL / "SKILL.md").read_text()) + if isinstance(score, Failure): + return score + listing = git("worktree", "list", "--porcelain", cwd=worktree) + branch = git("symbolic-ref", "--short", "-q", "HEAD", cwd=worktree) + head = git("rev-parse", "--short", "HEAD", cwd=worktree) + if isinstance(listing, Failure): + return listing + if isinstance(head, Failure): + return head + main = listing.splitlines()[0].removeprefix("worktree ") + made = made_review_folder(worktree) + if isinstance(made, Failure): + return made + checkout = folder / "checkout" + # The seats score the chunk's head, which holds origin's default branch since larv-review Β§4 step 1, as larv-review β†’ "Scoring run" says. + added = git("worktree", "add", "--quiet", "--detach", str(checkout), "HEAD", cwd=worktree) + tracked = added if isinstance(added, Failure) else git("ls-files", cwd=str(checkout)) + if isinstance(tracked, Failure): + shutil.rmtree(folder, ignore_errors=True) + return tracked + filled = { + **values, + "checkout": str(checkout), + "branch": head.strip() if isinstance(branch, Failure) else branch.strip(), + "main": main, + "forbidden": FORBIDDEN, + "git": f"`git -C {checkout} ls-files`", + "files": file_globs(tracked.splitlines()), + "preloaded": preloaded if preloaded is not None else preloaded_files(pathlib.Path(main), home), + "anchors": "\n".join(score[0]), + "dimensions": "\n".join(score[1]), + } + placeholder = re.compile(r"\{(" + "|".join(re.escape(name) for name in filled) + r")\}") + written = [] + for name, label, report in SEATS: + prompt = "\n\n".join((parts["Opening"], parts[label], parts["Shared brief"], parts[report])) + path = folder / f"{name}.md" + path.write_text(placeholder.sub(lambda found: filled[found.group(1)], prompt) + "\n") + written.append(str(path)) + before = f"Removed the scoring run set up before in {folder}.\n" if replaced else "" + return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts:\n" + "\n".join(written) + + +def removed_setup(worktree: str) -> Failure | None: + """Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist.""" + folder = scoring_folder(worktree, pathlib.Path.home()) + if not folder.exists(): + return None + if (folder / "checkout").exists() and isinstance(removed := git("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure): + return Failure(f"could not remove the scoring worktree {folder / 'checkout'}: {removed.reason}") + shutil.rmtree(folder, ignore_errors=True) + return None diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 13120f32..3c188c20 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -768,6 +768,17 @@ class LarvReviewTool(unittest.TestCase): seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect")) return self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1") + def test_record_scoring_removes_the_worktree_and_prompts_prepare_scoring_made(self): + self.commit("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"}) + prepared = self.run_tool("prepare-scoring") + self.assertEqual(prepared.returncode, 0, prepared.stderr) + self.assertEqual(len(self.git("worktree", "list").splitlines()), 2) + self.plan() + ran = self.record_sevens() + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertFalse((self.checkout.parent / ".local" / "state" / "larv-review" / "proj" / "scoring").exists()) + self.assertEqual(len(self.git("worktree", "list").splitlines()), 1) + 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() diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py new file mode 100644 index 00000000..2e2311c3 --- /dev/null +++ b/bin/larv_review/test_scoring_setup.py @@ -0,0 +1,197 @@ +from unittest import mock +import os +import pathlib +import re +import subprocess +import sys +import tempfile +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 failure import Failure +from test_env import isolated_env + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review" +SKILL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel" / "SKILL.md" +VALUES = {"language": "Python", "kind": "a CLI", "domain": "parsing", "domain docs": "the spec", "3am question": "the parse hangs"} + + +class ScoreBullets(unittest.TestCase): + def test_gives_the_six_anchors_and_four_dimensions_unbolded_each_on_one_line(self): + anchors, dimensions = score_bullets(SKILL.read_text()) + self.assertEqual(len(anchors), 6) + self.assertEqual(anchors[0], "- 1 β€” Spaghetti. No boundary holds. Finding where a behaviour lives is grep archaeology; changing it safely is guesswork, and the reliable technique is to change it and see what breaks. No map the reader builds survives contact with the code.") + self.assertTrue(anchors[5].startswith("- 10 β€” Duress-proof. Hungover,")) + 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.") + + +class ProjectValues(unittest.TestCase): + def test_reads_each_spelling_the_projects_use(self): + for spelling in ( + "## Scoring run\n\nThe values:\n\n- `{language}`: Python\n- `{kind}`: a CLI\n- `{domain}`: parsing\n- `{domain docs}`: the spec\n- `{3am question}`: the parse\n hangs\n\n## Next\n\n- `{kind}`: other\n", + "# 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", + "## 8. 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", + ): + with self.subTest(spelling=spelling[:20]): + self.assertEqual(project_values(spelling, "AGENTS.md"), VALUES) + + def test_keeps_a_colon_an_x_and_an_ellipsis_in_a_value_and_skips_a_bullet_without_a_colon(self): + text = "## Scoring run\n\n- Language: Python\n- Kind: a CLI: small\n- Kind\n- Domain: LaTeX\n- Domain docs: the spec\n- 3am question: it hangs...\n" + self.assertEqual(project_values(text, "AGENTS.md"), {**VALUES, "kind": "a CLI: small", "domain": "LaTeX", "3am question": "it hangs..."}) + + def test_names_the_values_a_section_lacks_and_a_file_without_one(self): + self.assertEqual(project_values("## Scoring run\n\n- Language: Python\n- Kind: a CLI\n", "AGENTS.md"), Failure("AGENTS.md β†’ \"Scoring run\" gives no {domain}, {domain docs} or {3am question}; add them as seat-prompts.md lists them")) + self.assertEqual(project_values("# P\n", "AGENTS.md"), Failure("AGENTS.md has no \"Scoring run\" section to fill the seats' prompts from; add one with {language}, {kind}, {domain}, {domain docs} and {3am question}")) + + +class FileGlobs(unittest.TestCase): + def test_names_no_test_files_where_every_glob_holds_none(self): + self.assertEqual(file_globs(["bin/a.py", "tests/x.py", "README.md"]), "`bin/**` and `README.md`") + + def test_gives_one_glob_per_directory_and_each_top_level_file_leaving_out_tests_and_the_forbidden_files(self): + paths = ["README.md", "ci.sh", "bin/run", "bin/a/main.py", "bin/a/test_main.py", "docs/decisions.md", "docs/guide.md", "todo.md", "tests/x.py", "web/app.test.ts"] + 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"] + self.assertEqual(bullets(lines), [["- a more"], ["- b"], ["- c"]]) + + +class PrepareScoring(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = pathlib.Path(os.path.realpath(temp.name)) + self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.root)} + self.checkout = self.root / "proj" + self.checkout.mkdir() + self.git("init", "-q", "-b", "item-9") + (self.checkout / "README.md").write_text("# P\n") + (self.checkout / "bin").mkdir() + (self.checkout / "bin" / "tool.py").write_text("") + + def git(self, *args): + return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout + + def commit(self, agents=None): + if agents is not None: + (self.checkout / "AGENTS.md").write_text(agents) + self.git("add", "-A") + self.git("commit", "-q", "-m", "start") + + def prepare(self, preloaded=None): + """What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs.""" + with mock.patch.dict(os.environ, self.env, clear=True): + return prepare_scoring(str(self.checkout), preloaded) + + def run_tool(self, *args): + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) + + def test_writes_each_seats_prompt_with_every_placeholder_filled_and_a_worktree_at_head(self): + self.commit("# A\n\n## 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") + ran = self.prepare("`README.md`") + folder = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" + worktree = folder / "checkout" + prompts = [folder / f"{seat}.md" for seat in ("junior-a", "mid-a", "maintainability-senior", "inherited-architect")] + self.assertEqual(ran, f"Scoring worktree, at {self.git('rev-parse', '--short', 'HEAD').strip()}: {worktree}\nPrompts:\n" + "\n".join(str(prompt) for prompt in prompts)) + self.assertEqual(subprocess.run(["git", "rev-parse", "HEAD"], cwd=worktree, env=self.env, capture_output=True, text=True).stdout, self.git("rev-parse", "HEAD")) + junior, _, senior, architect = (prompt.read_text() for prompt in prompts) + for prompt in (junior, architect): + self.assertEqual(re.findall(r"\{[a-z0-9 ]+\}", prompt), []) + self.assertTrue(junior.startswith(f"You are one seat of a comprehension panel. Tools: Read, Grep, Glob, and Bash only for `git -C {worktree} ls-files` and `ls`.")) + self.assertIn("\n\nYour background: ~2 years in Python, first codebase of this kind (a CLI); no exposure to the domain at all.\n\n", junior) + self.assertIn(f"Target: the project checked out at {worktree} (branch `item-9`). Read ONLY there β€” never {self.checkout}, which is a different version.", junior) + self.assertIn("every non-test tracked file: `bin/**`, `AGENTS.md` and `README.md`. Do NOT open todo.md, docs/decisions.md,", junior) + self.assertIn("from a DIFFERENT version (main): `README.md`.", junior) + self.assertIn("\n- 7 β€” Predictable. The layout answers", junior) + self.assertIn("Report, in this shape:", senior) + self.assertIn("~15 years taking over other people's systems", architect) + self.assertIn("The 3am question: the parse hangs β€” walking in cold", architect) + self.assertNotIn("Report, in this shape:", architect) + (folder / "mid-a.md").write_text("stale") + again = self.prepare() + self.assertTrue(again.startswith(f"Removed the scoring run set up before in {folder}.\nScoring worktree, at ")) + self.assertNotEqual((folder / "mid-a.md").read_text(), "stale") + self.assertEqual(len(self.git("worktree", "list").splitlines()), 2) + + def test_says_it_could_not_remove_a_checkout_git_does_not_hold(self): + self.commit() + checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout" + checkout.mkdir(parents=True) + with mock.patch.dict(os.environ, self.env, clear=True): + removed = removed_setup(str(self.checkout)) + self.assertIsInstance(removed, Failure) + self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) + self.assertTrue(checkout.exists()) + + def test_refuses_writing_nothing_where_the_project_gives_no_values(self): + self.commit() + ran = self.run_tool("prepare-scoring") + self.assertEqual(ran.returncode, 1) + self.assertIn("AGENTS.md has no \"Scoring run\" section", ran.stderr) + self.assertFalse((self.root / ".local" / "state" / "larv-review" / "proj" / "scoring").exists()) + self.assertEqual(len(self.git("worktree", "list").splitlines()), 1) + + def test_lists_the_harness_files_where_no_preloaded_is_given(self): + (self.checkout / "CLAUDE.md").write_text("@AGENTS.md\n") + self.commit("## 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") + self.assertNotIsInstance(self.prepare(), Failure) + junior = (self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "junior-a.md").read_text() + self.assertIn("from a DIFFERENT version (main): `CLAUDE.md` and `AGENTS.md`, which it imports.", junior) + + def test_leaves_out_a_claude_md_the_project_settings_exclude(self): + (self.root / ".claude").mkdir() + (self.root / ".claude" / "CLAUDE.md").write_text("# Home\n") + (self.root / ".claude" / "rules").mkdir() + rule = "always" + (self.root / ".claude" / "rules" / f"{rule}.md").write_text("# Always\n") + (self.checkout / ".claude").mkdir() + (self.checkout / ".claude" / "settings.json").write_text('{"claudeMdExcludes": ["**/.claude/CLAUDE.md"]}\n') + (self.checkout / ".claude" / "settings.local.json").write_text("not json") + self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/rules/{rule}.md`") + (self.checkout / ".claude" / "settings.json").write_text('{"claudeMdExcludes": [3]}\n') + self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/CLAUDE.md` and `~/.claude/rules/{rule}.md`") + + def test_names_each_import_and_each_rule_without_paths_leaving_out_what_the_user_settings_exclude(self): + (self.root / ".claude" / "rules").mkdir(parents=True) + (self.root / ".claude" / "settings.json").write_text('{"claudeMdExcludes": ["**/rules/skipped.md"]}') + (self.root / ".claude" / "rules" / "skipped.md").write_text("# Skipped\n") + (self.checkout / "CLAUDE.md").write_text("# Project\n\n@AGENTS.md\n@docs/x.md\n") + (self.checkout / ".claude" / "rules").mkdir(parents=True) + (self.checkout / ".claude" / "rules" / "always.md").write_text("# Always\n") + (self.checkout / ".claude" / "rules" / "scoped.md").write_text("---\npaths: ['*.py']\n---\n") + imports, rule = "`AGENTS.md`, which it imports, `docs/x.md`, which it imports", "always" + self.assertEqual(preloaded_files(self.checkout, self.root), f"`{CLAUDE_MD}`, {imports} and `.claude/rules/{rule}.md`") + + def test_reads_the_excludes_of_both_settings_files_and_names_none_where_nothing_loads(self): + (self.root / ".claude").mkdir() + (self.root / ".claude" / "CLAUDE.md").write_text("# Home\n") + (self.checkout / "CLAUDE.md").write_text("# Project\n") + (self.checkout / ".claude").mkdir() + settings, local = self.checkout / ".claude" / "settings.json", self.checkout / ".claude" / "settings.local.json" + for first, second in (("not json", '{"claudeMdExcludes": ["**/.claude/*.md", "**/proj/*.md"]}'), ('{"claudeMdExcludes": ["**/.claude/*.md"]}', '{"claudeMdExcludes": ["**/proj/*.md"]}')): + with self.subTest(first=first): + settings.write_text(first) + local.write_text(second) + self.assertEqual(preloaded_files(self.checkout, self.root), "none") + for odd in ("[1]", '{"claudeMdExcludes": 3}'): + with self.subTest(odd=odd): + settings.write_text(odd) + local.write_text(odd) + self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/{CLAUDE_MD}` and `{CLAUDE_MD}`") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/repo_checks/test_readme_test_line.py b/bin/repo_checks/test_readme_test_line.py deleted file mode 100644 index 1cd46c08..00000000 --- a/bin/repo_checks/test_readme_test_line.py +++ /dev/null @@ -1,16 +0,0 @@ -import pathlib -import re -import sys -import unittest - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) - -from machine_load.slots import CPUS_PER_SLOT -from repo_checks import ROOT - - -class TestLine(unittest.TestCase): - def test_the_readme_runs_the_tests_in_one_heavy_slots_cpus(self): - workers = re.search(r"pytest==\S+ -n (\d+) bin`", (ROOT / "README.md").read_text(encoding="utf-8")) - self.assertIsNotNone(workers, "README.md's Test line runs `pytest==X -n N bin`") - self.assertEqual(int(workers.group(1)), CPUS_PER_SLOT) diff --git a/bin/run-tests b/bin/run-tests new file mode 100755 index 00000000..e070a876 --- /dev/null +++ b/bin/run-tests @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from run_tests import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/run_tests/__init__.py b/bin/run_tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/run_tests/main.py b/bin/run_tests/main.py new file mode 100644 index 00000000..6bc51c5e --- /dev/null +++ b/bin/run_tests/main.py @@ -0,0 +1,99 @@ +"""Run this repo's test suite as README.md β†’ Test says, and print only what a reader needs from it. + +usage: run-tests [<pytest args>...] + +It runs pytest, pinned with pytest-xdist in one worker per CPU of a heavy slot through uvx, on the arguments given, +adding the repo's bin/ folder where none of them names a path that exists. It saves the whole +output to a new file. It prints each failing test's name, its first error lines and where it +failed, then pytest's short test summary and summary line, then `Full log: <path>`. Where pytest +printed no summary line, it prints the log's last lines in their place. + +Exit 0 where every test passed, 1 otherwise, or where pytest cannot start, saying why. +""" +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile + +from machine_load.slots import CPUS_PER_SLOT + +BIN = pathlib.Path(__file__).resolve().parents[1] +# ci.sh runs this command, so its pins live here; README.md β†’ Test's mutation command repeats the pytest pin, so change both. The workers fill one heavy slot, since run-heavy grants one. +PYTEST = ["uvx", "--python", shutil.which("python3") or sys.executable, "--with", "pytest-xdist==3.8.0", "pytest==9.2.0", "-n", str(CPUS_PER_SLOT)] +SECTION = re.compile(r"^=+ (.+) =+$") +TEST_HEADER = re.compile(r"^_+ .+ _+$") +# A traceback's last line, such as `bin/x/test_x.py:12: AssertionError`. +LOCATION = re.compile(r"^\S+:\d+: \S") +# pytest's last line, such as `==== 2 failed, 1 passed in 0.31s ====`, or without the rules under -q. +SUMMARY_LINE = re.compile(r"^(=+ )?(no tests ran|\d+ \w+).* in [\d.]+s\b.*$") +ERROR_LINES = 10 +LOG_TAIL = 20 + + +def pytest_args(argv: list[str]) -> list[str]: + """argv, with bin/ added where no argument names a path, so `run-tests -k name` still runs the suite.""" + if any(os.path.exists(arg.split("::")[0]) for arg in argv): + return argv + return [*argv, str(BIN)] + + +def report(log: str) -> list[str]: + """What to print of pytest's output: each failing test's header, error lines and location, then the short test summary and the summary line; [] where pytest printed no summary line. + + The error lines come from the FAILURES and ERRORS sections, since pytest-xdist leaves them out of the short summary's lines.""" + lines = log.splitlines() + ends = [index for index, line in enumerate(lines) if SUMMARY_LINE.match(line)] + if not ends: + return [] + printed: list[str] = [] + section = "" + errors = 0 + for line in lines[:ends[-1]]: + heading = SECTION.match(line) + if heading: + section = heading.group(1) + elif section in ("FAILURES", "ERRORS"): + if TEST_HEADER.match(line): + errors = 0 + printed.append(line) + elif line.startswith("E "): + errors += 1 + if errors <= ERROR_LINES: + printed.append(line) + elif LOCATION.match(line): + if errors > ERROR_LINES: + printed.append(f"E … {errors - ERROR_LINES} more lines in the log") + printed.append(line) + elif section == "short test summary info": + printed.append(line) + return [*printed, lines[ends[-1]]] + + +def run(argv: list[str], pytest: list[str] = PYTEST, cwd: str | None = None) -> int: + descriptor, log_path = tempfile.mkstemp(prefix="run-tests-", suffix=".log") + with os.fdopen(descriptor, "w") as log: + try: + code = subprocess.run([*pytest, *pytest_args(argv)], stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=cwd).returncode + except OSError as error: + os.unlink(log_path) + print(f"run-tests: cannot start {pytest[0]}: {error.strerror}", file=sys.stderr) + return 1 + output = pathlib.Path(log_path).read_text(errors="replace") + lines = report(output) + if lines: + print("\n".join(lines)) + else: + print("run-tests: pytest printed no summary line; the log ends:") + print("\n".join(output.splitlines()[-LOG_TAIL:])) + print(f"Full log: {log_path}") + return 0 if code == 0 else 1 + + +def main(argv: list[str]) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + return run(argv) diff --git a/bin/run_tests/test_run_tests.py b/bin/run_tests/test_run_tests.py new file mode 100644 index 00000000..139f316e --- /dev/null +++ b/bin/run_tests/test_run_tests.py @@ -0,0 +1,169 @@ +import contextlib +import importlib.util +import io +from unittest import mock +import os +import pathlib +import re +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from run_tests import main + +BIN = pathlib.Path(__file__).resolve().parents[1] +# The suite runs under pytest, and `python3 -m unittest` may run it where pytest is not installed. +HAS_PYTEST = importlib.util.find_spec("pytest") is not None +HAS_XDIST = importlib.util.find_spec("xdist") is not None +PYTEST_HERE = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider"] + + +class PytestArgs(unittest.TestCase): + def test_runs_bin_when_no_argument_names_a_path(self): + self.assertEqual(main.pytest_args([]), [str(BIN)]) + self.assertEqual(main.pytest_args(["-k", "no_such_path_here"]), ["-k", "no_such_path_here", str(BIN)]) + + def test_passes_a_given_path_on_alone(self): + with tempfile.TemporaryDirectory() as folder: + test_file = pathlib.Path(folder, "test_x.py") + test_file.write_text("") + self.assertEqual(main.pytest_args([str(test_file)]), [str(test_file)]) + self.assertEqual(main.pytest_args(["-x", f"{test_file}::T::test_a"]), ["-x", f"{test_file}::T::test_a"]) + + +def errors(count: int) -> str: + return "".join(f"E line {n}\n" for n in range(count)) + + +class Report(unittest.TestCase): + def test_prints_each_failure_and_error_with_its_errors_then_the_summary(self): + log = ( + "===== test session starts =====\nE not in a section\n" + f"===== FAILURES =====\n_____ test_a _____\n\n def test_a():\n{errors(main.ERROR_LINES)}a.py:2: AssertionError\n" + f"===== ERRORS =====\n_____ ERROR at setup of test_b _____\n{errors(main.ERROR_LINES + 3)}b.py:4: ValueError\n" + "===== short test summary info =====\nFAILED a.py::test_a\nERROR b.py::test_b\n===== 1 failed, 1 error in 0.10s =====\n" + ) + self.assertEqual(main.report(log), [ + "_____ test_a _____", *errors(main.ERROR_LINES).splitlines(), "a.py:2: AssertionError", + "_____ ERROR at setup of test_b _____", *errors(main.ERROR_LINES).splitlines(), "E … 3 more lines in the log", "b.py:4: ValueError", + "FAILED a.py::test_a", "ERROR b.py::test_b", "===== 1 failed, 1 error in 0.10s =====", + ]) + + def test_prints_nothing_where_pytest_printed_no_summary_line(self): + self.assertEqual(main.report("usage: pytest\nerror: unrecognized arguments\n"), []) + + +class Main(unittest.TestCase): + def test_prints_the_help_for_h_or_help_first_and_runs_anything_else(self): + for argv in (["-h"], ["--help"], ["--help", "bin/x"]): + with self.subTest(argv=argv): + out = io.StringIO() + with contextlib.redirect_stdout(out), mock.patch.object(main, "run") as run: + self.assertEqual(main.main(argv), 0) + self.assertEqual(out.getvalue(), main.__doc__.strip() + "\n") + run.assert_not_called() + with mock.patch.object(main, "run", return_value=1) as run: + self.assertEqual(main.main(["bin/x", "-h"]), 1) + run.assert_called_once_with(["bin/x", "-h"]) + + +class RunWithAStandIn(unittest.TestCase): + """run with a stand-in for pytest: a Python script given the arguments run passes on.""" + + def run_script(self, script: str, cwd: str | None = None) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.run(["-x"], [sys.executable, "-c", script], cwd) + lines = out.getvalue().splitlines() + if lines and lines[-1].startswith("Full log: "): + self.addCleanup(os.unlink, lines[-1].removeprefix("Full log: ")) + return code, out.getvalue(), err.getvalue() + + def test_saves_the_log_as_run_tests_star_log_in_the_temp_folder_which_ci_sh_prints(self): + code, out, _ = self.run_script("print('== 1 passed in 0.1s ==')") + self.assertEqual(code, 0) + log = pathlib.Path(out.splitlines()[-1].removeprefix("Full log: ")) + self.assertEqual(log.parent, pathlib.Path(tempfile.gettempdir())) + self.assertRegex(log.name, r"^run-tests-.+\.log$") + + def test_runs_in_the_folder_given_and_shows_the_last_lines_of_a_log_without_a_summary(self): + with tempfile.TemporaryDirectory() as folder: + script = "import os, sys; sys.stdout.buffer.write(b'bad \\xff byte\\n'); print('\\n'.join(map(str, range(30)))); print(os.getcwd())" + code, out, _ = self.run_script(script, folder) + self.assertEqual(code, 0) + tail = [str(n) for n in range(30 - main.LOG_TAIL + 1, 30)] + [os.path.realpath(folder)] + self.assertEqual(out.splitlines()[:-1], ["run-tests: pytest printed no summary line; the log ends:", *tail]) + + def test_reads_a_log_that_is_not_utf_8(self): + code, out, _ = self.run_script("import sys; sys.stdout.buffer.write(b'\\xff\\n== 1 failed in 0.1s ==\\n'); sys.exit(1)") + self.assertEqual(code, 1) + self.assertIn("== 1 failed in 0.1s ==", out) + + def test_says_on_stderr_that_a_command_cannot_start(self): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.run([], ["/no/such/uvx"]) + self.assertEqual((code, out.getvalue()), (1, "")) + self.assertEqual(err.getvalue(), "run-tests: cannot start /no/such/uvx: No such file or directory\n") + + +@unittest.skipUnless(HAS_PYTEST, "needs pytest importable") +class Run(unittest.TestCase): + def run_in(self, folder: str, pytest: list[str], *args: str) -> tuple[int, str]: + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + code = main.run(list(args), pytest, folder) + return code, out.getvalue() + + def log_named(self, output: str) -> pathlib.Path: + last = output.rstrip("\n").splitlines()[-1] + self.assertTrue(last.startswith("Full log: "), output) + path = pathlib.Path(last.removeprefix("Full log: ")) + self.addCleanup(path.unlink, missing_ok=True) + return path + + def test_a_passing_run_prints_the_summary_line_and_the_log_path(self): + with tempfile.TemporaryDirectory() as folder: + pathlib.Path(folder, "test_ok.py").write_text("def test_ok():\n\tprint('noise from a passing test')\n") + code, output = self.run_in(folder, PYTEST_HERE, "-s", folder) + self.assertEqual(code, 0) + lines = output.rstrip("\n").splitlines() + self.assertEqual(len(lines), 2, output) + self.assertRegex(lines[0], r"^=+ 1 passed in .* =+$") + self.assertIn("noise from a passing test", self.log_named(output).read_text()) + + def test_a_failing_run_prints_each_failing_test_with_its_error(self): + # pytest-xdist drops the error from the short summary's lines, so the run takes it from the FAILURES section. + workers = ["-n", "2"] if HAS_XDIST else [] + with tempfile.TemporaryDirectory() as folder: + pathlib.Path(folder, "test_bad.py").write_text("def test_ok():\n\tpass\n\ndef test_bad():\n\tassert 1 == 2, 'one is not two'\n\ndef test_long():\n\traise ValueError('\\n'.join(map(str, range(30))))\n") + code, output = self.run_in(folder, PYTEST_HERE, *workers, folder) + self.assertEqual(code, 1) + self.assertRegex(output, r"(?m)^_+ test_bad _+\nE +AssertionError: one is not two\n(E .*\n)*.*test_bad\.py:5: AssertionError$") + self.assertRegex(output, r"(?m)^FAILED .*test_bad\.py::test_bad\b") + self.assertRegex(output, r"(?m)^E +… \d+ more lines in the log$") + self.assertEqual(len(re.findall(r"(?m)^E ", output)), 2 + main.ERROR_LINES + 1) + self.assertRegex(output, r"=+ 2 failed, 1 passed in .* =+\n") + self.assertNotIn("def test_bad", output) + self.assertIn("def test_bad", self.log_named(output).read_text()) + + def test_a_run_that_cannot_start_says_so(self): + with tempfile.TemporaryDirectory() as folder: + code, output = self.run_in(folder, [os.path.join(folder, "no-such-uvx")]) + self.assertEqual(code, 1) + self.assertIn("run-tests: cannot start", output) + self.assertNotIn("Full log: ", output) + + def test_a_run_that_prints_no_summary_line_shows_the_logs_last_lines(self): + with tempfile.TemporaryDirectory() as folder: + code, output = self.run_in(folder, PYTEST_HERE, "--no-such-option", folder) + self.assertEqual(code, 1) + self.assertIn("run-tests: pytest printed no summary line; the log ends:", output) + self.assertIn("--no-such-option", output) + self.log_named(output) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/wait-for b/bin/wait-for new file mode 100755 index 00000000..6b1379ae --- /dev/null +++ b/bin/wait-for @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from wait_for import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/wait_for/__init__.py b/bin/wait_for/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/wait_for/main.py b/bin/wait_for/main.py new file mode 100644 index 00000000..dc042dac --- /dev/null +++ b/bin/wait_for/main.py @@ -0,0 +1,106 @@ +"""Wait until a file a background job writes holds a line matching a pattern, and print that line. + +usage: wait-for <file> [<pattern>] [--timeout <seconds>] + +<pattern> is a Python regular expression, searched for in each line; it prints the first line that +holds a match. Without <pattern>, it waits until the file holds anything, and prints its last +line. A last line without its newline counts once a check finds the file unchanged, since the +job may still be writing it. It checks every 2 seconds and gives up after --timeout seconds, 540 by default, so it fits +one foreground call of the Bash tool, whose limit is 600 seconds. + +Exit 0 on the line, 1 on the timeout, bad arguments or a file it cannot read, saying why. +""" +import pathlib +import re +import sys +import time +import typing + +from failure import Failure + +POLL_SECONDS = 2 +TIMEOUT_SECONDS = 540 +USAGE = "usage: wait-for <file> [<pattern>] [--timeout <seconds>]" + + +class Clock(typing.Protocol): + def monotonic(self) -> float: ... + def sleep(self, seconds: float) -> None: ... + + +def text_of(path: pathlib.Path) -> str | None | Failure: + """What the file holds; None where it doesn't exist.""" + try: + return path.read_text(errors="replace") + except FileNotFoundError: + return None + except OSError as error: + return Failure(f"cannot read {path}: {error.strerror}") + + +def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None: + """The first line of text matching pattern, or without one its last line; None where there is none.""" + lines = text.splitlines() + if pattern is None: + return lines[-1] if lines else None + return next((line for line in lines if pattern.search(line)), None) + + +def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) -> str | Failure: + path = pathlib.Path(file) + compiled = re.compile(pattern) if pattern is not None else None + deadline = clock.monotonic() + timeout + before = None + while True: + text = text_of(path) + if isinstance(text, Failure): + return text + # A last line without its newline may still be being written: it counts once a poll finds it unchanged. + settled = text is None or text.endswith("\n") or text == before + whole = text if settled or text is None else text[:text.rfind("\n") + 1] + # Without a pattern the last line is wanted, so an unsettled one waits. + if whole is not None and (settled or compiled is not None) and (found := line_in(whole, compiled)) is not None: + return found + before = text + left = deadline - clock.monotonic() + if left <= 0: + 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" + 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)) + + +def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure: + operands = list(argv) + timeout = float(TIMEOUT_SECONDS) + if "--timeout" in operands: + at = operands.index("--timeout") + given = operands[at + 1:at + 2] + if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0: + return Failure(f"give --timeout a number of seconds above 0; {USAGE}") + timeout = float(given[0]) + del operands[at:at + 2] + if not 1 <= len(operands) <= 2: + return Failure(USAGE) + pattern = operands[1] if len(operands) == 2 else None + if pattern is not None: + try: + re.compile(pattern) + except re.error as error: + return Failure(f"cannot read the pattern `{pattern}`: {error}") + return operands[0], pattern, timeout + + +def main(argv: list[str]) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + parsed = arguments(argv) + done = parsed if isinstance(parsed, Failure) else waited(*parsed) + if isinstance(done, Failure): + print(f"wait-for: {done.reason}", file=sys.stderr) + return 1 + print(done) + return 0 diff --git a/bin/wait_for/test_wait_for.py b/bin/wait_for/test_wait_for.py new file mode 100644 index 00000000..08d880b4 --- /dev/null +++ b/bin/wait_for/test_wait_for.py @@ -0,0 +1,148 @@ +import contextlib +import io +import pathlib +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from wait_for import main + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "wait-for" + + +class Clock: + """A fake clock whose sleep advances time and runs the next of the steps given, one per sleep.""" + + def __init__(self, *steps): + self.now = 0.0 + self.steps = list(steps) + + def monotonic(self) -> float: + return self.now + + def sleep(self, seconds: float): + self.now += seconds + if self.steps: + self.steps.pop(0)() + + +class WaitFor(unittest.TestCase): + def setUp(self): + self.file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "report.md") + + def test_prints_the_first_line_matching_the_pattern_once_the_file_holds_it(self): + clock = Clock(lambda: self.file.write_text("running\n"), lambda: self.file.write_text("running\n== 3 passed in 1s ==\nFull log: x\n")) + self.assertEqual(main.waited(str(self.file), r"passed|failed", 60, clock), "== 3 passed in 1s ==") + self.assertEqual(clock.now, 2 * main.POLL_SECONDS) + + def test_without_a_pattern_prints_the_last_line_once_the_file_holds_anything(self): + clock = Clock(lambda: self.file.write_text(""), lambda: self.file.write_text("# Report\nNo findings.\n")) + self.assertEqual(main.waited(str(self.file), None, 60, clock), "No findings.") + + def test_a_file_already_holding_the_line_returns_at_once(self): + self.file.write_text("done\n") + clock = Clock() + self.assertEqual(main.waited(str(self.file), "done", 60, clock), "done") + self.assertEqual(clock.now, 0) + + def test_gives_up_at_the_timeout_naming_the_file_and_its_last_line(self): + self.file.write_text("still running\n") + clock = Clock() + self.assertEqual(main.waited(str(self.file), "passed", 30, clock), Failure(f"{self.file} held no line matching `passed` after 30 s; its last line: still running")) + self.assertLessEqual(clock.now, 30) + + def test_gives_up_on_a_file_that_never_appears(self): + self.assertEqual(main.waited(str(self.file), None, 5, Clock()), Failure(f"{self.file} did not appear in 5 s")) + + def test_waits_for_a_half_written_last_line_to_end(self): + self.file.write_text("running\n== 3 passed in") + clock = Clock(lambda: self.file.write_text("running\n== 3 passed in 1s ==\n")) + self.assertEqual(main.waited(str(self.file), "passed", 60, clock), "== 3 passed in 1s ==") + + def test_takes_a_last_line_without_a_newline_once_a_poll_finds_it_unchanged(self): + self.file.write_text("# Report\nNo findings.") + clock = Clock() + self.assertEqual(main.waited(str(self.file), None, 60, clock), "No findings.") + self.assertEqual(clock.now, main.POLL_SECONDS) + + def test_takes_a_whole_line_at_once_beside_a_half_written_one(self): + self.file.write_text("a\nb\npart") + clock = Clock() + self.assertEqual(main.waited(str(self.file), "b", 60, clock), "b") + self.assertEqual(clock.now, 0) + self.file.write_text("done\n") + self.assertEqual(main.waited(str(self.file), None, 60, clock), "done") + self.assertEqual(clock.now, 0) + + def test_matches_no_part_of_a_half_written_first_line(self): + self.file.write_text("part") + clock = Clock(lambda: self.file.write_text("partial\n")) + self.assertEqual(main.waited(str(self.file), "p", 60, clock), "partial") + + def test_reads_a_line_that_is_not_utf_8(self): + self.file.write_bytes(b"caf\xe9 passed\n") + self.assertEqual(main.waited(str(self.file), "passed", 60, Clock()), "caf\ufffd passed") + + 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(clock.now, 3) + + def test_sleeps_only_the_time_left_before_the_timeout(self): + clock = Clock() + main.waited(str(self.file), None, 3, clock) + self.assertEqual(clock.now, 3) + clock = Clock() + main.waited(str(self.file), None, 2.5, clock) + self.assertEqual(clock.now, 2.5) + + def test_a_folder_fails_at_once_naming_it(self): + self.assertEqual(main.waited(str(self.file.parent), None, 60, Clock()), Failure(f"cannot read {self.file.parent}: Is a directory")) + + def test_main_prints_the_line_or_the_reason_and_gives_the_exit_code(self): + self.file.write_text("== 1 passed ==\n") + for argv, expected in ( + ([str(self.file), "passed", "--timeout", "5"], (0, "== 1 passed ==\n", "")), + (["--help"], (0, main.__doc__.strip() + "\n", "")), + (["-h"], (0, main.__doc__.strip() + "\n", "")), + (["--help", str(self.file)], (0, main.__doc__.strip() + "\n", "")), + ([str(self.file), "("], (1, "", "wait-for: cannot read the pattern `(`: missing ), unterminated subpattern at position 0\n")), + ): + with self.subTest(argv=argv): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.main(argv) + self.assertEqual((code, out.getvalue(), err.getvalue()), expected) + + def test_arguments_take_the_timeout_anywhere_and_refuse_a_bad_one(self): + self.assertEqual(main.arguments(["--timeout", "1.5", "f", "p"]), ("f", "p", 1.5)) + self.assertEqual(main.arguments(["f"]), ("f", None, 540.0)) + self.assertEqual(main.arguments(["f", "--timeout", "0.5"]), ("f", None, 0.5)) + for timeout in ("0", "-1", "x", "1.", None): + with self.subTest(timeout=timeout): + argv = ["f", "--timeout"] + ([timeout] if timeout else []) + self.assertEqual(main.arguments(argv), Failure(f"give --timeout a number of seconds above 0; {main.USAGE}")) + for argv in ([], ["f", "a", "b"]): + with self.subTest(argv=argv): + self.assertEqual(main.arguments(argv), Failure(main.USAGE)) + + def test_the_command_prints_the_line_a_file_holds(self): + self.file.write_text("== 1 passed in 0.1s ==\n") + result = subprocess.run([sys.executable, str(TOOL), str(self.file), "passed", "--timeout", "20"], capture_output=True, text=True, timeout=10) + self.assertEqual((result.returncode, result.stdout, result.stderr), (0, "== 1 passed in 0.1s ==\n", "")) + + def test_refuses_a_bad_pattern_timeout_or_argument_count_waiting_for_nothing(self): + for argv in ([], [str(self.file), "("], [str(self.file), "--timeout", "0"], [str(self.file), "--timeout", "x"], [str(self.file), "a", "b"]): + with self.subTest(argv=argv): + result = subprocess.run([sys.executable, str(TOOL), *argv], capture_output=True, text=True, timeout=10) + self.assertEqual((result.returncode, result.stdout), (1, "")) + self.assertIn("wait-for: ", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci.sh b/ci.sh index 08ba6a5f..d9ddcd76 100755 --- a/ci.sh +++ b/ci.sh @@ -9,5 +9,6 @@ git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --use git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle /tmp/repo cd /tmp/repo python3 -m pip install --quiet --disable-pip-version-check --user uv==0.12.23 - PATH="$HOME/.local/bin:$PATH" uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin + # On a failure, the CI log shows the whole pytest output, which run-tests saved to its log file. + PATH="$HOME/.local/bin:$PATH" bin/run-tests || { cat /tmp/run-tests-*.log; exit 1; } ' diff --git a/docs/reading-cost.md b/docs/reading-cost.md index b5b0c380..87610076 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1754,3 +1754,20 @@ Read most (opens and searches): - `bin/review_replay/main.py` 2 - `docs/score-anchors.md` 2 - `agents/prose-reviewer.md` 1 + +## Reading cost, chunk 20df46f40f0e, finished 2026-11-12T07:35:52Z + +116698 new input tokens before the first commit. + +Read most (opens and searches): + +- `todo.md` 10 +- `README.md` 6 +- `bin/release_plan/todo_table.py` 5 +- `bin/todo_item/test_todo_item.py` 5 +- `docs/decisions.md` 4 +- `bin/command_patterns/main.py` 3 +- `CLAUDE.md` 2 +- `bin/release_plan/test_ranking.py` 2 +- `bin/todo_item/main.py` 2 +- `skills/larv-review/SKILL.md` 2 diff --git a/skills/comprehension-panel/SKILL.md b/skills/comprehension-panel/SKILL.md index cf36ff85..4d6f7a6b 100644 --- a/skills/comprehension-panel/SKILL.md +++ b/skills/comprehension-panel/SKILL.md @@ -94,9 +94,9 @@ the end. Tell everyone not to manufacture confusion. ## The scoring run A scoring run needs four seats β€” Junior A, Mid A, the maintainability senior and the inherited -architect β€” plus the calibration seat ("The score") when more than one project is in play. Build -the four seats' prompts from `seat-prompts.md`, filled in from the project's `AGENTS.md` β†’ "Scoring -run". Change neither between runs, or the scores are not comparable. A project without that +architect β€” plus the calibration seat ("The score") when more than one project is in play. `~/.claude/bin/larv-review prepare-scoring` +builds the four seats' prompts from `seat-prompts.md`, filled in from the project's `AGENTS.md` β†’ +"Scoring run". Change neither between runs, or the scores are not comparable. A project without that section gets it at its first scoring run or paired ruling. ## The paired ruling diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index f9ea458a..7073b727 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -151,12 +151,12 @@ The comprehension check records how hard the project is for its contributor to r **Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot. -- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means. +- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means. - **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to 7.0. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to 7.0, and quotes those places. Its tagline holds the words `comprehension floor`, so its own chunk runs a scoring run; while a mean stays under 7.0, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says. -- **Second run.** Where `needs-scoring-run` printed that the chunk `leaves release … with no plan item`, launch the same four seats afresh on the same head. Their scores file's first line is `<PR or branch> rerun at <commit>`. Record it with the same `record-scoring` command. +- **Second run.** Where `needs-scoring-run` printed that the chunk `leaves release … with no plan item`, run `prepare-scoring` again and launch the same four seats afresh on the same head. Their scores file's first line is `<PR or branch> rerun at <commit>`. Record it with the same `record-scoring` command. - **Agreement.** After the second run, run `~/.claude/bin/larv-review agreement` and put its counts in the summary. On `Assumption fails:`, ask the user whether to keep the paired ruling or change the decision `review: the comprehension check records …`. Record the answer as a decision in the repo whose history was counted, with the counts that led to the ask. A later run asks again only when the rulings' rate falls, or the runs' rate rises, against the recorded counts. -**Record.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Commit what it appends, with the `todo.md` that `record-scoring` re-ranks in one commit titled `Record the comprehension check: …`, push it, and wait for the forge's checks (Β§4 step 4), not for an auto-review; it re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. Put each ruling with its base and votes, and each run's five scores, in the summary. +**Record.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Commit what it appends, with the `todo.md` that `record-scoring` re-ranks in one commit titled `Record the comprehension check: …`, and push it; it re-enters no pass, and `chunk-pr merge` waits for the forge's checks it starts. Resolve a merge conflict in the file by putting the default branch's entries first. Put each ruling with its base and votes, and each run's five scores, in the summary. **Places.** The header of systems-architect and stability-reviewer names `places.md`, which holds what `~/.claude/bin/larv-review places` prints: the places seats found hard since the newest scored commit. Ask each to report, as a 🟑, each of those places the change touches without making it easier to read, matching a place by its path and the function or section it names, since its line may have moved. Fix such a 🟑, or say in the PR summary why not; that reason settles it in place of a decline's record. @@ -186,20 +186,19 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 4. Gate -1. Merge `origin/<default branch>` into this branch unless the head already holds it. -2. Run `~/.claude/bin/rank_todo.py --check todo.md`; a failure is a finding. -3. Run the project's test suite locally unless a run at the head, Β§2's or a stability round's, left it verified green. -4. Watch the forge's checks until every one passes. A red check is a finding. -5. No CI configured β†’ the gate is local tests only; note it in the summary. -6. Everything green β†’ mark the PR ready with `~/.claude/bin/chunk-pr ready`. -7. **External auto-reviewer**, when the repo has one β€” its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none β†’ skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then β†’ note it in the summary and carry on, never waiting twice. Its rounds, Β§3 β†’ "Round cap". Once it has reviewed, each later return here before its cap, after a fix re-entered per Β§3, waits up to **5 minutes** for its re-review of the new commit. +1. Run `~/.claude/bin/chunk-pr sync`: it merges `origin/<default branch>` into this branch unless the head already holds it, then runs `rank_todo.py --check` on `todo.md`. A rank failure is a finding. +2. Run the project's test suite locally unless a run at the head, Β§2's or a stability round's, left it verified green. +3. The forge's checks: `chunk-pr merge` waits for them to pass (Β§5 step 4). A red check is a finding. +4. No CI configured β†’ the gate is local tests only; note it in the summary. +5. The local tests green β†’ mark the PR ready with `~/.claude/bin/chunk-pr ready '<final title>'`, which sets the title as it marks the PR ready. +6. **External auto-reviewer**, when the repo has one β€” its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none β†’ skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then β†’ note it in the summary and carry on, never waiting twice. Its rounds, Β§3 β†’ "Round cap". Once it has reviewed, each later return here before its cap, after a fix re-entered per Β§3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals and code health, unless the README voids it: does anything in it work against one? It breaks a maintain goal β†’ do not merge; redesign the change or drop its item. It works against an achieve goal β†’ do not merge; ask the human, stating the conflict. 2. Run the comprehension check (Β§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to Β§4, and keep the ruling and scoring run already recorded. -3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` β†’ "Working loop" in the branch, commit and push that, and wait for the forge's checks (Β§4 step 4); the commit re-enters no pass. -4. Aligned, every pass done and everything green β†’ **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, after `~/.claude/bin/larv-review scoring-run-owed` exits 0. A repo withholds this in its `AGENTS.md` β†’ leave the PR ready and unmerged, and say which line withheld it. +3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` β†’ "Working loop" in the branch, commit and push that; the commit re-enters no pass. +4. Aligned and every pass done β†’ **merge** with `~/.claude/bin/chunk-pr merge`, run in the background, since its wait can outlast the Bash tool's timeout. It waits for the pull request's checks to pass, then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass and `~/.claude/bin/larv-review scoring-run-owed` exits 0. A repo withholds this in its `AGENTS.md` β†’ leave the PR ready and unmerged, and say which line withheld it. 5. Merged β†’ run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary. 6. Stop. The next chunk gets a fresh session. diff --git a/todo.md b/todo.md index 95b304ee..a0f408f2 100644 --- a/todo.md +++ b/todo.md @@ -14,11 +14,9 @@ |---|---|---|---|---|---|---|---|---|---|---|---| | 340 | 0.9.0 | | question | **Decide whether a reviewer may start without `CLAUDE.md` where its replay misses no more findings than an unchanged replay does.** | 2 | 2 | 3 | 5 | 4 | 1.4 by 5 | 1.7 | | 331 | 0.9.0 | | question | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.9 | -| 325 | 0.9.0 | | | **Give this repo's test suite one command that runs it as README β†’ Test says, prints the failing tests and pytest's summary line, and saves the whole log to a file whose path it prints.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 | | 305 | 0.9.0 | | | **Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4, 1.2 by 3 | 1.8 | | 318 | 0.9.0 | | | **Let `review-replay` qualify a rung whose recall is no lower than the project's rung's own replay, and replay Opus 5.5 at low effort on the prose pass.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 5 | 1.7 | | 308 | 0.9.0 | | | **Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test, both of which the worker now checks before review.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3, 1.5 by 2 | 1.6 | -| 295 | 0.9.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 | | 319 | 0.9.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 | | 309 | 0.9.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 | | 299 | 0.9.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 | @@ -28,16 +26,12 @@ | 341 | 0.9.0 | | | **Hand each worker's claude a lower Read limit through `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`, kept only where replays of the archived review rounds find what two unchanged replays find.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.2 | | 310 | 0.9.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 1.0 | | 298 | 0.9.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 1.0 | -| 326 | 0.9.0 | | | **Let `chunk-pr ready` take the pull request's final title and set it as it marks the pull request ready.** | 2 | 1 | 3 | 4 | 2 | 1.4 by 1, 1.5 by 1 | 0.9 | -| 332 | 0.9.0 | | defect | **Let `deploy-release` move a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes.** | 2 | 2 | 2 | 4 | 2 | 1.5 by 2 | 0.9 | -| 336 | 0.9.0 | | | **Bring a chunk's branch level with origin's default branch, and print the rank check, with one `chunk-pr sync`.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 1, 1.5 by 1 | 0.8 | -| 334 | 0.9.0 | | | **Set up a scoring run with one `larv-review` command that makes the scoring worktree, writes each seat's prompt file, and removes both once `record-scoring` has run.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 2, 1.5 by 1 | 0.7 | | 327 | 0.9.0 | | | **Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 1, 1.4 by 1 | 0.7 | | 303 | 0.10.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.8 | | 304 | 0.10.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 4.4 | | 306 | 0.10.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 | | 302 | 0.10.0 | | | **Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.** | 2 | 2 | 3 | 5 | 3 | code health by 2 | 3.6 | -| 287 | 0.10.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 | +| 287 | 0.10.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at`, `gitea`, `checks_passed` and `required_checks` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 | | 338 | 0.10.0 | | owner | **Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 | | 288 | 0.10.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 | | 77 | 0.10.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 | @@ -96,14 +90,6 @@ The architect's πŸ”€ answer on PR #493 (item 292): four decisions expire "when a Recommendation: reword all four as above. They are decisions the repo held before item 292, so the rewording is lilleman's call. -### 325. Give this repo's test suite one command that runs it as README β†’ Test says, prints the failing tests and pytest's summary line, and saves the whole log to a file whose path it prints. - -The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 163 to 176 Bash calls ran pytest, mutation runs excluded, in 29 chunks, for about 32k command tokens and 3,000 to 3,500 s of wall time. Each worker typed README β†’ Test's incantation, with its pins, and cut the output with its own `| tail -N`: 14 spellings (tail sizes 1, 2, 3, 4, 5, 6, 8, 12, 15, 20, 25, 30 and 70, or no tail in 44 calls). A short tail cuts a failing run's evidence, and a long run without one floods the context. - -Add one command, beside the README's Test section, that runs the suite as README β†’ Test says, passes on any test paths or pytest options it is given, prints each failing test with its error and pytest's summary line, and saves the whole log to a file whose path it prints. Point README β†’ Test at it, so the pins live in one place. Write its tests first: a passing run, a failing one, and a run that cannot start. - -Left with the model: which tests to run, reading the failures and fixing them. - ### 305. Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after. Three records the archive lacks, asked for by lilleman on 2026-11-11 after the token research of that day. @@ -126,10 +112,6 @@ Rounds past the first cost $846 of the $9,154 the archive measured from 2026-09- Round 2 still matters elsewhere: 53 of 241 archived stability reports of round 2 or later open with BLOCK. So first count, from the archived round 2s, the BLOCKs that a run of `mutate-changes` and the tests on the fix would not have raised, and ship the skip only if none falls in a round it would skip. Evidence: one review round scored F1 0.376 and a second 0.26 to 0.30 with more false positives (arXiv 2603.16244, `claude -p` with Opus 4.6, 30 artifacts). Revise larv-review Β§3 β†’ "Re-entry" and the decision `review: a fix for a πŸ”΄ reruns the pass that found it…`. -### 295. Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file. - -In 0.7.0's 35 chunks, workers made 65 `tea api` calls in 26 chunks, mostly polling commit status and trying merge methods in turn, and ran 25 `until … sleep` loops that took 1,744 seconds. `chunk-pr merge` takes `--gate-passed` on the worker's word; waiting for the required checks itself makes that flag a fact, not a claim. This is the kind of step item 284 files, and can count as its first. - ### 319. Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session. On SWE-bench Verified with Haiku 4.5 and Opus 4.7, handing the strong model the weak model's transcript solved 69.2% at $1.61 a task; starting the strong model fresh solved 79.2% at $0.90 (arXiv 2608.24358, The Handoff Tax). A model switch also rereads the whole context uncached (Claude Code prompt caching docs). A worker that steps from Sonnet 5.5 to Opus 5.5 by `--resume` is the raw handoff; an effort-only step within one model keeps the cache and isn't. The escalated subagent, which starts fresh with the trigger's evidence, already follows the pattern that won. @@ -184,38 +166,6 @@ Probe first that `claude -p "/compact" --resume <id>` compacts a session: the Ag 153 `Judge cost:` entries total $109.76, a median of about $0.76 a verdict at every rung, and the cost follows the size of the records, not the transcript: about 76k characters in log and 188k in claude-config. In 224 of 251 recent verdicts (89%) the evidence sits in the worker's final message. A missed interrupt is the costly error, so the bar is zero changed interrupts and zero new rejections across the replay. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster. -### 326. Let `chunk-pr ready` take the pull request's final title and set it as it marks the pull request ready. - -The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 30 `tea pr edit` calls in 18 chunks, about 2.0k command tokens. 17 of them, in 15 chunks, retitled a draft pull request the worker had opened with a provisional title; the rest looked up `tea pr edit --help`, rewrote a description or toggled the draft. On Gitea, `chunk-pr ready` already rewrites the title, dropping `WIP: `, so setting the final title there is the same call. - -Let `chunk-pr ready` take an optional final title and set it as it marks the pull request ready, on GitHub and on Gitea, and refuse a title of more than one line. `bin/chunk_pr/main.py:42` `forge` is a place the comprehension seats found hard; where the change touches it, make it easier to read, or leave it to item 287. - -Left with the model: wording the title. - -### 332. Let `deploy-release` move a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes. - -On 2026-11-12, moving `~/.claude` from v0.7.0 to v0.8.0, `deploy-release` failed at `git checkout --quiet --detach v0.8.0`: "Your local changes to the following files would be overwritten by checkout: settings.json". Claude Code had rewritten the file with `"model": "opus"` and its keys in another order. The `settings` clean filter drops the model and sorts the keys, so `git diff` showed no change and the tool's own check passed, but checkout compares the file as it is on disk. `deploy-release --help` says a model picked with `/model` doesn't block the move. - -The move worked after `git checkout -- settings.json`, with the model added back by hand. Have the tool set aside a change the clean filter removes, move, and restore the model pick, or tell the user to pick it again, as it already does when the move changes `settings.json`. Test it with a working file that differs from HEAD only by the model and the key order. - -### 336. Bring a chunk's branch level with origin's default branch, and print the rank check, with one `chunk-pr sync`. - -Found by item 328's audit of release 0.8.0. 8 of its 9 chunks synced with the default branch by hand before the merge, in 13 calls (about 2.4k tokens, 6 s): `git fetch -q origin && git merge-base --is-ancestor origin/main HEAD && echo holds-main`, then, where that failed, `git merge -q origin/main`, then `rank_todo.py --check todo.md`. - -`chunk-pr sync` fetches origin, merges its default branch into the chunk's branch where the branch does not already hold it, and prints one line saying which it did. Then it runs `rank_todo.py --check` where the worktree has a `todo.md`, and prints its result. On a merge conflict it stops with the merge in progress and names the conflicted files. chunk-pr already finds origin's default branch for `open`, so `sync` reuses that; where the change touches `bin/chunk_pr/main.py:42` `forge`, which the comprehension seats found hard because its helpers live in other packages, make it easier to read. `chunk-pr --help` and `larv-review` Β§4 step 1, which merges origin's default branch in before the gate, name the command. - -Left with the model: resolving a conflict, such as one in `todo.md`, and fixing what the rank check reports. - -### 334. Set up a scoring run with one `larv-review` command that makes the scoring worktree, writes each seat's prompt file, and removes both once `record-scoring` has run. - -Found by item 328's audit of release 0.8.0. Of its 9 chunks, only item 296's ran a scoring run, since scoring runs are rare, and it set the run up by hand in about 20 Bash calls: 7 reads of `skills/comprehension-panel/SKILL.md`, `seat-prompts.md` and the scoring-run values (ls, wc, sed; about 12k result tokens); `git worktree add --detach ../claude-config-scoring origin/main`, then `git checkout -b scoring-item-301`; one `mkdir /tmp/seat296` and three heredocs writing shared.txt, report-plain.txt and report-arch.txt (6.6k chars); two heredocs writing scores.md (4.5k and 3.6k chars); `larv-review record-scoring`; and `rm -rf /tmp/seat296`. About 16k tokens in all. - -The prompt text is fixed: `seat-prompts.md` says to copy the opening, each seat's background, the shared brief and the report for its kind of seat verbatim, and lists each `{placeholder}`. A program fills most of them: `{checkout}`, `{branch}`, `{main}` and `{git}` from the worktree it makes, `{forbidden}` from fixed text, `{files}` from `git ls-files`, `{anchors}` and `{dimensions}` from `SKILL.md` β†’ "The score", and `{language}`, `{kind}`, `{domain}`, `{domain docs}` and `{3am question}` from the project's scoring-run values (claude-config's in `seat-prompts.md` β†’ "claude-config's values"). Where one needs judgement, such as `{preloaded}`, the command takes it as an argument. It refuses, writing nothing, where the project has no scoring-run values. Where the prompt files land, a folder under the chunk's review folder or the state folder, is the implementer's call. - -The command makes the detached scoring worktree on origin's default branch, writes one prompt file per seat of the four `SKILL.md` β†’ "The scoring run" names, and prints their paths. A second form, or `record-scoring` itself, removes the worktree and the prompt folder after recording. - -Left with the model: launching the seats, reading their reports and writing the scores. Item 316 (the seats' own agent type) and item 309 (two seats in the second pass) change who reads these prompts and how many, not how they are built, so this item does not overlap them. - ### 327. Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it. The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 72 commit calls in 33 chunks titled `Answer <pass> round <n>: R πŸ”΄, Y 🟑 (K misread); <what changed>`, about 11k command tokens, most of them the summary. Each worker counts R, Y and K by hand. All three are in the round's report, `<pass>-round-<n>.md` in the review folder: R and Y are its finding headings, and K counts the findings the reviewer marked `[misread]`, as `bin/review_rules/round_titles.py` says. That module parses the counts for `score-outcomes`, which reports them as goal 1.1's signal, and rule-hook's `round_cap.py` checks only the round number, so nothing checks today that the counts match the report. Of the 8 titles whose report the audit could match, none miscounted; one report wrote its markers at line start rather than in `###` headings, so the reports' format varies by reviewer. @@ -254,7 +204,7 @@ Recommendation: a floor item's tagline opens with one fixed phrase, `Reach the c The same chunk names the phrase where a floor item is filed: `skills/larv-review/SKILL.md` β†’ "Floor item", the `Next:` lines `floor_step` prints, and `larv-review --help` (`bin/larv_review/main.py`, lines 35 and 89). It rewords open floor item 300's tagline to open with the phrase, and updates the tests in `bin/larv_review/test_larv_review.py` that use floor taglines (lines 120, 361, 435, 537), adding one where a tagline quotes the floor mid-sentence and is due no run. -### 287. Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them. +### 287. Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at`, `gitea`, `checks_passed` and `required_checks` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them. Today the helpers live in two tools. `Forge` is defined in `bin/chunk_preflight/gathered.py` and imported by `bin/chunk_preflight/choices.py`, `bin/chunk_preflight/facts.py`, `bin/chunk_preflight/main.py` and `bin/chunk_pr/main.py`, and again through `choices` by `bin/deploy_release/forge.py`. `forge_of` lives in `choices.py`, which `bin/chunk_pr/main.py`, `bin/deploy_release/cut.py` and `bin/larv_review/reviewer_header.py` import. `open_pull`, `runner` and `gitea` live in `bin/deploy_release/forge.py`, which `bin/chunk_pr/main.py` and `bin/larv_review/reviewer_header.py` import. So `deploy_release` imports `chunk_preflight`, and `chunk_pr` and `larv_review` import both. @@ -346,7 +296,7 @@ Places the seats named, hardest first (`larv-review places`): - Shape: `bin/review_rules/comprehension_history.py:127` `entries`: a line-by-line parser that tolerates two legacy formats. - Shape: `bin/records/__init__.py:1` `records`: one name for three concepts, as `cut` and `Plan` also name several. - Shape: `bin/rule_hook/rules.py:25` `RULES`: rules sit inline in one module while five others have a module each. -- Navigation, Shape: `README.md:116` `bin/`: about 55 entries in one flat list, some 31 of them packages, the worst fan-out level. +- Navigation, Shape: `README.md:116` `bin/`: about 64 entries in one flat list, some 35 of them packages, the worst fan-out level. - Self-sufficiency: `skills/larv-review/SKILL.md:147` "Scoring run": dense rule prose with many cross-references; three sections rebuild one rule. Scored L 4 because the refactor touches several components that hold known defects, E 2 because review and a manual check see a regression, I 3 because every session runs these tools. The chunk runs a scoring run, since its tagline names the comprehension floor.