diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 00000000..417e0a8b --- /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 fails in a shallow clone + - run: sh ci.sh diff --git a/.gitignore b/.gitignore index a368caed..be09e5f8 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/ @@ -28,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/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 ebe1a11e..5cb40f11 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`, 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. @@ -114,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 @@ -130,7 +133,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..3937ba40 --- /dev/null +++ b/bin/command_patterns/main.py @@ -0,0 +1,91 @@ +"""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 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 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. +""" +import os +import pathlib +import sys + +from failure import Failure +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 []" + + +def main(argv: list[str]) -> int: + if argv in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + 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): + 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 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 new file mode 100644 index 00000000..580c8828 --- /dev/null +++ b/bin/command_patterns/tally.py @@ -0,0 +1,86 @@ +"""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 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 +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..4532cbfa --- /dev/null +++ b/bin/command_patterns/test_command_patterns.py @@ -0,0 +1,128 @@ +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 test_env import isolated_env +from command_patterns.tally import pattern, Row, tally + +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_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" * 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=(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"))]]) + 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 three archived chunks, 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_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__": + unittest.main() diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 1e1d5d2c..b765680e 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,21 @@ 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): + 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 - 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..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,27 +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, 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. + + 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 - 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"] - 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}") - sleep(POLL_SECONDS) + # 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 + 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 3016ebfe..cd85a141 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -23,10 +23,14 @@ 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, 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, - then moves to it as above. + 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 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..008bd0f2 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,14 +1,16 @@ +import itertools import json import os import pathlib import subprocess import sys 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 @@ -186,9 +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}/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() @@ -356,9 +360,34 @@ 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): + self.forge_state({**self.forge_state(), "checks": "success", "branch": json.loads(REQUIRED)}) ran = self.cut() - self.assertIn("pull request 1", ran.stderr) + self.assert_cut(ran) + merged = self.origin_git("rev-parse", "main").strip() + # 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): + 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,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: 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: branch if command[-1] == "repos/{owner}/{repo}/branches/main" else next(answers) + + +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): - 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", 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(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", 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", {"CI / tests (pull_request)"}, tea(statuses), slept.append)) + self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS]) + + 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", lambda command: '{"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/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/ci.sh b/ci.sh new file mode 100755 index 00000000..08ba6a5f --- /dev/null +++ b/ci.sh @@ -0,0 +1,13 @@ +#!/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 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")" +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 -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 +' diff --git a/docs/decisions.md b/docs/decisions.md index e8817dea..8c7eb2c6 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. 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 @@ -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` on the committed HEAD in a pinned Python container; the script's header says how. A run takes about 3 minutes. + +The protection lives in Gitea's settings, outside the repo: rule `main`, required status check `CI / tests (pull_request)`. A pull request has no status until CI queues its run, so `deploy-release --cut` waits for each check the protection requires rather than reading no status as no checks, for 30 minutes at most. CI runs no rule-hook check, so a `rule-override` in the PR body has nothing to override. Whoever adds a rule check to CI must also let it read the PR body's `rule-override`. Valid while gitea.larvit.se runs a runner labelled `docker-host`. + ## 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. 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