From 547a9505fd35339b4b8bce89ccea4b1682111d51 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:41:29 +0100 Subject: [PATCH 01/10] Run the suite in a pinned container with ci.sh --- .gitignore | 4 ++++ ci.sh | 12 ++++++++++++ docs/reading-cost.md | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100755 ci.sh diff --git a/.gitignore b/.gitignore index a368caed..71d16de6 100644 --- a/.gitignore +++ b/.gitignore @@ -10,11 +10,15 @@ !CHANGELOG.md !CLAUDE.md !README.md +!ci.sh !settings.json !todo.md !.claude/ !.claude/settings.json +!.gitea/ +!.gitea/workflows/ +!.gitea/workflows/*.yml !agents/ !agents/*.md !bin/ diff --git a/ci.sh b/ci.sh new file mode 100755 index 00000000..3a291f75 --- /dev/null +++ b/ci.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Runs the test suite on the committed HEAD as CI does: in a pinned Python container, as the caller's uid, so the tests root skips run too. +# The repo goes in as a git bundle rather than a bind mount, so the script works whether the CI runner shares the docker daemon's filesystem or not. +set -eu +cd "$(dirname "$0")" +git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" -e HOME=/tmp python:3.14.8 sh -euc ' + cat >/tmp/head.bundle + git clone --quiet /tmp/head.bundle /tmp/repo + cd /tmp/repo + python3 -m pip install --quiet --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 +' diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 30b65b2c..89b336ab 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1407,3 +1407,20 @@ Read most (opens and searches): - `AGENTS.md` 1 - `CHANGELOG.md` 1 - `bin/chunk_pr/test_chunk_pr.py` 1 + +## Reading cost, chunk e310fe001a4d, finished 2026-11-09T01:39:01Z + +86875 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/larv_review/main.py` 6 +- `bin/larv_review/test_larv_review.py` 6 +- `skills/larv-review/SKILL.md` 4 +- `README.md` 3 +- `bin/deploy_release/forge.py` 3 +- `bin/chunk_pr/main.py` 2 +- `bin/git_cli/git_repo.py` 2 +- `bin/larv_review/history_commands.py` 2 +- `bin/larv_review/reviewer_header.py` 2 +- `bin/review_replay/rounds.py` 2 -- 2.52.0 From daf6a38fc34b514351aa63b6bf0e51fe19db10ca Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:41:36 +0100 Subject: [PATCH 02/10] Run ci.sh on every pull request --- .gitea/workflows/ci.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .gitea/workflows/ci.yml diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 00000000..164d5ec0 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,11 @@ +name: CI +on: pull_request + +jobs: + tests: + runs-on: docker-host + steps: + - uses: actions/checkout@v7.0.1 + with: + fetch-depth: 0 # ci.sh bundles HEAD, which a shallow clone can't + - run: sh ci.sh -- 2.52.0 From 94aa8bafbf1050e3fe8a58bc207f3ad3fc651b63 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:44:40 +0100 Subject: [PATCH 03/10] Say as each step of deploy-release --cut finishes, end on a Done line, delete the merged release branch, and wait for the checks main's protection requires --- bin/deploy_release/cut.py | 35 +++++++++++-- bin/deploy_release/forge.py | 32 +++++++++--- bin/deploy_release/main.py | 7 ++- bin/deploy_release/test_deploy_release.py | 60 ++++++++++++++++++++--- 4 files changed, 114 insertions(+), 20 deletions(-) diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 1e1d5d2c..c156d90a 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -48,14 +48,34 @@ def cut(clone: str, checkout: str) -> str | Failure: return merged if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure): return made + said(f"tagged {merged[:12]} {tag}") if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure): # Until a rerun, chunk-preflight would read a tag only the clone holds as cut. git("tag", "--delete", tag, cwd=clone) return pushed + said(f"pushed the tag {tag}") + delete_release_branch(clone, f"release-{named}") moved = deploy(checkout) if isinstance(moved, Failure): return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.") - return f"Cut {tag}.\n\n{moved}" + return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it." + + +def said(step: str) -> None: + """Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen.""" + print(f"deploy-release: {step}", file=sys.stderr) + + +def delete_release_branch(clone: str, branch: str) -> None: + """Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then.""" + listed = branch_head(branch, clone) + if listed is None: + return + deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone) + if isinstance(deleted, Failure): + said(f"warning: the branch {branch} stays on origin: {deleted.reason}") + else: + said(f"deleted the branch {branch} on origin") def drop_unpushed_cut_tags(clone: str) -> Failure | None: @@ -136,6 +156,7 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: # Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main. if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure): return pushed + said(f"pushed the branch {branch}") head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") if isinstance(head, Failure): return head @@ -144,12 +165,18 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure): return created number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}") + if isinstance(number, str): + said(f"opened pull request {number}") if isinstance(number, Failure): return number - print(f"deploy-release: waiting for the checks of pull request {number}", file=sys.stderr) - if isinstance(passed := forge.checks_passed(on, number, head, run), Failure): + said(f"waiting for the checks of pull request {number}") + if isinstance(passed := forge.checks_passed(on, number, head, base, run), Failure): return passed - return forge.merge(on, number, head, run) + said(f"the checks of pull request {number} passed") + if isinstance(merged := forge.merge(on, number, head, run), Failure): + return merged + said(f"merged pull request {number}") + return None def branch_head(branch: str, clone: str) -> str | None | Failure: diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 7b9c1198..1237416d 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -68,29 +68,47 @@ def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> F return created if isinstance(created, Failure) else None -def checks_passed(forge: Forge, number: str, head: 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.""" +def checks_passed(forge: Forge, number: str, head: str, base: 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. + + On Gitea it also waits for each check the protection of base requires to report: 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 return None + required = required_checks(base, run) + if isinstance(required, Failure): + return required while True: status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") if isinstance(status, Failure): return status try: count, state = status["total_count"], status["state"] - except (KeyError, TypeError): + passed = {check["context"] for check in status.get("statuses") or [] if check["status"] == "success"} + except (KeyError, TypeError, AttributeError): return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") - # Gitea reads a commit with no status as pending, with total_count 0. - if count == 0 or state == "success": - return None - if state != "pending": + if state not in ("pending", "success"): return Failure(f"a check on pull request {number} ended in {state}") + # Gitea reads a commit with no status as pending, with total_count 0. + if (count == 0 or state == "success") and required <= passed: + return None sleep(POLL_SECONDS) +def required_checks(base: str, run: Run) -> set[str] | Failure: + """The checks Gitea's protection of the branch base requires before a merge.""" + protections = gitea(run, "repos/{owner}/{repo}/branch_protections") + if isinstance(protections, Failure): + return protections + try: + return {context for rule in protections or [] if base in (rule.get("rule_name"), rule.get("branch_name")) and rule.get("enable_status_check") for context in rule.get("status_check_contexts") or []} + except (AttributeError, TypeError): + return Failure(f"tea api listed branch protections in a shape that can't be read: {str(protections)[:200]}") + + def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None: """Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head.""" if forge == "gh": diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 3016ebfe..794709a8 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -23,10 +23,13 @@ landed and changes are unreleased. The release names the version; the tool doesn titled `Cut release `, and pushes it as the branch release-. The clone's own checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main. 2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for - its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so + its checks where there are any, and merges it fast-forward only. On Gitea it also waits for + each check main's branch protection requires to report. GitHub has no fast-forward merge, so there it rebase-merges the branch, which is already on top of main. 3. It tags the merged commit v, annotated `Cut release `, pushes only the tag, - then moves to it as above. + deletes the branch on origin, then moves to it as above. A failed delete only warns. +It says on stderr as each step finishes, and ends stdout, after the changelog, with the line +`Done: v is cut and pushed, and is on it.` Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index cacc2c96..1a752c0a 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -4,6 +4,7 @@ import pathlib import subprocess import sys import tempfile +import typing import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -186,6 +187,8 @@ elif args[:2] in (["pulls", "create"], ["pr", "create"]): save() sys.exit("pull request already exists for these targets") state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"}) +elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/branch_protections"]: + print("[]") elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): checks = state["checks"] print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) @@ -356,9 +359,35 @@ class Cut(unittest.TestCase): self.assertIn("origin", ran.stderr) self.assertEqual(self.forge_state()["pulls"], []) - def test_says_which_pull_request_it_waits_for(self): + def test_says_as_each_step_finishes_and_ends_saying_the_release_is_cut_and_the_checkout_on_it(self): ran = self.cut() - self.assertIn("pull request 1", ran.stderr) + self.assert_cut(ran) + merged = self.origin_git("rev-parse", "main").strip() + self.assertEqual(ran.stderr.splitlines(), [ + "deploy-release: pushed the branch release-0.2.0", + "deploy-release: opened pull request 1", + "deploy-release: waiting for the checks of pull request 1", + "deploy-release: the checks of pull request 1 passed", + "deploy-release: merged pull request 1", + f"deploy-release: tagged {merged[:12]} v0.2.0", + "deploy-release: pushed the tag v0.2.0", + "deploy-release: deleted the branch release-0.2.0 on origin", + ]) + self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.") + + def test_deletes_the_merged_release_branch_on_origin(self): + self.assert_cut(self.cut()) + self.assertEqual(self.origin_git("branch", "--list", "release-0.2.0"), "") + + def test_only_warns_where_deleting_the_release_branch_fails(self): + hook = self.origin / "hooks" / "pre-receive" + hook.write_text("#!/bin/sh\nif grep -q '^[^ ]* 0000000000000000000000000000000000000000 refs/heads/'; then echo 'deletes are refused' >&2; exit 1; fi\n") + hook.chmod(0o755) + ran = self.cut() + self.assert_cut(ran) + self.assertIn("deploy-release: warning: the branch release-0.2.0 stays on origin:", ran.stderr) + self.assertIn("deletes are refused", ran.stderr) + self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.") def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self): self.git(self.clone, "switch", "-q", "-c", "side") @@ -443,18 +472,35 @@ class Cut(unittest.TestCase): self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0") +def tea(statuses: list[str], protections: str = "[]") -> typing.Callable[[list[str]], str]: + """A tea answering each read of the head's status with the next of statuses, and of the branch protections with protections.""" + answers = iter(statuses) + return lambda command: protections if command[-1].endswith("/branch_protections") else next(answers) + + +REQUIRED = '[{"rule_name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}]' + + class ChecksPassed(unittest.TestCase): def test_waits_on_tea_while_a_check_is_pending(self): - statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']) slept = [] - self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append)) + self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append)) self.assertEqual(slept, [POLL_SECONDS]) - def test_takes_a_commit_with_no_status_on_tea_as_passed(self): - self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', self.fail)) + def test_takes_a_commit_with_no_status_on_tea_as_passed_where_the_base_requires_none(self): + self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 0}']), self.fail)) + + def test_waits_on_tea_for_a_check_the_base_requires_until_it_reports_and_passes(self): + slept = [] + statuses = ['{"state": "pending", "total_count": 0, "statuses": []}', '{"state": "success", "total_count": 1, "statuses": [{"context": "lint", "status": "success"}]}', '{"state": "success", "total_count": 2, "statuses": [{"context": "lint", "status": "success"}, {"context": "CI / tests (pull_request)", "status": "success"}]}'] + self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(statuses, REQUIRED), slept.append)) + self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS]) + + def test_ignores_on_tea_a_protection_of_another_branch(self): + self.assertIsNone(checks_passed("tea", "1", "abc", "develop", tea(['{"state": "pending", "total_count": 0}'], REQUIRED), self.fail)) def test_fails_on_tea_where_a_check_failed(self): - self.assertIsInstance(checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', self.fail), Failure) + self.assertIsInstance(checks_passed("tea", "1", "abc", "main", tea(['{"state": "failure", "total_count": 1}']), self.fail), Failure) if __name__ == "__main__": -- 2.52.0 From 2348e9abac6dcb606714351d66661834e314b399 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:44:47 +0100 Subject: [PATCH 04/10] Quiet ci.sh's git and pip notices --- ci.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci.sh b/ci.sh index 3a291f75..7c45522b 100755 --- a/ci.sh +++ b/ci.sh @@ -5,8 +5,8 @@ set -eu cd "$(dirname "$0")" git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" -e HOME=/tmp python:3.14.8 sh -euc ' cat >/tmp/head.bundle - git clone --quiet /tmp/head.bundle /tmp/repo + git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle /tmp/repo cd /tmp/repo - python3 -m pip install --quiet --user uv==0.12.23 + 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 ' -- 2.52.0 From 73d77a0cf86f2ea1f4dd4043a195aa787d8bd026 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:48:36 +0100 Subject: [PATCH 05/10] Print a release's shell command patterns with command-patterns --- .gitignore | 3 + README.md | 3 +- bin/command-patterns | 9 ++ bin/command_patterns/__init__.py | 0 bin/command_patterns/main.py | 86 +++++++++++++ bin/command_patterns/tally.py | 87 +++++++++++++ bin/command_patterns/test_command_patterns.py | 115 ++++++++++++++++++ 7 files changed, 302 insertions(+), 1 deletion(-) create mode 100755 bin/command-patterns create mode 100644 bin/command_patterns/__init__.py create mode 100644 bin/command_patterns/main.py create mode 100644 bin/command_patterns/tally.py create mode 100644 bin/command_patterns/test_command_patterns.py diff --git a/.gitignore b/.gitignore index 71d16de6..be09e5f8 100644 --- a/.gitignore +++ b/.gitignore @@ -32,8 +32,11 @@ !bin/chunk_preflight/*.py !bin/claude_code/ !bin/claude_code/*.py +!bin/command-patterns !bin/command_lines/ !bin/command_lines/*.py +!bin/command_patterns/ +!bin/command_patterns/*.py !bin/deploy-release !bin/deploy_release/ !bin/deploy_release/*.py diff --git a/README.md b/README.md index ebe1a11e..ac89df2d 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `chunk-pr open|ready|merge` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; `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 []` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`: per pattern its chunks, calls, command and result tokens and tool time, for an audit of the release; `command-patterns --help` states the measure. - `deploy-release [--cut] []` 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 ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` 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. @@ -130,7 +131,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py `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` and `failure.py`. `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/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. -- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. +- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does. - `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). diff --git a/bin/command-patterns b/bin/command-patterns new file mode 100755 index 00000000..8ef9be01 --- /dev/null +++ b/bin/command-patterns @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from command_patterns import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/command_patterns/__init__.py b/bin/command_patterns/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/command_patterns/main.py b/bin/command_patterns/main.py new file mode 100644 index 00000000..43753f00 --- /dev/null +++ b/bin/command_patterns/main.py @@ -0,0 +1,86 @@ +"""Print a table of the shell command patterns a release's chunks ran, so an audit of the release reads one table. + +usage: command-patterns [] + +Run it inside a project checkout or one of its worktrees. It reads loop-claude's archive of the +project, as reading-cost does, and takes each chunk that finished in the release's window: after +the tag before v and up to v's own tag, by their tag dates. Without , it +takes the chunks finished since the newest v* tag, the release not yet cut. It reads the worker's +transcript and each subagent's. + +Each Bash call counts once, under the pattern of its first simple command other than `cd`: the +tool's name, then up to two words that read as subcommands, as in `tea pr create`. A word that +holds anything but lowercase letters, digits and dashes, such as an option or a path, ends the +pattern. Per pattern the table lists the chunks that ran it, its calls, the tokens of its commands +and of their results, estimated at four characters a token, and the seconds from each call to its +result, most calls first. + +Exit 1, saying why, on unknown arguments, a version no tag names, or when git cannot start or finds +no checkout, or the archive cannot be read. +""" +import os +import pathlib +import sys + +from command_patterns.tally import table, tally +from failure import Failure +from git_cli.git_repo import git +from records.utc_stamp import seconds +from transcript_archive.location import project_archive +from transcript_archive.read import finished_chunks, read_threads + +USAGE = "usage: command-patterns []" + + +def main(argv: list[str]) -> int: + if argv in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if len(argv) > 1 or argv[:1] and argv[0].startswith("-"): + print(f"command-patterns: unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) + return 1 + printed = report(argv[0] if argv else None) + if isinstance(printed, Failure): + print(f"command-patterns: {printed.reason}", file=sys.stderr) + return 1 + print(printed) + return 0 + + +def report(version: str | None) -> str | Failure: + common = git("rev-parse", "--path-format=absolute", "--git-common-dir") + if isinstance(common, Failure): + return common + # The common dir is the main checkout's .git, whichever worktree runs this, and the main checkout's path keys the archive. + main_root = str(pathlib.Path(common.strip()).parent) + bounds = window(version, main_root) + if isinstance(bounds, Failure): + return bounds + after, until = bounds + chunks = finished_chunks(project_archive(main_root, pathlib.Path.home(), os.environ)) + if isinstance(chunks, Failure): + return chunks + threads = [] + for chunk in chunks: + if (after is None or seconds(chunk.finished) > after) and (until is None or seconds(chunk.finished) <= until): + read = read_threads(chunk) + if isinstance(read, Failure): + return read + threads.append(read) + named = f"v{version}" if version else "the release not yet cut" + return f"Shell command patterns of {len(threads)} chunk{'' if len(threads) == 1 else 's'} in {named}:\n\n{table(tally(threads))}" + + +def window(version: str | None, cwd: str) -> tuple[int | None, int | None] | Failure: + """The release's window as tag dates in seconds since the epoch: after the tag before it, up to its own; None where it is open.""" + listed = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--sort=-v:refname", "--format=%(refname:short) %(creatordate:unix)", cwd=cwd) + if isinstance(listed, Failure): + return listed + tags = [(name, int(stamp)) for name, stamp in (line.split() for line in listed.splitlines())] + if version is None: + return (tags[0][1] if tags else None, None) + names = [name for name, _ in tags] + if f"v{version}" not in names: + return Failure(f"no tag v{version}; name a cut release, or none for the release not yet cut") + at = names.index(f"v{version}") + return (tags[at + 1][1] if at + 1 < len(tags) else None, tags[at][1]) diff --git a/bin/command_patterns/tally.py b/bin/command_patterns/tally.py new file mode 100644 index 00000000..1a109d3c --- /dev/null +++ b/bin/command_patterns/tally.py @@ -0,0 +1,87 @@ +"""Tally the shell calls of archived chunks by command pattern, such as `tea pr create`.""" +import dataclasses +import datetime +import posixpath +import re + +from claude_code.entries import AssistantTurn, parse_entry, ToolCall, ToolResults +from command_lines.shell_command import segments + +# A word that reads as a subcommand, such as `pr` in `tea pr create`; an option, a path or a number ends the pattern. +SUBCOMMAND = re.compile(r"[a-z][a-z0-9-]*") +# The words after the tool a pattern keeps at most. +SUBCOMMANDS = 2 +# Tokens are estimated from characters, at about four characters a token. +CHARACTERS_PER_TOKEN = 4 + + +@dataclasses.dataclass(frozen=True) +class Call: + command: str + result: str + seconds: float + + +@dataclasses.dataclass(frozen=True) +class Row: + pattern: str + chunks: int + calls: int + command_tokens: int + result_tokens: int + seconds: int + + +def pattern(command: str) -> str: + """The call's first simple command other than `cd`: its tool's name, then up to two subcommand words.""" + commands = segments(command) + for words in commands: + if words[0] != "cd": + kept = [] + for word in words[1:1 + SUBCOMMANDS]: + if not SUBCOMMAND.fullmatch(word): + break + kept.append(word) + return " ".join([posixpath.basename(words[0]), *kept]) + return "cd" if commands else "(unparsed)" + + +def calls(thread: bytes) -> list[Call]: + """Each Bash call in a transcript, with its result's text and the seconds until the result; a call without a result has an empty one, taking no time.""" + asked: dict[str, tuple[str, str]] = {} + answered: dict[str, tuple[str, str]] = {} + for line in thread.splitlines(): + entry = parse_entry(line) + if isinstance(entry, AssistantTurn): + for part in entry.parts: + if isinstance(part, ToolCall) and part.name == "Bash" and isinstance(command := part.input.get("command"), str): + asked.setdefault(part.id, (command, entry.timestamp)) + elif isinstance(entry, ToolResults): + # Claude Code logs some results twice; the first carries the time the tool ended. + for found in entry.results: + answered.setdefault(found.tool_use_id, (found.text, entry.timestamp)) + return [Call(command, answered.get(id, ("", ""))[0], elapsed(at, answered.get(id, ("", ""))[1])) for id, (command, at) in asked.items()] + + +def elapsed(start: str, end: str) -> float: + """Seconds from one transcript timestamp to another; 0 where either is missing or unreadable.""" + try: + return max(0.0, (datetime.datetime.fromisoformat(end) - datetime.datetime.fromisoformat(start)).total_seconds()) + except ValueError: + return 0.0 + + +def tally(chunks: list[list[bytes]]) -> list[Row]: + """One row per pattern over the chunks, each given as its threads, most calls first.""" + found: dict[str, list[tuple[int, Call]]] = {} + for index, threads in enumerate(chunks): + for thread in threads: + for each in calls(thread): + found.setdefault(pattern(each.command), []).append((index, each)) + rows = [Row(name, len({index for index, _ in made}), len(made), sum(len(each.command) for _, each in made) // CHARACTERS_PER_TOKEN, sum(len(each.result) for _, each in made) // CHARACTERS_PER_TOKEN, round(sum(each.seconds for _, each in made))) for name, made in found.items()] + return sorted(rows, key=lambda row: (-row.calls, row.pattern)) + + +def table(rows: list[Row]) -> str: + lines = ["| Pattern | Chunks | Calls | Command tokens | Result tokens | Tool seconds |", "|---|---|---|---|---|---|"] + return "\n".join([*lines, *(f"| {row.pattern} | {row.chunks} | {row.calls} | {row.command_tokens} | {row.result_tokens} | {row.seconds} |" for row in rows)]) diff --git a/bin/command_patterns/test_command_patterns.py b/bin/command_patterns/test_command_patterns.py new file mode 100644 index 00000000..d81c1810 --- /dev/null +++ b/bin/command_patterns/test_command_patterns.py @@ -0,0 +1,115 @@ +import json +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from command_patterns.tally import pattern, Row, tally +from test_env import isolated_env + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "command-patterns" + + +def call(id: str, command: str, at: str) -> str: + return json.dumps({"type": "assistant", "timestamp": at, "message": {"id": f"m-{id}", "content": [{"type": "tool_use", "id": id, "name": "Bash", "input": {"command": command}}]}}) + + +def result(id: str, text: str, at: str) -> str: + return json.dumps({"type": "user", "timestamp": at, "message": {"content": [{"type": "tool_result", "tool_use_id": id, "content": text}]}}) + + +def thread(*lines: str) -> bytes: + return ("\n".join(lines) + "\n").encode() + + +class Pattern(unittest.TestCase): + def test_names_the_tool_and_its_subcommands_as_in_tea_pr_create(self): + self.assertEqual(pattern("tea pr create --title t"), "tea pr create") + + def test_skips_a_leading_cd(self): + self.assertEqual(pattern("cd /x && git status --short"), "git status") + + def test_stops_at_the_first_option_or_path(self): + self.assertEqual(pattern("git -C /x status"), "git") + self.assertEqual(pattern("~/.claude/bin/run-heavy ./ci.sh"), "run-heavy") + + def test_takes_a_lone_cd_as_cd(self): + self.assertEqual(pattern("cd /x"), "cd") + + +class Tally(unittest.TestCase): + def test_counts_each_patterns_chunks_calls_tokens_and_tool_time(self): + first = [thread(call("a", "tea pr create --title t", "2026-11-01T10:00:00Z"), result("a", "x" * 400, "2026-11-01T10:00:03Z"), call("b", "git status", "2026-11-01T10:01:00Z"), result("b", "", "2026-11-01T10:01:01Z"))] + second = [thread(call("c", "tea pr create --title u", "2026-11-02T10:00:00Z"), result("c", "y" * 40, "2026-11-02T10:00:02Z")), thread(call("d", "tea pr create", "2026-11-02T11:00:00Z"))] + rows = tally([first, second]) + self.assertEqual(rows[0], Row("tea pr create", chunks=2, calls=3, command_tokens=(23 + 23 + 13) // 4, result_tokens=(400 + 40) // 4, seconds=5)) + self.assertEqual(rows[1], Row("git status", chunks=1, calls=1, command_tokens=10 // 4, result_tokens=0, seconds=1)) + + def test_counts_a_result_logged_twice_once(self): + rows = tally([[thread(call("a", "ls", "2026-11-01T10:00:00Z"), result("a", "abcd", "2026-11-01T10:00:01Z"), result("a", "abcd", "2026-11-01T10:00:09Z"))]]) + self.assertEqual(rows, [Row("ls", chunks=1, calls=1, command_tokens=0, result_tokens=1, seconds=1)]) + + +class Main(unittest.TestCase): + """A checkout tagged v0.1.0 at 2026-11-01 and v0.2.0 at 2026-11-05, and one archived chunk finished before, between and after them.""" + + def setUp(self): + self.home = pathlib.Path(os.path.realpath(tempfile.mkdtemp())) + self.addCleanup(subprocess.run, ["rm", "-rf", str(self.home)]) + self.checkout = self.home / "code" / "project" + self.checkout.mkdir(parents=True) + self.env = {**isolated_env(), "HOME": str(self.home), "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"} + self.git("init", "-q", "-b", "main") + self.git("commit", "-q", "--allow-empty", "-m", "Start") + self.tag("v0.1.0", "2026-11-01T00:00:00Z") + self.tag("v0.2.0", "2026-11-05T00:00:00Z") + archive = self.home / ".claude" / "loop-claude-transcripts" / "project" + for name, finished, command in (("before", "2026-10-30T00:00:00Z", "make old"), ("between", "2026-11-03T00:00:00Z", "tea pr create"), ("after", "2026-11-07T00:00:00Z", "gh pr view")): + folder = archive / name + folder.mkdir(parents=True) + (folder / "worker.jsonl").write_bytes(thread(call(name, command, finished), result(name, "ok", finished))) + (folder / "worker.outcomes.md").write_text(f"Task: t\n\n{finished} Verdict: finished\n") + + def git(self, *args: str, at: str | None = None) -> None: + subprocess.run(["git", *args], check=True, cwd=self.checkout, env={**self.env, **({"GIT_COMMITTER_DATE": at} if at else {})}, capture_output=True) + + def tag(self, name: str, at: str) -> None: + self.git("tag", "-a", "-m", name, name, at=at) + + def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) + + def test_reads_the_chunks_finished_since_the_newest_tag_by_default(self): + ran = self.run_tool() + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertIn("| gh pr view | 1 | 1 |", ran.stdout) + self.assertNotIn("tea pr create", ran.stdout) + self.assertIn("1 chunk", ran.stdout) + + def test_reads_the_chunks_finished_between_the_tag_before_a_release_and_its_own(self): + ran = self.run_tool("0.2.0") + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertIn("| tea pr create | 1 | 1 |", ran.stdout) + self.assertNotIn("make old", ran.stdout) + self.assertNotIn("gh pr view", ran.stdout) + + def test_reads_every_chunk_before_the_first_tag_for_the_first_release(self): + ran = self.run_tool("0.1.0") + self.assertIn("| make old | 1 | 1 |", ran.stdout) + self.assertNotIn("tea pr create", ran.stdout) + + def test_refuses_a_release_no_tag_names(self): + ran = self.run_tool("0.9.0") + self.assertEqual(ran.returncode, 1) + self.assertIn("v0.9.0", ran.stderr) + + def test_refuses_more_than_one_argument(self): + self.assertEqual(self.run_tool("0.1.0", "0.2.0").returncode, 1) + + +if __name__ == "__main__": + unittest.main() -- 2.52.0 From a88f74f5accb991dfaaabbf5d29ca0dac66e82c9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:50:26 +0100 Subject: [PATCH 06/10] Record CI and main's protection in the decisions, hold ci.sh's image to README's Python, and say so in README --- AGENTS.md | 3 ++- README.md | 2 ++ bin/command_patterns/main.py | 8 +++---- bin/command_patterns/test_command_patterns.py | 2 +- bin/repo_checks/test_ci.py | 22 +++++++++++++++++++ docs/decisions.md | 10 +++++++-- 6 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 bin/repo_checks/test_ci.py diff --git a/AGENTS.md b/AGENTS.md index ace1043f..4ea92660 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ Decisions live in `docs/decisions.md`: - bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names -- bin/: the tools and their tests run on the host's Python, with no container +- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI - bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers - chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone - comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release @@ -56,6 +56,7 @@ Decisions live in `docs/decisions.md`: - rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter - settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped - settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit +- tests: CI runs the suite through `ci.sh` on every pull request, in a pinned Python container, and `main`'s branch protection holds a merge until it passes - tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code - the repo may name bender, bender-infra and ai-sandbox - todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order diff --git a/README.md b/README.md index ac89df2d..09a66a49 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,8 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t 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'`. +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`. + To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start. ```ini diff --git a/bin/command_patterns/main.py b/bin/command_patterns/main.py index 43753f00..f1c46592 100644 --- a/bin/command_patterns/main.py +++ b/bin/command_patterns/main.py @@ -22,12 +22,12 @@ import os import pathlib import sys -from command_patterns.tally import table, tally from failure import Failure -from git_cli.git_repo import git -from records.utc_stamp import seconds -from transcript_archive.location import project_archive from transcript_archive.read import finished_chunks, read_threads +from git_cli.git_repo import git +from transcript_archive.location import project_archive +from records.utc_stamp import seconds +from command_patterns.tally import table, tally USAGE = "usage: command-patterns []" diff --git a/bin/command_patterns/test_command_patterns.py b/bin/command_patterns/test_command_patterns.py index d81c1810..5255f96f 100644 --- a/bin/command_patterns/test_command_patterns.py +++ b/bin/command_patterns/test_command_patterns.py @@ -8,8 +8,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from command_patterns.tally import pattern, Row, tally from test_env import isolated_env +from command_patterns.tally import pattern, Row, tally TOOL = pathlib.Path(__file__).resolve().parents[1] / "command-patterns" diff --git a/bin/repo_checks/test_ci.py b/bin/repo_checks/test_ci.py new file mode 100644 index 00000000..e2b0f8b4 --- /dev/null +++ b/bin/repo_checks/test_ci.py @@ -0,0 +1,22 @@ +import pathlib +import re +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from repo_checks import ROOT +from repo_checks.test_types import SUPPORTED + + +class Ci(unittest.TestCase): + def test_ci_runs_the_python_readme_install_names(self): + image = re.search(r"python:(3\.\d+)\.\d+", (ROOT / "ci.sh").read_text(encoding="utf-8")) + supported = SUPPORTED.search((ROOT / "README.md").read_text(encoding="utf-8")) + self.assertIsNotNone(image, "ci.sh runs a python:3.N.P image") + self.assertIsNotNone(supported, "README.md's Install names `the latest stable Python, today 3.N`") + self.assertEqual(image.group(1), supported.group(1), "ci.sh's image follows the Python README.md's Install names") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md index e8817dea..06221315 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,9 +10,9 @@ Valid while the archive's file names, the Vocabulary and the panel keep these words. -## bin/: the tools and their tests run on the host's Python, with no container +## bin/: the tools run on the host's Python, with no container, and so do their tests outside CI -2026-09-24, larv-review. Serves goals 1 and 2. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. Valid while claude runs on the host. +2026-09-24, larv-review. Serves goals 1 and 2. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. CI alone runs them in a container, which drives no claude (the `tests:` entry on CI). Valid while claude runs on the host. ## bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers @@ -426,6 +426,12 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc 2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and loop-claude picks each project's model in `~/.claude/loop-claude-models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`. +## tests: CI runs the suite through `ci.sh` on every pull request, in a pinned Python container, and `main`'s branch protection holds a merge until it passes + +2026-11-09, larv-review, through todo item 12. Serves goal 1.1: a merge no longer rests on the worker's word. larv-review's gate was the local run alone, which it skips when the last stability round left the suite green, so an unattended chunk could merge on the worker's own report. gitea.larvit.se's runners labelled `docker-host` run `.gitea/workflows/ci.yml`, which runs `ci.sh`: it pipes the committed HEAD as a git bundle into `python:3.14.8` and runs README's Test line there as a non-root user, so the tests root skips run too. A bundle, not a bind mount, works whether or not the runner shares the docker daemon's filesystem. A run takes about 3 minutes. `test_ci.py` holds the image to the Python README Install names. + +The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override; a rule check added to CI would need one. Valid while gitea.larvit.se runs a runner labelled `docker-host`. + ## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code 2026-10-16, lilleman asked for research on what makes tests valuable, then for these changes; claude drafted them. Serves goal 1.1, since a test that cannot catch a bug, or breaks without one, lowers quality and costs review rounds. -- 2.52.0 From a2390754f3989a4ecb9edfc261e5f8f3eeace929 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 02:51:24 +0100 Subject: [PATCH 07/10] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20nothing=20t?= =?UTF-8?q?o=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From d62857f20ef2174c8356449bf057923f5ebe8260 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 03:05:11 +0100 Subject: [PATCH 08/10] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20name=20t?= =?UTF-8?q?he=20checks=20main=20requires=20in=20the=20waiting=20line,=20gi?= =?UTF-8?q?ve=20up=20after=2030=20minutes=20naming=20a=20required=20check?= =?UTF-8?q?=20that=20never=20passed,=20and=20match=20a=20required=20check?= =?UTF-8?q?=20as=20Gitea's=20glob;=20stability's=20branch-endpoint=20fix?= =?UTF-8?q?=20and=20prose's=20'to=20the=20tag'=20ride=20along?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/deploy_release/cut.py | 7 ++- bin/deploy_release/forge.py | 53 +++++++++++++--------- bin/deploy_release/main.py | 5 ++- bin/deploy_release/test_deploy_release.py | 54 ++++++++++++++++------- docs/decisions.md | 2 +- 5 files changed, 79 insertions(+), 42 deletions(-) diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index c156d90a..b765680e 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -169,8 +169,11 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: said(f"opened pull request {number}") if isinstance(number, Failure): return number - said(f"waiting for the checks of pull request {number}") - if isinstance(passed := forge.checks_passed(on, number, head, base, run), Failure): + required = forge.required_checks(on, base, run) + if isinstance(required, Failure): + return required + said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else "")) + if isinstance(passed := forge.checks_passed(on, number, head, required, run), Failure): return passed said(f"the checks of pull request {number} passed") if isinstance(merged := forge.merge(on, number, head, run), Failure): diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 1237416d..cb94b0f1 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -2,6 +2,7 @@ Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged. """ +import fnmatch import json import subprocess import time @@ -12,6 +13,8 @@ from chunk_preflight.choices import Forge # How long the cut waits between two reads of the head commit's status on Gitea. POLL_SECONDS = 10 +# How long the cut waits for the checks before it gives up; CI took about 3 minutes in 2026-11. +WAIT_SECONDS = 30 * 60 # Runs a command in the clone: what it printed, or a Failure with its reason. Run = typing.Callable[[list[str]], str | Failure] @@ -68,45 +71,51 @@ def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> F return created if isinstance(created, Failure) else None -def checks_passed(forge: Forge, number: str, head: str, base: 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. +def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure: + """The checks, or glob patterns of checks, that the forge's protection of the branch base requires before a merge. None on GitHub, where gh's watch covers them. - On Gitea it also waits for each check the protection of base requires to report: a check CI has yet to queue is no status at all. + Gitea answers a branch with the protection rule it applies there, so the cut never picks among the rules itself. + """ + if forge == "gh": + return set() + branch = gitea(run, f"repos/{{owner}}/{{repo}}/branches/{base}") + if isinstance(branch, Failure): + return branch + try: + return set(branch.get("status_check_contexts") or []) if branch.get("enable_status_check") else set() + except (AttributeError, TypeError): + 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. + + 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 return None - required = required_checks(base, run) - if isinstance(required, Failure): - return required - while True: + for _ in range(WAIT_SECONDS // POLL_SECONDS + 1): status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") if isinstance(status, Failure): return status try: count, state = status["total_count"], status["state"] - passed = {check["context"] for check in status.get("statuses") or [] if check["status"] == "success"} + passed = [check["context"] for check in status.get("statuses") or [] if check["status"] == "success"] except (KeyError, TypeError, AttributeError): return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") if state not in ("pending", "success"): return Failure(f"a check on pull request {number} ended in {state}") - # Gitea reads a commit with no status as pending, with total_count 0. - if (count == 0 or state == "success") and required <= passed: + # 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: return None - sleep(POLL_SECONDS) - - -def required_checks(base: str, run: Run) -> set[str] | Failure: - """The checks Gitea's protection of the branch base requires before a merge.""" - protections = gitea(run, "repos/{owner}/{repo}/branch_protections") - if isinstance(protections, Failure): - return protections - try: - return {context for rule in protections or [] if base in (rule.get("rule_name"), rule.get("branch_name")) and rule.get("enable_status_check") for context in rule.get("status_check_contexts") or []} - except (AttributeError, TypeError): - return Failure(f"tea api listed branch protections in a shape that can't be read: {str(protections)[:200]}") + if _ < WAIT_SECONDS // POLL_SECONDS: + sleep(POLL_SECONDS) + waited_on = f"{', '.join(missing)}, which the protection requires, never passed" if missing else "a check is still pending" + return Failure(f"gave up on pull request {number} after {WAIT_SECONDS // 60} minutes: {waited_on}") def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None: diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 794709a8..cd85a141 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -24,10 +24,11 @@ landed and changes are unreleased. The release names the version; the tool doesn checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main. 2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for its checks where there are any, and merges it fast-forward only. On Gitea it also waits for - each check main's branch protection requires to report. GitHub has no fast-forward merge, so + each check main's branch protection requires to report, and names them. It gives up after 30 + minutes, naming any required check that never passed. GitHub has no fast-forward merge, so there it rebase-merges the branch, which is already on top of main. 3. It tags the merged commit v, annotated `Cut release `, pushes only the tag, - deletes the branch on origin, then moves to it as above. A failed delete only warns. + deletes the branch on origin, then moves to the tag as above. A failed delete only warns. It says on stderr as each step finishes, and ends stdout, after the changelog, with the line `Done: v is cut and pushed, and is on it.` Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 1a752c0a..cfd92ad8 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -3,13 +3,14 @@ import os import pathlib import subprocess import sys +import itertools import tempfile import typing import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from deploy_release.forge import checks_passed, POLL_SECONDS +from deploy_release.forge import checks_passed, POLL_SECONDS, required_checks, WAIT_SECONDS from failure import Failure from test_env import isolated_env @@ -187,11 +188,11 @@ elif args[:2] in (["pulls", "create"], ["pr", "create"]): save() sys.exit("pull request already exists for these targets") state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"}) -elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/branch_protections"]: - print("[]") +elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/branches/main"]: + print(json.dumps(state.get("branch", {"name": "main"}))) elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): checks = state["checks"] - print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) + print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1, "statuses": [] if checks == "none" else [{"context": "CI / tests (pull_request)", "status": checks}]})) elif forge == "gh" and args[:2] == ["pr", "checks"]: if state["checks"] == "none": save() @@ -360,13 +361,14 @@ class Cut(unittest.TestCase): self.assertEqual(self.forge_state()["pulls"], []) def test_says_as_each_step_finishes_and_ends_saying_the_release_is_cut_and_the_checkout_on_it(self): + self.forge_state({**self.forge_state(), "checks": "success", "branch": json.loads(REQUIRED)}) ran = self.cut() self.assert_cut(ran) merged = self.origin_git("rev-parse", "main").strip() self.assertEqual(ran.stderr.splitlines(), [ "deploy-release: pushed the branch release-0.2.0", "deploy-release: opened pull request 1", - "deploy-release: waiting for the checks of pull request 1", + "deploy-release: waiting for the checks of pull request 1; main requires CI / tests (pull_request)", "deploy-release: the checks of pull request 1 passed", "deploy-release: merged pull request 1", f"deploy-release: tagged {merged[:12]} v0.2.0", @@ -472,35 +474,57 @@ class Cut(unittest.TestCase): self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0") -def tea(statuses: list[str], protections: str = "[]") -> typing.Callable[[list[str]], str]: - """A tea answering each read of the head's status with the next of statuses, and of the branch protections with protections.""" +def tea(statuses: typing.Iterable[str], branch: str = '{"name": "main"}') -> typing.Callable[[list[str]], str]: + """A tea answering each read of the head's status with the next of statuses, and of branch main with branch.""" answers = iter(statuses) - return lambda command: protections if command[-1].endswith("/branch_protections") else next(answers) + return lambda command: branch if command[-1] == "repos/{owner}/{repo}/branches/main" else next(answers) -REQUIRED = '[{"rule_name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}]' +REQUIRED = '{"name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}' + + +class RequiredChecks(unittest.TestCase): + def test_reads_on_tea_the_checks_the_protection_of_the_base_requires(self): + self.assertEqual(required_checks("tea", "main", tea([], REQUIRED)), {"CI / tests (pull_request)"}) + + def test_reads_none_on_tea_where_the_protection_turns_status_checks_off(self): + self.assertEqual(required_checks("tea", "main", tea([], '{"name": "main", "enable_status_check": false, "status_check_contexts": ["CI / tests (pull_request)"]}')), set()) + + def test_fails_on_tea_where_the_branch_reads_in_another_shape(self): + self.assertIsInstance(required_checks("tea", "main", tea([], "[]")), Failure) + + def test_reads_none_on_github_whose_watch_covers_them(self): + self.assertEqual(required_checks("gh", "main", self.fail), set()) class ChecksPassed(unittest.TestCase): def test_waits_on_tea_while_a_check_is_pending(self): slept = [] - self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append)) + self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append)) self.assertEqual(slept, [POLL_SECONDS]) def test_takes_a_commit_with_no_status_on_tea_as_passed_where_the_base_requires_none(self): - self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 0}']), self.fail)) + self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 0}']), self.fail)) def test_waits_on_tea_for_a_check_the_base_requires_until_it_reports_and_passes(self): slept = [] statuses = ['{"state": "pending", "total_count": 0, "statuses": []}', '{"state": "success", "total_count": 1, "statuses": [{"context": "lint", "status": "success"}]}', '{"state": "success", "total_count": 2, "statuses": [{"context": "lint", "status": "success"}, {"context": "CI / tests (pull_request)", "status": "success"}]}'] - self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(statuses, REQUIRED), slept.append)) + self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / tests (pull_request)"}, tea(statuses), slept.append)) self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS]) - def test_ignores_on_tea_a_protection_of_another_branch(self): - self.assertIsNone(checks_passed("tea", "1", "abc", "develop", tea(['{"state": "pending", "total_count": 0}'], REQUIRED), self.fail)) + def test_takes_on_tea_a_required_glob_as_met_by_a_check_it_matches(self): + passed = '{"state": "success", "total_count": 1, "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]}' + self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / *"}, tea([passed]), self.fail)) + + def test_gives_up_on_tea_after_the_wait_naming_a_required_check_that_never_reported(self): + slept = [] + waited = checks_passed("tea", "1", "abc", {"CI / tests (pull_request)"}, tea(itertools.repeat('{"state": "pending", "total_count": 0, "statuses": []}')), slept.append) + self.assertIsInstance(waited, Failure) + self.assertIn("CI / tests (pull_request)", waited.reason) + self.assertEqual(sum(slept), WAIT_SECONDS) def test_fails_on_tea_where_a_check_failed(self): - self.assertIsInstance(checks_passed("tea", "1", "abc", "main", tea(['{"state": "failure", "total_count": 1}']), self.fail), Failure) + self.assertIsInstance(checks_passed("tea", "1", "abc", set(), tea(['{"state": "failure", "total_count": 1}']), self.fail), Failure) if __name__ == "__main__": diff --git a/docs/decisions.md b/docs/decisions.md index 06221315..98464814 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -430,7 +430,7 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc 2026-11-09, larv-review, through todo item 12. Serves goal 1.1: a merge no longer rests on the worker's word. larv-review's gate was the local run alone, which it skips when the last stability round left the suite green, so an unattended chunk could merge on the worker's own report. gitea.larvit.se's runners labelled `docker-host` run `.gitea/workflows/ci.yml`, which runs `ci.sh`: it pipes the committed HEAD as a git bundle into `python:3.14.8` and runs README's Test line there as a non-root user, so the tests root skips run too. A bundle, not a bind mount, works whether or not the runner shares the docker daemon's filesystem. A run takes about 3 minutes. `test_ci.py` holds the image to the Python README Install names. -The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override; a rule check added to CI would need one. Valid while gitea.larvit.se runs a runner labelled `docker-host`. +The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override; a rule check added to CI would need one. Valid while gitea.larvit.se runs a runner labelled `docker-host`. ## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code -- 2.52.0 From 6e95eb146d4aa45a8ddfcb2ecaf59d82e73c1154 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 03:09:41 +0100 Subject: [PATCH 09/10] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20test=20the?= =?UTF-8?q?=20two-subcommand=20cap,=20an=20unparsed=20command,=20an=20unev?= =?UTF-8?q?en=20token=20sum=20and=20a=20zero-second=20call,=20assert=20eac?= =?UTF-8?q?h=20progress=20line's=20facts=20in=20order,=20and=20say=20in=20?= =?UTF-8?q?ci.sh=20why=20it=20is=20sh;=20the=20branch=20endpoint=20landed?= =?UTF-8?q?=20with=20product-owner's=20answer,=20and=20the=20help=20now=20?= =?UTF-8?q?says=20the=20highest=20tag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/command_patterns/test_command_patterns.py | 25 ++++++++++++++----- bin/deploy_release/test_deploy_release.py | 20 +++++++-------- ci.sh | 3 ++- 3 files changed, 30 insertions(+), 18 deletions(-) diff --git a/bin/command_patterns/test_command_patterns.py b/bin/command_patterns/test_command_patterns.py index 5255f96f..4532cbfa 100644 --- a/bin/command_patterns/test_command_patterns.py +++ b/bin/command_patterns/test_command_patterns.py @@ -37,17 +37,23 @@ class Pattern(unittest.TestCase): self.assertEqual(pattern("git -C /x status"), "git") self.assertEqual(pattern("~/.claude/bin/run-heavy ./ci.sh"), "run-heavy") + def test_keeps_two_subcommands_at_most(self): + self.assertEqual(pattern("git remote add origin x"), "git remote add") + + def test_names_a_command_it_cannot_parse_unparsed(self): + self.assertEqual(pattern('echo "unclosed'), "(unparsed)") + def test_takes_a_lone_cd_as_cd(self): self.assertEqual(pattern("cd /x"), "cd") class Tally(unittest.TestCase): def test_counts_each_patterns_chunks_calls_tokens_and_tool_time(self): - first = [thread(call("a", "tea pr create --title t", "2026-11-01T10:00:00Z"), result("a", "x" * 400, "2026-11-01T10:00:03Z"), call("b", "git status", "2026-11-01T10:01:00Z"), result("b", "", "2026-11-01T10:01:01Z"))] + first = [thread(call("a", "tea pr create --title t", "2026-11-01T10:00:00Z"), result("a", "x" * 401, "2026-11-01T10:00:03Z"), call("b", "git status", "2026-11-01T10:01:00Z"), result("b", "", "2026-11-01T10:01:00Z"))] second = [thread(call("c", "tea pr create --title u", "2026-11-02T10:00:00Z"), result("c", "y" * 40, "2026-11-02T10:00:02Z")), thread(call("d", "tea pr create", "2026-11-02T11:00:00Z"))] rows = tally([first, second]) - self.assertEqual(rows[0], Row("tea pr create", chunks=2, calls=3, command_tokens=(23 + 23 + 13) // 4, result_tokens=(400 + 40) // 4, seconds=5)) - self.assertEqual(rows[1], Row("git status", chunks=1, calls=1, command_tokens=10 // 4, result_tokens=0, seconds=1)) + self.assertEqual(rows[0], Row("tea pr create", chunks=2, calls=3, command_tokens=(23 + 23 + 13) // 4, result_tokens=(401 + 40) // 4, seconds=5)) + self.assertEqual(rows[1], Row("git status", chunks=1, calls=1, command_tokens=10 // 4, result_tokens=0, seconds=0)) def test_counts_a_result_logged_twice_once(self): rows = tally([[thread(call("a", "ls", "2026-11-01T10:00:00Z"), result("a", "abcd", "2026-11-01T10:00:01Z"), result("a", "abcd", "2026-11-01T10:00:09Z"))]]) @@ -55,7 +61,7 @@ class Tally(unittest.TestCase): class Main(unittest.TestCase): - """A checkout tagged v0.1.0 at 2026-11-01 and v0.2.0 at 2026-11-05, and one archived chunk finished before, between and after them.""" + """A checkout tagged v0.1.0 at 2026-11-01 and v0.2.0 at 2026-11-05, and three archived chunks, finished before, between and after them.""" def setUp(self): self.home = pathlib.Path(os.path.realpath(tempfile.mkdtemp())) @@ -107,8 +113,15 @@ class Main(unittest.TestCase): self.assertEqual(ran.returncode, 1) self.assertIn("v0.9.0", ran.stderr) - def test_refuses_more_than_one_argument(self): - self.assertEqual(self.run_tool("0.1.0", "0.2.0").returncode, 1) + def test_refuses_more_than_one_version(self): + ran = self.run_tool("0.1.0", "0.2.0") + self.assertEqual(ran.returncode, 1) + self.assertIn("one version at most", ran.stderr) + + def test_refuses_an_unknown_option(self): + ran = self.run_tool("--all") + self.assertEqual(ran.returncode, 1) + self.assertIn("unknown option", ran.stderr) if __name__ == "__main__": diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index cfd92ad8..008bd0f2 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,9 +1,9 @@ +import itertools import json import os import pathlib import subprocess import sys -import itertools import tempfile import typing import unittest @@ -365,16 +365,14 @@ class Cut(unittest.TestCase): ran = self.cut() self.assert_cut(ran) merged = self.origin_git("rev-parse", "main").strip() - self.assertEqual(ran.stderr.splitlines(), [ - "deploy-release: pushed the branch release-0.2.0", - "deploy-release: opened pull request 1", - "deploy-release: waiting for the checks of pull request 1; main requires CI / tests (pull_request)", - "deploy-release: the checks of pull request 1 passed", - "deploy-release: merged pull request 1", - f"deploy-release: tagged {merged[:12]} v0.2.0", - "deploy-release: pushed the tag v0.2.0", - "deploy-release: deleted the branch release-0.2.0 on origin", - ]) + # Each step's line, in order, with the facts it must name. + steps = [("pushed", "release-0.2.0"), ("opened", "1"), ("waiting", "1", "CI / tests (pull_request)"), ("passed", "1"), ("merged", "1"), ("tagged", merged[:12], "v0.2.0"), ("pushed", "v0.2.0"), ("deleted", "release-0.2.0")] + lines = ran.stderr.splitlines() + self.assertEqual(len(lines), len(steps), ran.stderr) + for line, facts in zip(lines, steps): + self.assertTrue(line.startswith("deploy-release: "), line) + for fact in facts: + self.assertIn(fact, line) self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.") def test_deletes_the_merged_release_branch_on_origin(self): diff --git a/ci.sh b/ci.sh index 7c45522b..08ba6a5f 100755 --- a/ci.sh +++ b/ci.sh @@ -1,5 +1,6 @@ #!/bin/sh -# Runs the test suite on the committed HEAD as CI does: in a pinned Python container, as the caller's uid, so the tests root skips run too. +# Runs the test suite on the committed HEAD as CI does: in a pinned Python container, as the caller's uid, so the tests that skip under root still run. +# It is sh, not Python, since it runs on the CI runner's host, which needs only git and docker. # The repo goes in as a git bundle rather than a bind mount, so the script works whether the CI runner shares the docker daemon's filesystem or not. set -eu cd "$(dirname "$0")" -- 2.52.0 From da4d376136781a763b0300c96dc8f6606d2df00b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 9 Nov 2026 03:09:41 +0100 Subject: [PATCH 10/10] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20define=20a?= =?UTF-8?q?=20subcommand=20word=20in=20command-patterns'=20help=20and=20sp?= =?UTF-8?q?lit=20its=20table=20sentence,=20point=20the=20bin/=20decision?= =?UTF-8?q?=20at=20the=20CI=20entry=20by=20name,=20leave=20ci.sh's=20pinne?= =?UTF-8?q?d=20details=20to=20its=20header,=20say=20what=20a=20CI=20rule?= =?UTF-8?q?=20check=20needs,=20and=20split=20the=20two=20argument=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitea/workflows/ci.yml | 2 +- README.md | 2 +- bin/command_patterns/main.py | 25 +++++++++++++++---------- bin/command_patterns/tally.py | 3 +-- docs/decisions.md | 6 +++--- 5 files changed, 21 insertions(+), 17 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 164d5ec0..417e0a8b 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -7,5 +7,5 @@ jobs: steps: - uses: actions/checkout@v7.0.1 with: - fetch-depth: 0 # ci.sh bundles HEAD, which a shallow clone can't + fetch-depth: 0 # ci.sh bundles HEAD, which fails in a shallow clone - run: sh ci.sh diff --git a/README.md b/README.md index 09a66a49..5cb40f11 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `chunk-pr open|ready|merge` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; `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 []` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`: per pattern its chunks, calls, command and result tokens and tool time, for an audit of the release; `command-patterns --help` states the measure. +- `command-patterns []` 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; `command-patterns --help` states its columns. - `deploy-release [--cut] []` 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 ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` 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. diff --git a/bin/command_patterns/main.py b/bin/command_patterns/main.py index f1c46592..3937ba40 100644 --- a/bin/command_patterns/main.py +++ b/bin/command_patterns/main.py @@ -1,19 +1,21 @@ -"""Print a table of the shell command patterns a release's chunks ran, so an audit of the release reads one table. +"""Print a table of the shell command patterns a release's chunks ran. usage: command-patterns [] Run it inside a project checkout or one of its worktrees. It reads loop-claude's archive of the project, as reading-cost does, and takes each chunk that finished in the release's window: after the tag before v and up to v's own tag, by their tag dates. Without , it -takes the chunks finished since the newest v* tag, the release not yet cut. It reads the worker's +takes the chunks finished since the highest v* tag, the release not yet cut. It reads the worker's transcript and each subagent's. Each Bash call counts once, under the pattern of its first simple command other than `cd`: the -tool's name, then up to two words that read as subcommands, as in `tea pr create`. A word that -holds anything but lowercase letters, digits and dashes, such as an option or a path, ends the -pattern. Per pattern the table lists the chunks that ran it, its calls, the tokens of its commands -and of their results, estimated at four characters a token, and the seconds from each call to its -result, most calls first. +tool's name, then up to two words that read as subcommands, as in `tea pr create`. A subcommand +starts with a lowercase letter and holds only lowercase letters, digits and dashes; any other word, +such as an option, a path or a number, ends the pattern. + +The table has one row per pattern, most calls first. Its columns are the chunks that ran the +pattern, its calls, and the tokens of its commands and of their results. Tokens are estimated at +four characters each. The last column sums the seconds from each call to its result. Exit 1, saying why, on unknown arguments, a version no tag names, or when git cannot start or finds no checkout, or the archive cannot be read. @@ -36,8 +38,11 @@ def main(argv: list[str]) -> int: if argv in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - if len(argv) > 1 or argv[:1] and argv[0].startswith("-"): - print(f"command-patterns: unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) + if any(word.startswith("-") for word in argv): + print(f"command-patterns: unknown option in {' '.join(argv)}; {USAGE}", file=sys.stderr) + return 1 + if len(argv) > 1: + print(f"command-patterns: takes one version at most, not {' '.join(argv)}; {USAGE}", file=sys.stderr) return 1 printed = report(argv[0] if argv else None) if isinstance(printed, Failure): @@ -81,6 +86,6 @@ def window(version: str | None, cwd: str) -> tuple[int | None, int | None] | Fai return (tags[0][1] if tags else None, None) names = [name for name, _ in tags] if f"v{version}" not in names: - return Failure(f"no tag v{version}; name a cut release, or none for the release not yet cut") + return Failure(f"no tag v{version}; name a cut release, or give no version for the release not yet cut") at = names.index(f"v{version}") return (tags[at + 1][1] if at + 1 < len(tags) else None, tags[at][1]) diff --git a/bin/command_patterns/tally.py b/bin/command_patterns/tally.py index 1a109d3c..580c8828 100644 --- a/bin/command_patterns/tally.py +++ b/bin/command_patterns/tally.py @@ -7,11 +7,10 @@ import re from claude_code.entries import AssistantTurn, parse_entry, ToolCall, ToolResults from command_lines.shell_command import segments -# A word that reads as a subcommand, such as `pr` in `tea pr create`; an option, a path or a number ends the pattern. +# A subcommand word, such as `pr` in `tea pr create`. Any other word ends the pattern. SUBCOMMAND = re.compile(r"[a-z][a-z0-9-]*") # The words after the tool a pattern keeps at most. SUBCOMMANDS = 2 -# Tokens are estimated from characters, at about four characters a token. CHARACTERS_PER_TOKEN = 4 diff --git a/docs/decisions.md b/docs/decisions.md index 98464814..8c7eb2c6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -12,7 +12,7 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo ## bin/: the tools run on the host's Python, with no container, and so do their tests outside CI -2026-09-24, larv-review. Serves goals 1 and 2. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. CI alone runs them in a container, which drives no claude (the `tests:` entry on CI). Valid while claude runs on the host. +2026-09-24, larv-review. Serves goals 1 and 2. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. The tests also run in a container through `ci.sh`, on CI and to reproduce a CI failure, since they drive no claude (the entry `tests: CI runs the suite through ci.sh`). Valid while claude runs on the host. ## bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers @@ -428,9 +428,9 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc ## tests: CI runs the suite through `ci.sh` on every pull request, in a pinned Python container, and `main`'s branch protection holds a merge until it passes -2026-11-09, larv-review, through todo item 12. Serves goal 1.1: a merge no longer rests on the worker's word. larv-review's gate was the local run alone, which it skips when the last stability round left the suite green, so an unattended chunk could merge on the worker's own report. gitea.larvit.se's runners labelled `docker-host` run `.gitea/workflows/ci.yml`, which runs `ci.sh`: it pipes the committed HEAD as a git bundle into `python:3.14.8` and runs README's Test line there as a non-root user, so the tests root skips run too. A bundle, not a bind mount, works whether or not the runner shares the docker daemon's filesystem. A run takes about 3 minutes. `test_ci.py` holds the image to the Python README Install names. +2026-11-09, larv-review, through todo item 12. Serves goal 1.1: a merge no longer rests on the worker's word. larv-review's gate was the local run alone, which it skips when the last stability round left the suite green, so an unattended chunk could merge on the worker's own report. gitea.larvit.se's runners labelled `docker-host` run `.gitea/workflows/ci.yml`, which runs `ci.sh` on the committed HEAD in a pinned Python container; the script's header says how. A run takes about 3 minutes. -The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override; a rule check added to CI would need one. Valid while gitea.larvit.se runs a runner labelled `docker-host`. +The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override. Whoever adds a rule check to CI must also let it read the PR body's `rule-override`. Valid while gitea.larvit.se runs a runner labelled `docker-host`. ## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code -- 2.52.0