From 4b5b306bd5889484592731fc6144358ac029107c Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:10:59 +0000 Subject: [PATCH 01/49] docs(contributing): the checklist a reviewer of a change follows What a read-only reviewer checks, in order, against the section of AGENTS.md that owns each rule; the question of silent acceptance; and how a finding and a report are written. Co-Authored-By: Claude Opus 5.5 --- docs/contributing/review-checklist.md | 107 ++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 docs/contributing/review-checklist.md diff --git a/docs/contributing/review-checklist.md b/docs/contributing/review-checklist.md new file mode 100644 index 00000000..54683ecd --- /dev/null +++ b/docs/contributing/review-checklist.md @@ -0,0 +1,107 @@ +# Review checklist + +What a reviewer of a change to this repository checks, and how it reports. Both reviewers that +[`review.md`](review.md) runs are told to read this file first, since Claude Code's +`/code-review` has angles of its own and opens no file of the repository unless told; anyone else +reviewing a pull request, a branch or a local diff reaches it through +[`AGENTS.md`](../../AGENTS.md#review). + +Each item names what to look for; the rule, its exceptions and its procedure stay with the section +of `AGENTS.md` it links. Read that section before you report against it. + +## Reviews are read-only + +A reviewer reads and reports. It makes no edit, commit or push, runs no build or test, no +`loft fmt`, `loft publish` or `loft reconcile --accept`, writes nothing to Yard Log and creates no +worktree. A gate not run or a check not made is a finding, not something to go and run. + +## Define the target + +- What is reviewed: a pull request, a branch, a commit range or a local diff, and against which + base (`develop` unless stated). +- Read the list of changed files first (`git diff --stat`), then the patch by area: `spec/`, + `loft.trace.yaml` and `changes/`; each crate under `crates/`; the Yard page and its tests; + `plugins/` and the skill sources; `schemas/` and `testdata/`; `scripts/`, `.github/` and + `docs/`. +- Read the guidance of each area touched: the section of `AGENTS.md` that owns it, and the skill + references it names. + +## Inspect in this order + +1. **The specification first.** Behavior the change adds or changes without `spec/` stating it, + or the commit of the specification coming after the code; a node given a key or a label by + hand instead of by `loft fmt` and `loft publish`; a decision `accepted` while its choice is + still open, or `proposed` once it is made; `loft fmt --check` or + `loft check --fail-on warning` that would not be clean + ([Normative contract](../../AGENTS.md#normative-contract)). A shared rule changed without an + entry in `testdata/v1/divergences.json` + ([Agreement with v1](../../AGENTS.md#agreement-with-v1)). +2. **Correctness.** Wrong results; an exit code other than 0, 1 and 2 as + [Commands and their output](../../AGENTS.md#commands-and-their-output) assigns them, or a JSON + document not built through `crates/loft-cli/src/json.rs` or not matching its schema; an + output change without a new schema version; a file of the Format written other than through + the journaled save ([Repository layout](../../AGENTS.md#repository-layout)); a race between + two writers of Yard Log or the tree. And the question of silent acceptance below. +3. **Boundaries.** A model crate that performs I/O, a model that depends on the other model or on + a store, a store that depends on the other store, or any crate that depends on a crate of the + private server ([Repository layout](../../AGENTS.md#repository-layout)); a test that reaches a + real external system other than through a contract suite, a request that bypasses the network + client, or a new external system without its Component, port and simulator + ([Software Plant](../../AGENTS.md#software-plant)); anything confidential in a file, a commit + message, a comment or a test name ([Public hygiene](../../AGENTS.md#public-hygiene)); a golden + vector, or a file under `testdata/v1/` written by a v1 implementation, changed to make a + failure disappear. +4. **Gates and shape.** A gate of the [Workflow](../../AGENTS.md#workflow) list that the paths + touched call for and that the author does not report as run; a lint suppressed, a threshold + in `clippy.toml` raised, a source file over 500 lines, a directory over 15 entries, or a + `deslop-please` finding put on an allow list or moved out of sight instead of fixed at its + cause; code compressed or moved only to pass a limit. A new command without its Feature and + tags, its entry in `crates/loft-cli/tests/common/commands.rs` or its schema. +5. **Tests and trace.** A behavior without a test, or a test that would still pass without the + change; a label in a test name; a test file not declared in its group's `mod.rs`; a + simulator scenario without its contract case. A test added, renamed or removed without its + link in `loft.trace.yaml`, a link accepted before the test was read against its criterion, or + a changed test whose link was not accepted in the same commit + ([Workflow](../../AGENTS.md#workflow)). +6. **Duplication.** Logic, a test, a fixture or a contract copied instead of reused, or the diff + repeating itself; a cleanup that says "no other users" without a search of the whole tree + behind it. +7. **Docs and names.** Guidance in `AGENTS.md`, `docs/` or a skill reference left stale by the + change; a British spelling; a change its readers will notice without a change file under + `changes/`, or `CHANGELOG.md` edited on a branch ([Workflow](../../AGENTS.md#workflow)); a + package under `plugins/` edited by hand, or a manifest version that disagrees with `loft`'s + ([The agent skill](../../AGENTS.md#the-agent-skill)); a typed ID replaced by a plain string. +8. **Rules learned from review**, below. + +### Silent acceptance + +For each check the change adds or relies on that refuses input (a parser, a validator, a guard, a +merge rule), ask which input it would let through without a word: another valid spelling of the +same thing, an empty or missing value, a duplicate, a value from a newer version, a path that +leaves the tree. Such an input is a finding, and so is a refusal with no test. + +The fix belongs to the kind of input, not the example: a check that let one form through is +fail-open, so it is made to refuse by default (parse fail-closed) rather than taught that one +form. + +### Rules learned from review + +Entries are added as [review.md](review.md#review-comments-that-state-a-general-rule) describes: +each links the guidance that owns its rule and says what breaking it costs. + +None yet. + +## Each finding + +- Point at the exact changed lines. +- Name the concrete failure: the input or state, and what goes wrong. "Differs from how I would + write it" is not a finding. +- Say what is missing when that is the gap: a test, a trace link, a gate run, a change file. + +## Report + +- Findings first, ordered by severity; a short summary of the change after, if any. +- No findings: say so explicitly, and name the residual risks and the checks a read-only review + could not make. +- Post comments on a pull request only when the person asked for that; then inline, short, and + with enough context for the author to act. From 3a767d3dbfcca108a5cff53ccbfe291ff8d2d17c Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:14:13 +0000 Subject: [PATCH 02/49] scripts: run the two read-only reviewers of a change in parallel scripts/agent-review/review.py runs Claude Code's /code-review in a fresh `claude -p` session and Codex in a fresh `codex exec` run on one commit, with the models and the effort pinned in the script alone, and saves each review outside the tree. With --stage, each run is a task of the branch's Yard Log. --probe checks that the Claude reviewer can call nothing but Agent, Bash, Read and Skill, with no MCP server, and that the Codex sandbox refuses a write. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/prompt.md | 23 ++ scripts/agent-review/review.py | 315 ++++++++++++++++++++ scripts/agent-review/reviewer-settings.json | 29 ++ 3 files changed, 367 insertions(+) create mode 100644 scripts/agent-review/prompt.md create mode 100755 scripts/agent-review/review.py create mode 100644 scripts/agent-review/reviewer-settings.json diff --git a/scripts/agent-review/prompt.md b/scripts/agent-review/prompt.md new file mode 100644 index 00000000..37035d8c --- /dev/null +++ b/scripts/agent-review/prompt.md @@ -0,0 +1,23 @@ +You are a read-only reviewer of the change {base}...{branch} (commit {commit}) in this +repository. Read docs/contributing/review-checklist.md first and apply it, with the sections of +AGENTS.md it links for the areas the change touches. + +Get the diff with exactly this command and nothing around it: git diff {base}...{branch} + +Read files with single read-only commands. Never fetch, check out, build, test or write +anything: a gate not run or a check not made is a finding, not something to go and run. + +Answer these two questions as well: + +- Duplication: does the diff copy logic, a test, a fixture or a contract that already exists, or + repeat itself? +- Silent acceptance: for each check the change adds or relies on that refuses input, which input + would it let through without a word? + +Report findings first, ordered by severity, each with its file and lines, the input or state, and +what goes wrong. With no findings, say so, and name the residual risks and the checks a read-only +review could not make. + +What the author tells you about the change: + +{context} diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py new file mode 100755 index 00000000..bec6e96a --- /dev/null +++ b/scripts/agent-review/review.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""Run the two read-only reviewers of docs/contributing/review.md on one commit, in parallel. + +Claude Code's /code-review runs in a fresh `claude -p` session and Codex in a fresh `codex exec` +run, with the models and effort pinned below, which is the one place that pins them. Each review +is saved under --out, which lies outside the tree. With --stage, each run is also a task of that +stage of the branch's Yard Log: active before it starts; done once its review is saved, with its +model, effort, commit, session or thread and tokens; open with the reason when it fails. + +--probe checks the setup instead: the Claude reviewer can call no tool but Agent, Bash, Read and +Skill, and the Codex reviewer cannot write in the tree. + +Exits 0 when every review asked for was saved (or the probe passed), 1 when one failed, and 2 on +a usage error. +""" + +import argparse +import json +import shlex +import shutil +import subprocess +import sys +import uuid +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from pathlib import Path + +CLAUDE_MODEL = "claude-opus-5-5" +CODEX_MODEL = "gpt-6.2-astra" +EFFORT = "high" + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +CLAUDE_TOOLS = ("Agent", "Bash", "Read", "Skill") +# The session's start event names the Agent tool by its older name, Task. +CLAUDE_TOOL_NAMES = {*CLAUDE_TOOLS, "Task"} +READ_ONLY = ( + "Read-only reviewer. The branch is already in the repository: never fetch, check out or " + "write. Use single read-only git, grep, head, tail, wc, cat or jq commands, or pipes of " + "them; no redirects, cd, variables or loops." +) +PROBE_FILE = "agent-review-probe" + + +@dataclass +class Run: + """One reviewer's run: what it was given, and what it left.""" + + name: str + model: str + commit: str + base: str + out: Path + session: str = field(default_factory=lambda: str(uuid.uuid4())) + text: str = "" + ident: str = "" + tokens: str = "" + error: str = "" + + @property + def label(self) -> str: + return "Claude /code-review" if self.name == "claude" else "Codex" + + @property + def review_path(self) -> Path: + return self.out / f"{self.commit[:12]}-{self.name}.md" + + @property + def raw_path(self) -> Path: + suffix = "json" if self.name == "claude" else "jsonl" + return self.out / f"{self.commit[:12]}-{self.name}.{suffix}" + + def command(self, prompt: str, output: str = "json") -> list[str]: + if self.name == "claude": + return [ + "claude", "-p", "--session-id", self.session, prompt, + "--model", self.model, "--effort", EFFORT, "--output-format", output, + "--strict-mcp-config", "--permission-mode", "dontAsk", + "--tools", ",".join(CLAUDE_TOOLS), "--setting-sources", "project", + "--settings", str(HERE / "reviewer-settings.json"), + "--append-system-prompt", READ_ONLY, + ] + return [ + "codex", "exec", "--json", "--ignore-user-config", + "--disable", "apps", "--disable", "browser_use", "--disable", "computer_use", + "--sandbox", "read-only", "-C", str(ROOT), "-m", self.model, + "-c", f'model_reasoning_effort="{EFFORT}"', + "-o", str(self.review_path), "-", + ] + + def execute(self, prompt: str) -> None: + """Run the reviewer to its end and keep what it left; never raises.""" + # Codex reads its prompt from standard input; Claude takes it as an argument and must + # not wait on a terminal. + stdin = {"input": prompt} if self.name == "codex" else {"stdin": subprocess.DEVNULL} + try: + done = subprocess.run( + self.command(prompt), cwd=ROOT, capture_output=True, text=True, **stdin + ) + except OSError as error: + self.error = f"could not start {self.name}: {error}" + return + self.raw_path.write_text(done.stdout) + if self.name == "claude": + self._read_claude(done.stdout) + else: + self._read_codex(done.stdout) + if not self.error and done.returncode != 0: + self.error = f"exited {done.returncode}: {done.stderr.strip()[-400:]}" + if not self.error and not self.text.strip(): + self.error = "the reviewer printed no review" + if not self.error and self.name == "claude": + self.review_path.write_text(self.text) + + def _read_claude(self, stdout: str) -> None: + try: + data = json.loads(stdout) + except json.JSONDecodeError: + self.error = "Claude printed no JSON result" + return + self.ident = data.get("session_id", self.session) + self.text = data.get("result") or "" + if data.get("is_error") or data.get("subtype") not in (None, "success"): + self.error = f"Claude ended with {data.get('subtype')}: {self.text[:400]}" + usage = data.get("usage") or {} + ran = ", ".join(data.get("modelUsage") or {}) or "unknown" + self.tokens = ( + f"input {usage.get('input_tokens', 0)}, cache read " + f"{usage.get('cache_read_input_tokens', 0)}, cache write " + f"{usage.get('cache_creation_input_tokens', 0)}, output " + f"{usage.get('output_tokens', 0)}; models that ran: {ran}" + ) + + def _read_codex(self, stdout: str) -> None: + for line in stdout.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + kind = event.get("type") + if kind == "thread.started": + self.ident = event.get("thread_id", "") + elif kind == "turn.completed": + usage = event.get("usage") or {} + self.tokens = ( + f"input {usage.get('input_tokens', 0)}, cached " + f"{usage.get('cached_input_tokens', 0)}, output " + f"{usage.get('output_tokens', 0)}, reasoning " + f"{usage.get('reasoning_output_tokens', 0)}" + ) + elif kind == "turn.failed": + self.error = (event.get("error") or {}).get("message", "the turn failed") + elif kind == "error" and not self.error: + self.error = event.get("message", "Codex reported an error") + if self.review_path.exists(): + self.text = self.review_path.read_text() + + def task(self, stage: str, state: str) -> dict: + """The run's Yard task, in the state given.""" + where = f"{self.commit[:12]} against {self.base}" + if state == "active": + detail = f"{self.label} {self.model}, effort {EFFORT}, reviewing {where}." + elif state == "done": + detail = ( + f"{self.label} {self.model}, effort {EFFORT}, reviewed {where}; " + f"{'session' if self.name == 'claude' else 'thread'} {self.ident}; " + f"tokens: {self.tokens}. Review: {self.review_path}" + ) + else: + detail = f"{self.label} {self.model}, effort {EFFORT}, on {where} failed: {self.error}" + block = { + "id": f"review-{self.name}-{self.commit[:8]}", "kind": "task", "stage": stage, + "title": f"{self.label} review of {self.commit[:8]}", "state": state, + "detail": detail, + } + if self.name == "claude": + block["assignee"] = {"host": "claude-code", "session": self.session} + return block + + +class Yard: + """Writes each run's task into the branch's Yard Log, or nothing without --stage or loft.""" + + def __init__(self, stage: str | None, session: str | None, host: str) -> None: + self.stage, self.session, self.host = stage, session, host + if stage and shutil.which("loft") is None: + print("loft is not on PATH: the runs are not recorded in Yard Log", file=sys.stderr) + self.stage = None + + def record(self, runs: list[Run], state: str | None = None) -> None: + if not self.stage: + return + batch = [run.task(self.stage, state or ("open" if run.error else "done")) for run in runs] + done = subprocess.run( + ["loft", "yard", "write", "--input", "-", "--session", self.session or "", + "--host", self.host, "--tree", str(ROOT), "--format", "json"], + input=json.dumps(batch), capture_output=True, text=True, + ) + if done.returncode != 0: + print(f"Yard Log refused the tasks: {done.stdout or done.stderr}", file=sys.stderr) + + +def git(*args: str) -> str: + return subprocess.run( + ["git", *args], cwd=ROOT, capture_output=True, text=True, check=True + ).stdout.strip() + + +def usage_error(message: str) -> None: + print(f"review.py: {message}", file=sys.stderr) + sys.exit(2) + + +def arguments() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--branch", help="the branch reviewed; the current one when not given") + parser.add_argument("--base", default="develop", help="what it is reviewed against") + parser.add_argument("--context", type=Path, help="a file of what the author tells reviewers") + parser.add_argument("--out", type=Path, required=True, help="a directory outside the tree") + parser.add_argument("--stage", help="the Yard Log stage whose tasks record the runs") + parser.add_argument("--session", help="the author's session, which writes the tasks") + parser.add_argument("--host", default="claude-code", choices=("claude-code", "codex")) + parser.add_argument("--only", choices=("claude", "codex"), help="run one reviewer alone") + parser.add_argument("--dry-run", action="store_true", help="print the commands; run nothing") + parser.add_argument("--probe", action="store_true", help="check the reviewers' setup") + args = parser.parse_args() + out = args.out.resolve() + if out == ROOT or ROOT in out.parents: + usage_error(f"--out must lie outside the tree, not in {ROOT}") + if args.stage and not args.session: + usage_error("--stage needs --session, the author's session that writes the tasks") + args.out = out + return args + + +def prompt_for(args: argparse.Namespace, branch: str, commit: str) -> str: + context = args.context.read_text().strip() if args.context else "" + return (HERE / "prompt.md").read_text().format( + base=args.base, branch=branch, commit=commit, context=context or "Nothing more." + ) + + +def claude_start(run: Run) -> dict: + """The start event of a short Claude reviewer session, which names what it can call.""" + command = run.command("Say ok.", output="stream-json") + command += ["--verbose", "--no-session-persistence"] + done = subprocess.run( + command, cwd=ROOT, capture_output=True, text=True, stdin=subprocess.DEVNULL + ) + for line in done.stdout.splitlines(): + event = json.loads(line) + if event.get("type") == "system" and event.get("subtype") == "init": + return event + return {} + + +def probe(runs: list[Run]) -> int: + """Check that each reviewer can do nothing but read.""" + failed = False + for run in runs: + if run.name == "claude": + start = claude_start(run) + tools, servers = start.get("tools") or [], start.get("mcp_servers") + skills = start.get("skills") or start.get("slash_commands") or [] + extra = set(tools) - CLAUDE_TOOL_NAMES + bad = not tools or extra or servers or "code-review" not in skills + print(f"Claude tools: {', '.join(tools) or 'none'}; MCP servers: {servers}; " + f"/code-review {'present' if 'code-review' in skills else 'missing'}") + else: + target = ROOT / PROBE_FILE + run.execute(f"Run exactly `touch {PROBE_FILE}` once, then say whether it worked.") + bad = target.exists() + target.unlink(missing_ok=True) + print(f"Codex write in the tree: {'allowed' if bad else 'refused'}") + failed = failed or bool(bad) + print("probe failed" if failed else "probe passed") + return 1 if failed else 0 + + +def main() -> int: + args = arguments() + branch = args.branch or git("rev-parse", "--abbrev-ref", "HEAD") + try: + commit = git("rev-parse", "--verify", f"{branch}^{{commit}}") + git("rev-parse", "--verify", f"{args.base}^{{commit}}") + except subprocess.CalledProcessError: + usage_error(f"{branch} or {args.base} is not a commit here; fetch it first") + names = [args.only] if args.only else ["claude", "codex"] + models = {"claude": CLAUDE_MODEL, "codex": CODEX_MODEL} + runs = [Run(name, models[name], commit, args.base, args.out) for name in names] + prompt = prompt_for(args, branch, commit) + claude_prompt = f"/code-review {EFFORT} {branch} against {args.base}. {prompt}" + if args.dry_run: + for run in runs: + given = claude_prompt if run.name == "claude" else prompt + print(shlex.join(run.command(given))) + if "codex" in names: + print(f"\nCodex reads this prompt on standard input:\n\n{prompt}") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + if args.probe: + return probe(runs) + yard = Yard(args.stage, args.session, args.host) + yard.record(runs, "active") + with ThreadPoolExecutor(len(runs)) as pool: + for run in runs: + pool.submit(run.execute, claude_prompt if run.name == "claude" else prompt) + yard.record(runs) + for run in runs: + print(f"{run.label}: {run.error or run.review_path}", file=sys.stderr) + return 1 if any(run.error for run in runs) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/agent-review/reviewer-settings.json b/scripts/agent-review/reviewer-settings.json new file mode 100644 index 00000000..dec7de90 --- /dev/null +++ b/scripts/agent-review/reviewer-settings.json @@ -0,0 +1,29 @@ +{ + "permissions": { + "deny": [ + "Edit", + "Write", + "NotebookEdit", + "WebFetch", + "WebSearch", + "mcp__loft", + "Bash(git *--output*)", + "Bash(git *--ext-diff*)", + "Bash(git *--textconv*)", + "Bash(git *--filters*)" + ], + "allow": [ + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(git show:*)", + "Bash(git ls-tree:*)", + "Bash(git merge-base:*)", + "Bash(grep:*)", + "Bash(head:*)", + "Bash(tail:*)", + "Bash(wc:*)", + "Bash(cat:*)", + "Bash(jq:*)" + ] + } +} From 66061b7e1d08e65d2ecfa635510cc42349be5329 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:15:04 +0000 Subject: [PATCH 03/49] scripts: record review runs under the author's Claude Code session by default Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index bec6e96a..8f6a4d46 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -16,6 +16,7 @@ import argparse import json +import os import shlex import shutil import subprocess @@ -218,7 +219,9 @@ def arguments() -> argparse.Namespace: parser.add_argument("--context", type=Path, help="a file of what the author tells reviewers") parser.add_argument("--out", type=Path, required=True, help="a directory outside the tree") parser.add_argument("--stage", help="the Yard Log stage whose tasks record the runs") - parser.add_argument("--session", help="the author's session, which writes the tasks") + parser.add_argument( + "--session", help="the author's session, which writes the tasks; in Claude Code, its own" + ) parser.add_argument("--host", default="claude-code", choices=("claude-code", "codex")) parser.add_argument("--only", choices=("claude", "codex"), help="run one reviewer alone") parser.add_argument("--dry-run", action="store_true", help="print the commands; run nothing") @@ -227,6 +230,8 @@ def arguments() -> argparse.Namespace: out = args.out.resolve() if out == ROOT or ROOT in out.parents: usage_error(f"--out must lie outside the tree, not in {ROOT}") + if args.host == "claude-code": + args.session = args.session or os.environ.get("CLAUDE_CODE_SESSION_ID") if args.stage and not args.session: usage_error("--stage needs --session, the author's session that writes the tasks") args.out = out From dd9e05b9a3b2565dd2e55bde32077f101a394061 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:15:04 +0000 Subject: [PATCH 04/49] docs(contributing): the agent review a change passes before a person is asked The sequence from self-review and /simplify through two parallel read-only reviewers to the verified findings a person picks from; the pinned models and effort; what the reviewers are given; how the runner is driven and its setup checked; how a round is recorded; and how a review comment that states a general rule becomes guidance. Co-Authored-By: Claude Opus 5.5 --- docs/contributing/review.md | 143 ++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 docs/contributing/review.md diff --git a/docs/contributing/review.md b/docs/contributing/review.md new file mode 100644 index 00000000..df174d0b --- /dev/null +++ b/docs/contributing/review.md @@ -0,0 +1,143 @@ +# Agent review before a human + +A change is reviewed by two agents before a person is asked to review it. This file is the how: +the sequence, the two reviewers and their models, what they are given, how each round is +recorded, and the commands. What a reviewer looks for is in +[`review-checklist.md`](review-checklist.md). The two rules behind both are in +[`AGENTS.md`](../../AGENTS.md#review): review before a human is asked, and reviews are read-only. + +## When + +At the end of each branch, and of each wave of a larger one, before its author asks a person to +review or merge it; and again on the fix commits, when the fixes go beyond mechanical ones (step 8). + +## The sequence + +1. **Self-review and gates.** Read the diff line by line and fix what you find. Ask the question + of [silent acceptance](review-checklist.md#silent-acceptance) of each check the change adds or + relies on that refuses input, and try the inputs it names. Run the gates the + [Workflow](../../AGENTS.md#workflow) calls for on the paths the change touches, and note each + as run, with its result, or not run, with the reason. +2. **`/simplify`** in the author's session. It applies its cleanups; commit them. +3. **Two reviews in parallel on that commit**: Claude Code's `/code-review` in a fresh + `claude -p` session and Codex in a fresh `codex exec` run, both started by + [`scripts/agent-review/review.py`](../../scripts/agent-review/review.py). Both are read-only: + they report and change nothing, and run no build or test. +4. **Merge** the two reviews into one list: duplicates removed, each finding tagged with its + source (`C` for Claude, `X` for Codex, `C+X` for both), disagreements between the reviewers + flagged. +5. **Verify each finding.** A finding about behavior gets a focused test that reproduces it, run + alone (`cargo nextest run -p -E 'test(/…/)'`, or the page's own suite), failing + first. A finding no test can show (docs, naming, duplication, shape) gets evidence from + reading: the file and line, or a search of the whole tree. Each finding ends confirmed, + refuted with a reason, or not testable with its evidence. The findings and their verdicts go + into the review stage's note of issues in Yard Log (below). +6. **The person sees the verified list and picks** which findings to act on. +7. **Fix.** A reproduction test becomes the regression test, and its trace link is added; the + tests written for declined findings are deleted. Fix the kind of input, not the example: an + input a check let through shows the check is fail-open, so make it refuse by default rather + than teach it that one input. +8. **Re-review only the fix commits**, and only when the fixes go beyond mechanical ones, with the + same two runs, against the commit last reviewed (`--base `). After two rounds on one + change, one more form of an input kind a check already covers gets a test of its own only + where a real input could take that form; an exotic form the check refuses goes into the pull + request as a residual risk, and one it lets through goes back to step 7. Findings of other + kinds are fixed as usual. The person decides whether another round runs. +9. **Record the round** in the pull request (below). + +If a reviewer cannot run, say so in the pull request instead of quietly dropping it. + +## Models and effort + +Claude `claude-opus-5-5` and Codex `gpt-6.2-astra`, both at `high` effort, which is also the +floor: a person may ask for a higher effort on a run, never a lower one. The models are this +repository's choice, not whatever a command line calls newest; a newer model takes over only once +a person decides it does, by changing the constants at the top of `review.py`, the one place +that pins them. The effort is set on every call, since a machine's default may be anything, and +Codex runs with `--ignore-user-config` so that no personal configuration reaches it. Claude's +result names the models that ran, and the script records them; Codex prints no model, so its +task records the model asked for. + +## What the reviewers are given + +[`scripts/agent-review/prompt.md`](../../scripts/agent-review/prompt.md) is the prompt both +receive: that the review is read-only, the checklist to read first, the exact diff command, the +questions of duplication and silent acceptance, and the shape of the report. The author adds +what the reviewers cannot infer in a context file passed with `--context`: + +- the gates already run and their results, so that no reviewer tries to build; +- the Feature, Requirement or decision the change serves, and what `spec/` changes; +- constraints the diff does not show, such as a schema version already released, a golden vector + that must not move, or a file only a v1 implementation writes. + +Never put a credential, a token or the contents of an `.env` file into a prompt. Sending a +diff of this public repository to both reviewers' providers is approved. + +## Running the reviewers + +From the root of the worktree whose branch is reviewed, with the branch and its base present +locally (the reviewers can neither fetch nor check out): + +```sh +scripts/agent-review/review.py --context --out \ + [--branch ] [--base develop] [--stage --session ] +``` + +- Both reviewers run at once; each review is saved under `--out` as + `-claude.md` and `-codex.md`, beside the raw output of its run. The script + refuses an `--out` inside the tree, and exits 1 when either review failed, naming the reason. +- `--only claude` or `--only codex` runs one alone; `--dry-run` prints both commands and the + prompt and runs nothing. +- The Claude reviewer runs with `--permission-mode dontAsk`, the tools `Agent`, `Bash`, `Read` + and `Skill`, no MCP server, project settings alone and + [`reviewer-settings.json`](../../scripts/agent-review/reviewer-settings.json), which denies the + edit and web tools and allows a short list of reading commands. `dontAsk` refuses everything + else, so the prompt names the diff command exactly: a reviewer that composes its own refuses + itself and reviews nothing. The list prevents accidents; it is not a sandbox. Keep it to these + few reading commands rather than adding more and chasing their options. +- The Codex reviewer runs in Codex's `read-only` sandbox, with apps, the browser and computer use + turned off. Do not use `codex review`: it takes neither a sandbox nor a prompt with a base. + +**Check the setup** once on each machine, and after each upgrade of Claude Code or Codex: + +```sh +scripts/agent-review/review.py --probe --out +``` + +It passes when the Claude reviewer's session can call nothing but `Agent`, `Bash`, `Read` and +`Skill`, has no MCP server and has `/code-review`, and when the Codex reviewer's attempt to write a +file in the tree is refused. + +## Recording a round + +**In Yard Log.** With `--stage` and `--session` (in Claude Code the session defaults to the +author's own), the script writes each run as a task of that stage: `active` before it starts; +`done` once its review is saved, with the model, the effort, the commit, the session or thread +and the tokens in its detail; `open` with the reason when it fails. Without `loft` on the path it +records nothing and says so. The author keeps the round's findings in the stage's note of +issues, one table for the round: + +| # | Src | Finding | Verdict | Evidence | +| --- | --- | --- | --- | --- | +| 1 | C+X | `path/to/file.rs:120`: an empty key is accepted as the root | Confirmed | `refuses_an_empty_key` fails before the fix | + +This repository's git ignores `.yard/`, so that record stays on the machine. + +**In the pull request.** The [pull request template](../../.github/pull_request_template.md) has +the Agent review table: one row each for `/simplify`, Claude's `/code-review` and Codex, with the +model, the effort, the commit reviewed and the result, and below it the findings refuted or +declined, with the reason, for the person reviewing to settle. A branch merged into `develop` +without a pull request carries the same table in the body of its merge commit. + +## Review comments that state a general rule + +When a review comment, from either reviewer or a person, states a rule that holds for code in +general and not only for its line, the author records it in the same pull request as the fix: + +- the rule goes into the guidance that owns its topic (`AGENTS.md`, a skill reference, a crate's + documentation), unless it is already there; +- one entry under [Rules learned from review](review-checklist.md#rules-learned-from-review) + links to it, with what breaking it costs; +- the review thread gets a link to the rule. + +A comment about one line, or about taste, is not a rule; when unclear, ask in the thread. From 4f7f43c101a25c9cb7faf54d0f5c6a188e64ec02 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:15:15 +0000 Subject: [PATCH 05/49] docs(agents): review before a human is asked, and reviews are read-only AGENTS.md states the two rules and points at the procedure, the checklist and the runner; the sentence that kept a review from building or testing now names the reviewer, since the author verifies findings with focused tests. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 2e706c9a..a8e199c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,7 +378,20 @@ The thinking behind the Software Plant is at . - For a focused loop, use `cargo nextest run -p `. - Run the workspace suite at most once per commit, and never in a loop: a branch's commits are not re-tested one by one, and no two workspace runs share a machine at once, however many agents - are working. A review reads the diff; it builds and tests nothing and creates no worktree. + are working. A reviewer reads the diff; it builds and tests nothing and creates no worktree. + +## Review + +- **Review before a human is asked.** At the end of a branch or a wave, after `/simplify`, Claude + Code's `/code-review` and Codex review the same commit in parallel, each in a fresh session that + `scripts/agent-review/review.py` starts with the models and the effort it pins. The author + merges their findings, verifies each one, with a focused failing test where it is about + behavior, and shows the person the verified list to choose from. `docs/contributing/review.md` + is the procedure. +- **Reviews are read-only.** A reviewer reports and changes nothing, and runs no build or test; a + gate not run is a finding. Only the author, verifying, writes and runs tests, and only focused + ones. `docs/contributing/review-checklist.md` is what a reviewer checks and how it reports, + and any review of a change here follows it. ## Releasing From 8ce58f1711b021188367a3a34a2f29c4fb3a9b01 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:15:21 +0000 Subject: [PATCH 06/49] ci: a pull request template that records its checks and its agent review Co-Authored-By: Claude Opus 5.5 --- .github/pull_request_template.md | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..9e039756 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,35 @@ +## Summary + + + +## Specification + + + +## Checks + + + +- [ ] + +## Agent review + + + +| Run | Model | Effort | Commit | Result | +| --- | --- | --- | --- | --- | +| `/simplify` | | | | | +| Claude `/code-review` | | | | | +| Codex | | | | | + + From 560ef491ae4ddeba9b64b32af89897f834fb1313 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:16:46 +0000 Subject: [PATCH 07/49] scripts: refuse what the review runner let pass in silence A probe passes only when the reviewer ran (a Codex that never started wrote nothing either, and a Claude session that never answered still printed its start event); a review left by an earlier run on the same commit no longer passes for a failed one; a branch with no change against its base is refused rather than reviewed as empty; and the runner reads on the system's older Python. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 37 +++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 8f6a4d46..40f304ea 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -14,6 +14,8 @@ a usage error. """ +from __future__ import annotations + import argparse import json import os @@ -94,6 +96,8 @@ def execute(self, prompt: str) -> None: # Codex reads its prompt from standard input; Claude takes it as an argument and must # not wait on a terminal. stdin = {"input": prompt} if self.name == "codex" else {"stdin": subprocess.DEVNULL} + # A review left by an earlier run on the same commit must not pass for this one's. + self.review_path.unlink(missing_ok=True) try: done = subprocess.run( self.command(prompt), cwd=ROOT, capture_output=True, text=True, **stdin @@ -246,17 +250,25 @@ def prompt_for(args: argparse.Namespace, branch: str, commit: str) -> str: def claude_start(run: Run) -> dict: - """The start event of a short Claude reviewer session, which names what it can call.""" + """The start event of a short Claude reviewer session, which names what it can call, or + nothing when the session did not start or did not answer.""" command = run.command("Say ok.", output="stream-json") command += ["--verbose", "--no-session-persistence"] - done = subprocess.run( - command, cwd=ROOT, capture_output=True, text=True, stdin=subprocess.DEVNULL - ) + try: + done = subprocess.run( + command, cwd=ROOT, capture_output=True, text=True, stdin=subprocess.DEVNULL + ) + except OSError: + return {} + events = [] for line in done.stdout.splitlines(): - event = json.loads(line) - if event.get("type") == "system" and event.get("subtype") == "init": - return event - return {} + try: + events.append(json.loads(line)) + except json.JSONDecodeError: + continue + answered = any(e.get("type") == "result" and not e.get("is_error") for e in events) + starts = [e for e in events if e.get("type") == "system" and e.get("subtype") == "init"] + return starts[0] if answered and starts else {} def probe(runs: list[Run]) -> int: @@ -274,9 +286,12 @@ def probe(runs: list[Run]) -> int: else: target = ROOT / PROBE_FILE run.execute(f"Run exactly `touch {PROBE_FILE}` once, then say whether it worked.") - bad = target.exists() + wrote = target.exists() target.unlink(missing_ok=True) - print(f"Codex write in the tree: {'allowed' if bad else 'refused'}") + # A Codex that never ran writes nothing either: the run itself must succeed. + bad = wrote or run.error + print(f"Codex write in the tree: {'allowed' if wrote else 'refused'}" + f"{f'; the run failed: {run.error}' if run.error else ''}") failed = failed or bool(bad) print("probe failed" if failed else "probe passed") return 1 if failed else 0 @@ -305,6 +320,8 @@ def main() -> int: args.out.mkdir(parents=True, exist_ok=True) if args.probe: return probe(runs) + if not git("diff", "--name-only", f"{args.base}...{commit}"): + usage_error(f"{branch} holds no change against {args.base}: there is nothing to review") yard = Yard(args.stage, args.session, args.host) yard.record(runs, "active") with ThreadPoolExecutor(len(runs)) as pool: From efbc19043c63bfdad39d36fa1975fc3d4757bea3 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:22:33 +0000 Subject: [PATCH 08/49] refactor(review): state each rule once and give each reviewer its own class The read-only rule lives in AGENTS.md, the review criteria in the checklist, the models and the effort in the runner's constants; the procedure and the prompt point at them instead of repeating them. The runner gives Claude and Codex a class each, builds each prompt once so that --dry-run prints what is sent, takes the allowed commands from the reviewer settings, enforces the effort floor through --effort, and runs the probe's two checks at once into files of their own, so that a probe no longer overwrites a saved review. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 21 +- docs/contributing/review-checklist.md | 19 +- docs/contributing/review.md | 137 +++++----- scripts/agent-review/prompt.md | 19 +- scripts/agent-review/review.py | 362 ++++++++++++++------------ 5 files changed, 276 insertions(+), 282 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8e199c5..9e61fe00 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,20 +378,19 @@ The thinking behind the Software Plant is at . - For a focused loop, use `cargo nextest run -p `. - Run the workspace suite at most once per commit, and never in a loop: a branch's commits are not re-tested one by one, and no two workspace runs share a machine at once, however many agents - are working. A reviewer reads the diff; it builds and tests nothing and creates no worktree. + are working. A reviewer builds and tests nothing ([Review](#review)). ## Review -- **Review before a human is asked.** At the end of a branch or a wave, after `/simplify`, Claude - Code's `/code-review` and Codex review the same commit in parallel, each in a fresh session that - `scripts/agent-review/review.py` starts with the models and the effort it pins. The author - merges their findings, verifies each one, with a focused failing test where it is about - behavior, and shows the person the verified list to choose from. `docs/contributing/review.md` - is the procedure. -- **Reviews are read-only.** A reviewer reports and changes nothing, and runs no build or test; a - gate not run is a finding. Only the author, verifying, writes and runs tests, and only focused - ones. `docs/contributing/review-checklist.md` is what a reviewer checks and how it reports, - and any review of a change here follows it. +- **Review before a human is asked.** At the end of a branch or a wave, before a person is asked + to review or merge it, the change passes the agent review of `docs/contributing/review.md`: two + read-only reviewers in parallel, whose findings the author verifies and the person picks from. + Here it takes the place of the wave review the `yard` skill describes. +- **Reviews are read-only.** A reviewer reads and reports: it makes no edit, commit or push, runs + no build or test, no `loft fmt`, `loft publish` or `loft reconcile --accept`, writes nothing to + Yard Log and creates no worktree. Only the author, verifying a finding, writes and runs tests, + and only focused ones. `docs/contributing/review-checklist.md` is what any reviewer of a change + here checks, and how it reports. ## Releasing diff --git a/docs/contributing/review-checklist.md b/docs/contributing/review-checklist.md index 54683ecd..6c914146 100644 --- a/docs/contributing/review-checklist.md +++ b/docs/contributing/review-checklist.md @@ -1,19 +1,12 @@ # Review checklist -What a reviewer of a change to this repository checks, and how it reports. Both reviewers that -[`review.md`](review.md) runs are told to read this file first, since Claude Code's -`/code-review` has angles of its own and opens no file of the repository unless told; anyone else -reviewing a pull request, a branch or a local diff reaches it through -[`AGENTS.md`](../../AGENTS.md#review). +What any reviewer of a change to this repository checks, and how it reports; the reviewers of +[`review.md`](review.md) are pointed here by their prompt. Each item names what to look for; the +rule, its exceptions and its procedure stay with the section of `AGENTS.md` it links. Read that +section before you report against it. -Each item names what to look for; the rule, its exceptions and its procedure stay with the section -of `AGENTS.md` it links. Read that section before you report against it. - -## Reviews are read-only - -A reviewer reads and reports. It makes no edit, commit or push, runs no build or test, no -`loft fmt`, `loft publish` or `loft reconcile --accept`, writes nothing to Yard Log and creates no -worktree. A gate not run or a check not made is a finding, not something to go and run. +A review is read-only, as [Review](../../AGENTS.md#review) says: a gate not run or a check not +made is a finding, not something to go and run. ## Define the target diff --git a/docs/contributing/review.md b/docs/contributing/review.md index df174d0b..c7c3ee18 100644 --- a/docs/contributing/review.md +++ b/docs/contributing/review.md @@ -1,10 +1,8 @@ # Agent review before a human -A change is reviewed by two agents before a person is asked to review it. This file is the how: -the sequence, the two reviewers and their models, what they are given, how each round is -recorded, and the commands. What a reviewer looks for is in -[`review-checklist.md`](review-checklist.md). The two rules behind both are in -[`AGENTS.md`](../../AGENTS.md#review): review before a human is asked, and reviews are read-only. +How a change passes the agent review that [Review](../../AGENTS.md#review) asks for before a +person is asked to review it: the sequence, the reviewers, how they are run and how a round is +recorded. What a reviewer looks for is [`review-checklist.md`](review-checklist.md). ## When @@ -15,65 +13,57 @@ review or merge it; and again on the fix commits, when the fixes go beyond mecha 1. **Self-review and gates.** Read the diff line by line and fix what you find. Ask the question of [silent acceptance](review-checklist.md#silent-acceptance) of each check the change adds or - relies on that refuses input, and try the inputs it names. Run the gates the - [Workflow](../../AGENTS.md#workflow) calls for on the paths the change touches, and note each - as run, with its result, or not run, with the reason. + relies on, and try the inputs it names. Run the gates the [Workflow](../../AGENTS.md#workflow) + calls for on the paths the change touches, and note each as run, with its result, or not run, + with the reason. 2. **`/simplify`** in the author's session. It applies its cleanups; commit them. -3. **Two reviews in parallel on that commit**: Claude Code's `/code-review` in a fresh - `claude -p` session and Codex in a fresh `codex exec` run, both started by - [`scripts/agent-review/review.py`](../../scripts/agent-review/review.py). Both are read-only: - they report and change nothing, and run no build or test. +3. **Two reviews in parallel on that commit**, Claude Code's `/code-review` in a fresh `claude -p` + session and Codex in a fresh `codex exec` run, both started by + [`scripts/agent-review/review.py`](../../scripts/agent-review/review.py) (below). 4. **Merge** the two reviews into one list: duplicates removed, each finding tagged with its source (`C` for Claude, `X` for Codex, `C+X` for both), disagreements between the reviewers flagged. -5. **Verify each finding.** A finding about behavior gets a focused test that reproduces it, run - alone (`cargo nextest run -p -E 'test(/…/)'`, or the page's own suite), failing - first. A finding no test can show (docs, naming, duplication, shape) gets evidence from - reading: the file and line, or a search of the whole tree. Each finding ends confirmed, - refuted with a reason, or not testable with its evidence. The findings and their verdicts go - into the review stage's note of issues in Yard Log (below). -6. **The person sees the verified list and picks** which findings to act on. +5. **Verify each finding.** A finding about behavior gets a focused test that reproduces it, + failing first, run alone as the [Workflow](../../AGENTS.md#workflow)'s focused loop runs one. + A finding no test can show (docs, naming, duplication, shape) gets evidence from reading: the + file and line, or a search of the whole tree. Each finding ends confirmed, refuted with a + reason, or not testable with its evidence. +6. **The person sees the verified list and picks** which findings to act on. Unlike the wave + review of the `yard` skill, which fixes the confirmed findings at once, every finding here + waits for that choice. 7. **Fix.** A reproduction test becomes the regression test, and its trace link is added; the - tests written for declined findings are deleted. Fix the kind of input, not the example: an - input a check let through shows the check is fail-open, so make it refuse by default rather - than teach it that one input. + tests written for declined findings are deleted. A check that let an input through is fixed + for the whole kind of input, as [silent acceptance](review-checklist.md#silent-acceptance) + says. 8. **Re-review only the fix commits**, and only when the fixes go beyond mechanical ones, with the same two runs, against the commit last reviewed (`--base `). After two rounds on one change, one more form of an input kind a check already covers gets a test of its own only where a real input could take that form; an exotic form the check refuses goes into the pull - request as a residual risk, and one it lets through goes back to step 7. Findings of other - kinds are fixed as usual. The person decides whether another round runs. -9. **Record the round** in the pull request (below). + request as a residual risk, and one it lets through goes back to step 7. The person decides + whether another round runs. +9. **Record the round** (below). If a reviewer cannot run, say so in the pull request instead of quietly dropping it. -## Models and effort +## The reviewers -Claude `claude-opus-5-5` and Codex `gpt-6.2-astra`, both at `high` effort, which is also the -floor: a person may ask for a higher effort on a run, never a lower one. The models are this -repository's choice, not whatever a command line calls newest; a newer model takes over only once -a person decides it does, by changing the constants at the top of `review.py`, the one place -that pins them. The effort is set on every call, since a machine's default may be anything, and -Codex runs with `--ignore-user-config` so that no personal configuration reaches it. Claude's -result names the models that ran, and the script records them; Codex prints no model, so its -task records the model asked for. +The constants at the top of `review.py` pin both models and the effort, the floor for both +reviewers and `/code-review`'s level; `--dry-run` prints them. A person may ask for more effort on +a run (`--effort`), never less. The models are this repository's choice, not whatever a command +line calls newest: a newer one takes over only once a person decides it does, by changing those +constants. Codex runs with `--ignore-user-config`, so no personal configuration reaches it. -## What the reviewers are given - -[`scripts/agent-review/prompt.md`](../../scripts/agent-review/prompt.md) is the prompt both -receive: that the review is read-only, the checklist to read first, the exact diff command, the -questions of duplication and silent acceptance, and the shape of the report. The author adds -what the reviewers cannot infer in a context file passed with `--context`: +The [prompt](../../scripts/agent-review/prompt.md) points both at the checklist and names the +exact diff command. The author adds, in a file passed with `--context`, what they cannot infer: - the gates already run and their results, so that no reviewer tries to build; - the Feature, Requirement or decision the change serves, and what `spec/` changes; - constraints the diff does not show, such as a schema version already released, a golden vector that must not move, or a file only a v1 implementation writes. -Never put a credential, a token or the contents of an `.env` file into a prompt. Sending a -diff of this public repository to both reviewers' providers is approved. +Never put a credential, a token or the contents of an `.env` file into a prompt. -## Running the reviewers +## Running them From the root of the worktree whose branch is reviewed, with the branch and its base present locally (the reviewers can neither fetch nor check out): @@ -83,51 +73,42 @@ scripts/agent-review/review.py --context --out ] [--base develop] [--stage --session ] ``` -- Both reviewers run at once; each review is saved under `--out` as - `-claude.md` and `-codex.md`, beside the raw output of its run. The script - refuses an `--out` inside the tree, and exits 1 when either review failed, naming the reason. -- `--only claude` or `--only codex` runs one alone; `--dry-run` prints both commands and the - prompt and runs nothing. -- The Claude reviewer runs with `--permission-mode dontAsk`, the tools `Agent`, `Bash`, `Read` - and `Skill`, no MCP server, project settings alone and - [`reviewer-settings.json`](../../scripts/agent-review/reviewer-settings.json), which denies the - edit and web tools and allows a short list of reading commands. `dontAsk` refuses everything - else, so the prompt names the diff command exactly: a reviewer that composes its own refuses - itself and reviews nothing. The list prevents accidents; it is not a sandbox. Keep it to these - few reading commands rather than adding more and chasing their options. +Both reviewers run at once, and each review is saved under `--out` beside the raw output of its +run; the script exits 1 when either failed, naming the reason. `--only` runs one alone. + +- The Claude reviewer runs under `--permission-mode dontAsk`, with the tools `CLAUDE_TOOLS` + names, no MCP server, project settings alone and + [`reviewer-settings.json`](../../scripts/agent-review/reviewer-settings.json), whose deny list + removes the edit and web tools even where the tool list names them. `dontAsk` refuses + every command the allow list does not hold, so the prompt names the diff command exactly: a + reviewer that composes its own refuses itself and reviews nothing. The list prevents accidents; + it is not a sandbox. Keep it to a few reading commands rather than adding more and chasing + their options. - The Codex reviewer runs in Codex's `read-only` sandbox, with apps, the browser and computer use turned off. Do not use `codex review`: it takes neither a sandbox nor a prompt with a base. -**Check the setup** once on each machine, and after each upgrade of Claude Code or Codex: - -```sh -scripts/agent-review/review.py --probe --out -``` - -It passes when the Claude reviewer's session can call nothing but `Agent`, `Bash`, `Read` and -`Skill`, has no MCP server and has `/code-review`, and when the Codex reviewer's attempt to write a -file in the tree is refused. +**Check the setup** with `--probe` once on each machine, and after each upgrade of Claude Code or +Codex: it fails when the Claude reviewer can call more than it should or lacks `/code-review`, or +when the Codex reviewer could write in the tree. ## Recording a round -**In Yard Log.** With `--stage` and `--session` (in Claude Code the session defaults to the -author's own), the script writes each run as a task of that stage: `active` before it starts; -`done` once its review is saved, with the model, the effort, the commit, the session or thread -and the tokens in its detail; `open` with the reason when it fails. Without `loft` on the path it -records nothing and says so. The author keeps the round's findings in the stage's note of -issues, one table for the round: +**In Yard Log.** With `--stage`, the script records each run as a task of that stage (in Claude +Code `--session` defaults to the author's own). The author keeps the round's findings in the +stage's note of issues, whose table gives how each was found (`Src`), its verdict and evidence, +and its fix: -| # | Src | Finding | Verdict | Evidence | -| --- | --- | --- | --- | --- | -| 1 | C+X | `path/to/file.rs:120`: an empty key is accepted as the root | Confirmed | `refuses_an_empty_key` fails before the fix | +| # | Src | Finding | Verdict | Evidence | Fix | +| --- | --- | --- | --- | --- | --- | +| 1 | C+X | `path/to/file.rs:120`: an empty key is accepted as the root | Confirmed | `refuses_an_empty_key` fails before the fix | Picked; fixed in `abc1234` | This repository's git ignores `.yard/`, so that record stays on the machine. -**In the pull request.** The [pull request template](../../.github/pull_request_template.md) has -the Agent review table: one row each for `/simplify`, Claude's `/code-review` and Codex, with the -model, the effort, the commit reviewed and the result, and below it the findings refuted or -declined, with the reason, for the person reviewing to settle. A branch merged into `develop` -without a pull request carries the same table in the body of its merge commit. +**In the pull request.** The [template](../../.github/pull_request_template.md) has the Agent +review table: one row each for `/simplify`, Claude's `/code-review` and Codex, with the model, the +effort, the commit reviewed and the result, and below it the findings refuted or declined, with +the reason, for the person reviewing to settle. A branch merged into `develop` without a pull +request carries the same table in the body of its merge commit. ## Review comments that state a general rule diff --git a/scripts/agent-review/prompt.md b/scripts/agent-review/prompt.md index 37035d8c..822aa356 100644 --- a/scripts/agent-review/prompt.md +++ b/scripts/agent-review/prompt.md @@ -1,23 +1,10 @@ You are a read-only reviewer of the change {base}...{branch} (commit {commit}) in this -repository. Read docs/contributing/review-checklist.md first and apply it, with the sections of -AGENTS.md it links for the areas the change touches. +repository. Read docs/contributing/review-checklist.md first and apply all of it, its questions +of duplication and silent acceptance and its report included, with the sections of AGENTS.md it +links for the areas the change touches. Get the diff with exactly this command and nothing around it: git diff {base}...{branch} -Read files with single read-only commands. Never fetch, check out, build, test or write -anything: a gate not run or a check not made is a finding, not something to go and run. - -Answer these two questions as well: - -- Duplication: does the diff copy logic, a test, a fixture or a contract that already exists, or - repeat itself? -- Silent acceptance: for each check the change adds or relies on that refuses input, which input - would it let through without a word? - -Report findings first, ordered by severity, each with its file and lines, the input or state, and -what goes wrong. With no findings, say so, and name the residual risks and the checks a read-only -review could not make. - What the author tells you about the change: {context} diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 40f304ea..20798af5 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -2,13 +2,12 @@ """Run the two read-only reviewers of docs/contributing/review.md on one commit, in parallel. Claude Code's /code-review runs in a fresh `claude -p` session and Codex in a fresh `codex exec` -run, with the models and effort pinned below, which is the one place that pins them. Each review -is saved under --out, which lies outside the tree. With --stage, each run is also a task of that -stage of the branch's Yard Log: active before it starts; done once its review is saved, with its -model, effort, commit, session or thread and tokens; open with the reason when it fails. +run, with the models pinned below, the one place that pins them, at the effort --effort names: +the first of EFFORTS, the floor, unless a person asks for more. Each review is saved under --out, +outside the tree. With --stage, each run is also a task of that stage of the branch's Yard Log. ---probe checks the setup instead: the Claude reviewer can call no tool but Agent, Bash, Read and -Skill, and the Codex reviewer cannot write in the tree. +--probe checks the setup instead: the Claude reviewer can call no tool beyond CLAUDE_TOOLS, has +no MCP server and has /code-review, and the Codex reviewer cannot write in the tree. Exits 0 when every review asked for was saved (or the probe passed), 1 when one failed, and 2 on a usage error. @@ -25,108 +24,140 @@ import sys import uuid from concurrent.futures import ThreadPoolExecutor -from dataclasses import dataclass, field from pathlib import Path CLAUDE_MODEL = "claude-opus-5-5" CODEX_MODEL = "gpt-6.2-astra" -EFFORT = "high" +# The reasoning effort of both models, which is also /code-review's level; the first is the floor. +EFFORTS = ("high", "xhigh") HERE = Path(__file__).resolve().parent ROOT = HERE.parent.parent +SETTINGS = HERE / "reviewer-settings.json" CLAUDE_TOOLS = ("Agent", "Bash", "Read", "Skill") -# The session's start event names the Agent tool by its older name, Task. -CLAUDE_TOOL_NAMES = {*CLAUDE_TOOLS, "Task"} -READ_ONLY = ( - "Read-only reviewer. The branch is already in the repository: never fetch, check out or " - "write. Use single read-only git, grep, head, tail, wc, cat or jq commands, or pipes of " - "them; no redirects, cd, variables or loops." -) PROBE_FILE = "agent-review-probe" -@dataclass +def read_only_rule() -> str: + """The Claude reviewer's system rule, naming the commands its settings allow.""" + allowed = json.loads(SETTINGS.read_text())["permissions"]["allow"] + commands = ", ".join(rule.removeprefix("Bash(").removesuffix(":*)") for rule in allowed) + return ( + "Read-only reviewer. The branch is already in the repository: never fetch, check out or " + f"write. Run only these commands, alone or piped into each other: {commands}. No " + "redirects, cd, variables or loops." + ) + + +def json_lines(text: str) -> list[dict]: + events = [] + for line in text.splitlines(): + try: + events.append(json.loads(line)) + except json.JSONDecodeError: + continue + return events + + class Run: - """One reviewer's run: what it was given, and what it left.""" - - name: str - model: str - commit: str - base: str - out: Path - session: str = field(default_factory=lambda: str(uuid.uuid4())) - text: str = "" - ident: str = "" - tokens: str = "" - error: str = "" - - @property - def label(self) -> str: - return "Claude /code-review" if self.name == "claude" else "Codex" - - @property - def review_path(self) -> Path: - return self.out / f"{self.commit[:12]}-{self.name}.md" - - @property - def raw_path(self) -> Path: - suffix = "json" if self.name == "claude" else "jsonl" - return self.out / f"{self.commit[:12]}-{self.name}.{suffix}" + """One reviewer's run on one commit: its command, and what it left.""" - def command(self, prompt: str, output: str = "json") -> list[str]: - if self.name == "claude": - return [ - "claude", "-p", "--session-id", self.session, prompt, - "--model", self.model, "--effort", EFFORT, "--output-format", output, - "--strict-mcp-config", "--permission-mode", "dontAsk", - "--tools", ",".join(CLAUDE_TOOLS), "--setting-sources", "project", - "--settings", str(HERE / "reviewer-settings.json"), - "--append-system-prompt", READ_ONLY, - ] - return [ - "codex", "exec", "--json", "--ignore-user-config", - "--disable", "apps", "--disable", "browser_use", "--disable", "computer_use", - "--sandbox", "read-only", "-C", str(ROOT), "-m", self.model, - "-c", f'model_reasoning_effort="{EFFORT}"', - "-o", str(self.review_path), "-", - ] + name = label = model = ident_noun = raw_suffix = "" + + def __init__(self, commit: str, base: str, out: Path, effort: str, tag: str = "") -> None: + self.base, self.effort = base, effort + self.short = commit[:12] + stem = f"{self.short}-{self.name}{tag}" + self.review_path = out / f"{stem}.md" + self.raw_path = out / f"{stem}.{self.raw_suffix}" + self.text = self.ident = self.tokens = self.error = "" + + def prompt(self, branch: str, text: str) -> str: + return text + + def command(self, prompt: str) -> list[str]: + raise NotImplementedError + + def stdin(self, prompt: str) -> dict: + raise NotImplementedError + + def read(self, stdout: str) -> None: + raise NotImplementedError + + def probe(self) -> tuple[bool, str]: + raise NotImplementedError def execute(self, prompt: str) -> None: """Run the reviewer to its end and keep what it left; never raises.""" - # Codex reads its prompt from standard input; Claude takes it as an argument and must - # not wait on a terminal. - stdin = {"input": prompt} if self.name == "codex" else {"stdin": subprocess.DEVNULL} - # A review left by an earlier run on the same commit must not pass for this one's. + # A review left by an earlier run must not pass for this one's. self.review_path.unlink(missing_ok=True) try: done = subprocess.run( - self.command(prompt), cwd=ROOT, capture_output=True, text=True, **stdin + self.command(prompt), cwd=ROOT, capture_output=True, text=True, + **self.stdin(prompt), ) except OSError as error: self.error = f"could not start {self.name}: {error}" return self.raw_path.write_text(done.stdout) - if self.name == "claude": - self._read_claude(done.stdout) - else: - self._read_codex(done.stdout) - if not self.error and done.returncode != 0: + self.read(done.stdout) + if self.error: + return + if done.returncode != 0: self.error = f"exited {done.returncode}: {done.stderr.strip()[-400:]}" - if not self.error and not self.text.strip(): + elif not self.text.strip(): self.error = "the reviewer printed no review" - if not self.error and self.name == "claude": - self.review_path.write_text(self.text) - def _read_claude(self, stdout: str) -> None: + def task(self, stage: str, state: str) -> dict: + """The run's Yard task, in the state given.""" + head = f"{self.label} {self.model}, effort {self.effort}" + where = f"{self.short} against {self.base}" + detail = { + "active": f"{head}, reviewing {where}.", + "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " + f"tokens: {self.tokens}. Review: {self.review_path}", + "open": f"{head}, on {where} failed: {self.error}", + }[state] + return { + "id": f"review-{self.name}-{self.short}", "kind": "task", "stage": stage, + "title": f"{self.label} review of {self.short}", "state": state, "detail": detail, + } + + +class ClaudeRun(Run): + name, label, model = "claude", "Claude /code-review", CLAUDE_MODEL + ident_noun, raw_suffix = "session", "json" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.ident = str(uuid.uuid4()) + + def prompt(self, branch: str, text: str) -> str: + return f"/code-review {self.effort} {branch} against {self.base}. {text}" + + def command(self, prompt: str, output: str = "json") -> list[str]: + return [ + "claude", "-p", "--session-id", self.ident, prompt, + "--model", self.model, "--effort", self.effort, "--output-format", output, + "--strict-mcp-config", "--permission-mode", "dontAsk", + "--tools", ",".join(CLAUDE_TOOLS), "--setting-sources", "project", + "--settings", str(SETTINGS), "--append-system-prompt", read_only_rule(), + ] + + def stdin(self, prompt: str) -> dict: + # The prompt is an argument; the session must not wait on a terminal. + return {"stdin": subprocess.DEVNULL} + + def read(self, stdout: str) -> None: try: data = json.loads(stdout) except json.JSONDecodeError: self.error = "Claude printed no JSON result" return - self.ident = data.get("session_id", self.session) self.text = data.get("result") or "" if data.get("is_error") or data.get("subtype") not in (None, "success"): self.error = f"Claude ended with {data.get('subtype')}: {self.text[:400]}" + return usage = data.get("usage") or {} ran = ", ".join(data.get("modelUsage") or {}) or "unknown" self.tokens = ( @@ -135,13 +166,56 @@ def _read_claude(self, stdout: str) -> None: f"{usage.get('cache_creation_input_tokens', 0)}, output " f"{usage.get('output_tokens', 0)}; models that ran: {ran}" ) + self.review_path.write_text(self.text) + + def task(self, stage: str, state: str) -> dict: + return {**super().task(stage, state), + "assignee": {"host": "claude-code", "session": self.ident}} + + def probe(self) -> tuple[bool, str]: + """Start a short session and read what its start event says it can call.""" + command = self.command("Say ok.", output="stream-json") + try: + done = subprocess.run( + [*command, "--verbose", "--no-session-persistence"], cwd=ROOT, + capture_output=True, text=True, stdin=subprocess.DEVNULL, + ) + except OSError as error: + return True, f"Claude could not start: {error}" + events = json_lines(done.stdout) + start = next((e for e in events if e.get("subtype") == "init"), None) + answered = any(e.get("type") == "result" and not e.get("is_error") for e in events) + if not start or not answered: + return True, f"Claude did not start or answer: {done.stderr.strip()[-400:]}" + tools, servers = start.get("tools") or [], start.get("mcp_servers") or [] + skills = start.get("skills") or start.get("slash_commands") or [] + # The start event names the Agent tool by its older name, Task. + extra = set(tools) - {*CLAUDE_TOOLS, "Task"} + bad = not tools or bool(extra) or bool(servers) or "code-review" not in skills + return bad, ( + f"Claude tools: {', '.join(tools) or 'none'}; MCP servers: {servers}; " + f"/code-review {'present' if 'code-review' in skills else 'missing'}" + ) + - def _read_codex(self, stdout: str) -> None: - for line in stdout.splitlines(): - try: - event = json.loads(line) - except json.JSONDecodeError: - continue +class CodexRun(Run): + name, label, model = "codex", "Codex", CODEX_MODEL + ident_noun, raw_suffix = "thread", "jsonl" + + def command(self, prompt: str) -> list[str]: + return [ + "codex", "exec", "--json", "--ignore-user-config", + "--disable", "apps", "--disable", "browser_use", "--disable", "computer_use", + "--sandbox", "read-only", "-C", str(ROOT), "-m", self.model, + "-c", f'model_reasoning_effort="{self.effort}"', + "-o", str(self.review_path), "-", + ] + + def stdin(self, prompt: str) -> dict: + return {"input": prompt} + + def read(self, stdout: str) -> None: + for event in json_lines(stdout): kind = event.get("type") if kind == "thread.started": self.ident = event.get("thread_id", "") @@ -160,27 +234,17 @@ def _read_codex(self, stdout: str) -> None: if self.review_path.exists(): self.text = self.review_path.read_text() - def task(self, stage: str, state: str) -> dict: - """The run's Yard task, in the state given.""" - where = f"{self.commit[:12]} against {self.base}" - if state == "active": - detail = f"{self.label} {self.model}, effort {EFFORT}, reviewing {where}." - elif state == "done": - detail = ( - f"{self.label} {self.model}, effort {EFFORT}, reviewed {where}; " - f"{'session' if self.name == 'claude' else 'thread'} {self.ident}; " - f"tokens: {self.tokens}. Review: {self.review_path}" - ) - else: - detail = f"{self.label} {self.model}, effort {EFFORT}, on {where} failed: {self.error}" - block = { - "id": f"review-{self.name}-{self.commit[:8]}", "kind": "task", "stage": stage, - "title": f"{self.label} review of {self.commit[:8]}", "state": state, - "detail": detail, - } - if self.name == "claude": - block["assignee"] = {"host": "claude-code", "session": self.session} - return block + def probe(self) -> tuple[bool, str]: + """Ask Codex to write a file in the tree, and check that the sandbox refused it.""" + target = ROOT / PROBE_FILE + self.execute(f"Run exactly `touch {PROBE_FILE}` once, then say whether it worked.") + wrote = target.exists() + target.unlink(missing_ok=True) + message = f"Codex write in the tree: {'allowed' if wrote else 'refused'}" + if self.error: + message += f"; the run failed: {self.error}" + # A Codex that never ran wrote nothing either: the run itself must succeed. + return wrote or bool(self.error), message class Yard: @@ -193,11 +257,11 @@ def __init__(self, stage: str | None, session: str | None, host: str) -> None: self.stage = None def record(self, runs: list[Run], state: str | None = None) -> None: - if not self.stage: + if not self.stage or not self.session: return batch = [run.task(self.stage, state or ("open" if run.error else "done")) for run in runs] done = subprocess.run( - ["loft", "yard", "write", "--input", "-", "--session", self.session or "", + ["loft", "yard", "write", "--input", "-", "--session", self.session, "--host", self.host, "--tree", str(ROOT), "--format", "json"], input=json.dumps(batch), capture_output=True, text=True, ) @@ -205,6 +269,9 @@ def record(self, runs: list[Run], state: str | None = None) -> None: print(f"Yard Log refused the tasks: {done.stdout or done.stderr}", file=sys.stderr) +RUNS = {"claude": ClaudeRun, "codex": CodexRun} + + def git(*args: str) -> str: return subprocess.run( ["git", *args], cwd=ROOT, capture_output=True, text=True, check=True @@ -222,23 +289,23 @@ def arguments() -> argparse.Namespace: parser.add_argument("--base", default="develop", help="what it is reviewed against") parser.add_argument("--context", type=Path, help="a file of what the author tells reviewers") parser.add_argument("--out", type=Path, required=True, help="a directory outside the tree") + parser.add_argument("--effort", choices=EFFORTS, default=EFFORTS[0]) parser.add_argument("--stage", help="the Yard Log stage whose tasks record the runs") parser.add_argument( "--session", help="the author's session, which writes the tasks; in Claude Code, its own" ) parser.add_argument("--host", default="claude-code", choices=("claude-code", "codex")) - parser.add_argument("--only", choices=("claude", "codex"), help="run one reviewer alone") + parser.add_argument("--only", choices=tuple(RUNS), help="run one reviewer alone") parser.add_argument("--dry-run", action="store_true", help="print the commands; run nothing") parser.add_argument("--probe", action="store_true", help="check the reviewers' setup") args = parser.parse_args() - out = args.out.resolve() - if out == ROOT or ROOT in out.parents: + args.out = args.out.resolve() + if args.out == ROOT or ROOT in args.out.parents: usage_error(f"--out must lie outside the tree, not in {ROOT}") if args.host == "claude-code": args.session = args.session or os.environ.get("CLAUDE_CODE_SESSION_ID") if args.stage and not args.session: usage_error("--stage needs --session, the author's session that writes the tasks") - args.out = out return args @@ -249,54 +316,22 @@ def prompt_for(args: argparse.Namespace, branch: str, commit: str) -> str: ) -def claude_start(run: Run) -> dict: - """The start event of a short Claude reviewer session, which names what it can call, or - nothing when the session did not start or did not answer.""" - command = run.command("Say ok.", output="stream-json") - command += ["--verbose", "--no-session-persistence"] - try: - done = subprocess.run( - command, cwd=ROOT, capture_output=True, text=True, stdin=subprocess.DEVNULL - ) - except OSError: - return {} - events = [] - for line in done.stdout.splitlines(): - try: - events.append(json.loads(line)) - except json.JSONDecodeError: - continue - answered = any(e.get("type") == "result" and not e.get("is_error") for e in events) - starts = [e for e in events if e.get("type") == "system" and e.get("subtype") == "init"] - return starts[0] if answered and starts else {} - - def probe(runs: list[Run]) -> int: - """Check that each reviewer can do nothing but read.""" - failed = False - for run in runs: - if run.name == "claude": - start = claude_start(run) - tools, servers = start.get("tools") or [], start.get("mcp_servers") - skills = start.get("skills") or start.get("slash_commands") or [] - extra = set(tools) - CLAUDE_TOOL_NAMES - bad = not tools or extra or servers or "code-review" not in skills - print(f"Claude tools: {', '.join(tools) or 'none'}; MCP servers: {servers}; " - f"/code-review {'present' if 'code-review' in skills else 'missing'}") - else: - target = ROOT / PROBE_FILE - run.execute(f"Run exactly `touch {PROBE_FILE}` once, then say whether it worked.") - wrote = target.exists() - target.unlink(missing_ok=True) - # A Codex that never ran writes nothing either: the run itself must succeed. - bad = wrote or run.error - print(f"Codex write in the tree: {'allowed' if wrote else 'refused'}" - f"{f'; the run failed: {run.error}' if run.error else ''}") - failed = failed or bool(bad) + """Check, both at once, that each reviewer can do nothing but read.""" + with ThreadPoolExecutor(len(runs)) as pool: + results = list(pool.map(lambda run: run.probe(), runs)) + for _, message in results: + print(message) + failed = any(bad for bad, _ in results) print("probe failed" if failed else "probe passed") return 1 if failed else 0 +def unchanged(base: str, commit: str) -> bool: + quiet = subprocess.run(["git", "diff", "--quiet", f"{base}...{commit}"], cwd=ROOT) + return quiet.returncode == 0 + + def main() -> int: args = arguments() branch = args.branch or git("rev-parse", "--abbrev-ref", "HEAD") @@ -305,28 +340,27 @@ def main() -> int: git("rev-parse", "--verify", f"{args.base}^{{commit}}") except subprocess.CalledProcessError: usage_error(f"{branch} or {args.base} is not a commit here; fetch it first") - names = [args.only] if args.only else ["claude", "codex"] - models = {"claude": CLAUDE_MODEL, "codex": CODEX_MODEL} - runs = [Run(name, models[name], commit, args.base, args.out) for name in names] - prompt = prompt_for(args, branch, commit) - claude_prompt = f"/code-review {EFFORT} {branch} against {args.base}. {prompt}" + names = [args.only] if args.only else list(RUNS) + tag = "-probe" if args.probe else "" + runs = [RUNS[name](commit, args.base, args.out, args.effort, tag) for name in names] + if args.probe: + args.out.mkdir(parents=True, exist_ok=True) + return probe(runs) + text = prompt_for(args, branch, commit) + prompts = {run.name: run.prompt(branch, text) for run in runs} if args.dry_run: for run in runs: - given = claude_prompt if run.name == "claude" else prompt - print(shlex.join(run.command(given))) - if "codex" in names: - print(f"\nCodex reads this prompt on standard input:\n\n{prompt}") + print(shlex.join(run.command(prompts[run.name]))) + if "codex" in prompts: + print(f"\nCodex reads this prompt on standard input:\n\n{prompts['codex']}") return 0 - args.out.mkdir(parents=True, exist_ok=True) - if args.probe: - return probe(runs) - if not git("diff", "--name-only", f"{args.base}...{commit}"): + if unchanged(args.base, commit): usage_error(f"{branch} holds no change against {args.base}: there is nothing to review") + args.out.mkdir(parents=True, exist_ok=True) yard = Yard(args.stage, args.session, args.host) yard.record(runs, "active") with ThreadPoolExecutor(len(runs)) as pool: - for run in runs: - pool.submit(run.execute, claude_prompt if run.name == "claude" else prompt) + list(pool.map(lambda run: run.execute(prompts[run.name]), runs)) yard.record(runs) for run in runs: print(f"{run.label}: {run.error or run.review_path}", file=sys.stderr) From eb9bc35e4f2f3c577cd1392352a08ca6b440558c Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:28:13 +0000 Subject: [PATCH 09/49] scripts: keep local paths out of a review's Yard task, and count Claude's tokens The task names the saved review by its file name alone, not by its path on the machine. The tokens of a Claude run are summed from each model's counts in modelUsage, since the top-level usage of a print-mode result reads zero. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 20798af5..447892cb 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -115,7 +115,7 @@ def task(self, stage: str, state: str) -> dict: detail = { "active": f"{head}, reviewing {where}.", "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " - f"tokens: {self.tokens}. Review: {self.review_path}", + f"tokens: {self.tokens}. Review: {self.review_path.name}", "open": f"{head}, on {where} failed: {self.error}", }[state] return { @@ -158,13 +158,17 @@ def read(self, stdout: str) -> None: if data.get("is_error") or data.get("subtype") not in (None, "success"): self.error = f"Claude ended with {data.get('subtype')}: {self.text[:400]}" return - usage = data.get("usage") or {} - ran = ", ".join(data.get("modelUsage") or {}) or "unknown" + # The top-level usage of a print-mode result can read zero; each model's own counts, + # subagents included, are in modelUsage. + models = data.get("modelUsage") or {} + + def total(key: str) -> int: + return sum(usage.get(key, 0) for usage in models.values()) + self.tokens = ( - f"input {usage.get('input_tokens', 0)}, cache read " - f"{usage.get('cache_read_input_tokens', 0)}, cache write " - f"{usage.get('cache_creation_input_tokens', 0)}, output " - f"{usage.get('output_tokens', 0)}; models that ran: {ran}" + f"input {total('inputTokens')}, cache read {total('cacheReadInputTokens')}, " + f"cache write {total('cacheCreationInputTokens')}, output {total('outputTokens')}; " + f"models that ran: {', '.join(models) or 'unknown'}" ) self.review_path.write_text(self.text) From a3088678cc241701d204008228fe66dec7efeae4 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:37:02 +0000 Subject: [PATCH 10/49] scripts: review the pinned commit, count a run only when it read the diff, and probe for real The runner reviews the checked-out commit of a clean tree against its base, and names both commits in the diff the reviewers are told to run. A run counts as a review only when its stream shows that exact diff run with success: Claude's in stream-json, Codex's in its command items. Each invocation has its own files and Yard tasks; each run records its end as it ends, and any failure becomes its task's reason rather than a traceback; a Yard write refused exits 1, and a --stage without loft, or without a host and session to write as, is refused. The host is inferred from the environment it runs in. A Codex error counts only when no turn completed, and git that cannot compare the commits is a usage error. The probe shows each refusal: Claude must try a write that dontAsk denies, asked without the read-only rule, which makes a model decline to try; Codex's read-only sandbox must refuse a write and allow a read, tried without a model, since codex exec shows no event for a command the sandbox refused. Both probe paths are new to the probe, so no file of the tree is removed. The runner is now review.py (the command), reviewers.py (the two reviewers) and probe.py. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/probe.py | 105 +++++++++ scripts/agent-review/prompt.md | 4 +- scripts/agent-review/review.py | 375 ++++++++---------------------- scripts/agent-review/reviewers.py | 259 +++++++++++++++++++++ 4 files changed, 460 insertions(+), 283 deletions(-) create mode 100644 scripts/agent-review/probe.py create mode 100644 scripts/agent-review/reviewers.py diff --git a/scripts/agent-review/probe.py b/scripts/agent-review/probe.py new file mode 100644 index 00000000..717a1cef --- /dev/null +++ b/scripts/agent-review/probe.py @@ -0,0 +1,105 @@ +"""The setup check of review.py --probe. + +The Claude reviewer is asked to write a file in the tree, and passes only when `dontAsk` refused +the attempt and its session could call no more than it should. Codex's sandbox is tried without +a model, since `codex exec --json` shows no event for a command the sandbox refused: under the +read-only policy a write must fail and a read succeed; and the Codex reviewer must answer a turn. +""" + +from __future__ import annotations + +import secrets +import subprocess + +from reviewers import ( + CLAUDE_TOOLS, NO_DIFF, ROOT, ClaudeRun, CodexRun, Run, json_lines, +) + +# The start event names the Agent tool by its older name, Task. +CLAUDE_TOOL_NAMES = {*CLAUDE_TOOLS, "Task"} + + +def write_request(path: str) -> str: + return ( + f"This is a permission check. Run exactly `touch {path}` with the Bash tool once, even " + "if you expect it to be refused, then say whether it worked." + ) + + +def claude_verdict(events: list[dict], path: str, wrote: bool) -> tuple[bool, str]: + """Whether the Claude reviewer failed the probe, and what it showed.""" + start = next((e for e in events if e.get("subtype") == "init"), None) + result = next((e for e in reversed(events) if e.get("type") == "result"), None) + if not start or not result or result.get("is_error"): + return True, "Claude did not start or answer" + tools, servers = start.get("tools") or [], start.get("mcp_servers") or [] + skills = start.get("skills") or start.get("slash_commands") or [] + denied = [ + (d.get("tool_input") or {}).get("command", "") + for d in result.get("permission_denials") or [] + ] + refused = any(path in command for command in denied) + extra = set(tools) - CLAUDE_TOOL_NAMES + bad = wrote or not refused or not tools or bool(extra) or bool(servers) + bad = bad or "code-review" not in skills + return bad, ( + f"Claude tools: {', '.join(tools) or 'none'}; MCP servers: {servers}; /code-review " + f"{'present' if 'code-review' in skills else 'missing'}; write " + f"{'made' if wrote else 'refused by dontAsk' if refused else 'never tried'}" + ) + + +def sandboxed(command: list[str]) -> int: + """The exit code of a command run under Codex's read-only sandbox policy.""" + done = subprocess.run( + ["codex", "sandbox", "-c", 'sandbox_mode="read-only"', "--", *command], + cwd=ROOT, capture_output=True, text=True, + ) + return done.returncode + + +def codex_verdict(wrote: bool, write_code: int, read_code: int, error: str) -> tuple[bool, str]: + """Whether Codex failed the probe, and what it showed.""" + shown = "made" if wrote else "refused by the sandbox" if write_code != 0 else "not refused" + read = "allowed" if read_code == 0 else "refused" + message = f"Codex write in the tree: {shown}; read: {read}" + if error: + message += f"; the reviewer did not answer: {error}" + return wrote or write_code == 0 or read_code != 0 or bool(error), message + + +def probe_claude(run: ClaudeRun, path: str) -> tuple[bool, str]: + # At low effort, since a model that reasons long may decline a write it expects refused. + check = ClaudeRun(run.target, run.review_path.parent, "low") + command = check.command(write_request(path), rule=False) + ["--no-session-persistence"] + try: + done = subprocess.run( + command, cwd=ROOT, capture_output=True, text=True, stdin=subprocess.DEVNULL + ) + except OSError as error: + return True, f"Claude could not start: {error}" + return claude_verdict(json_lines(done.stdout), path, (ROOT / path).exists()) + + +def probe_codex(run: CodexRun, path: str) -> tuple[bool, str]: + try: + write_code = sandboxed(["touch", path]) + read_code = sandboxed(["cat", "AGENTS.md"]) + except OSError as error: + return True, f"Codex could not start: {error}" + run.execute("Say ok.") + # The run is no review, so only its own failure counts, not the lack of a diff. + error = "" if run.error.startswith(NO_DIFF) else run.error + return codex_verdict((ROOT / path).exists(), write_code, read_code, error) + + +def probe(run: Run) -> tuple[bool, str]: + """Probe one reviewer on a path of its own that nothing in the tree holds.""" + path = f"agent-review-probe-{secrets.token_hex(4)}" + try: + if isinstance(run, ClaudeRun): + return probe_claude(run, path) + return probe_codex(run, path) + finally: + # The path is new to this probe, so whatever lies there now the reviewer wrote. + (ROOT / path).unlink(missing_ok=True) diff --git a/scripts/agent-review/prompt.md b/scripts/agent-review/prompt.md index 822aa356..460f191e 100644 --- a/scripts/agent-review/prompt.md +++ b/scripts/agent-review/prompt.md @@ -1,9 +1,9 @@ -You are a read-only reviewer of the change {base}...{branch} (commit {commit}) in this +You are a read-only reviewer of the change {range}, the branch {branch} against {base}, in this repository. Read docs/contributing/review-checklist.md first and apply all of it, its questions of duplication and silent acceptance and its report included, with the sections of AGENTS.md it links for the areas the change touches. -Get the diff with exactly this command and nothing around it: git diff {base}...{branch} +Get the diff with exactly this command and nothing around it: {diff} What the author tells you about the change: diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 447892cb..da293085 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -1,16 +1,17 @@ #!/usr/bin/env python3 -"""Run the two read-only reviewers of docs/contributing/review.md on one commit, in parallel. +"""Run the two read-only reviewers of docs/contributing/review.md on the checked-out commit. Claude Code's /code-review runs in a fresh `claude -p` session and Codex in a fresh `codex exec` -run, with the models pinned below, the one place that pins them, at the effort --effort names: -the first of EFFORTS, the floor, unless a person asks for more. Each review is saved under --out, -outside the tree. With --stage, each run is also a task of that stage of the branch's Yard Log. +run, in parallel, with the models reviewers.py pins, the one place that pins them, at the effort +--effort names: the first of EFFORTS, the floor, unless a person asks for more. The worktree must +be clean at the commit reviewed, since the reviewers read its files. Each review is saved under +--out, outside the tree, with names of its own invocation. With --stage, each run is also a task +of that stage of the branch's Yard Log, written when it starts and again when it ends. ---probe checks the setup instead: the Claude reviewer can call no tool beyond CLAUDE_TOOLS, has -no MCP server and has /code-review, and the Codex reviewer cannot write in the tree. +--probe checks the setup instead (probe.py). -Exits 0 when every review asked for was saved (or the probe passed), 1 when one failed, and 2 on -a usage error. +Exits 0 when every review asked for was saved and recorded (or the probe passed), 1 when a run +failed or Yard Log refused its task, and 2 on a usage error. """ from __future__ import annotations @@ -22,258 +23,35 @@ import shutil import subprocess import sys -import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path -CLAUDE_MODEL = "claude-opus-5-5" -CODEX_MODEL = "gpt-6.2-astra" -# The reasoning effort of both models, which is also /code-review's level; the first is the floor. -EFFORTS = ("high", "xhigh") - -HERE = Path(__file__).resolve().parent -ROOT = HERE.parent.parent -SETTINGS = HERE / "reviewer-settings.json" -CLAUDE_TOOLS = ("Agent", "Bash", "Read", "Skill") -PROBE_FILE = "agent-review-probe" - - -def read_only_rule() -> str: - """The Claude reviewer's system rule, naming the commands its settings allow.""" - allowed = json.loads(SETTINGS.read_text())["permissions"]["allow"] - commands = ", ".join(rule.removeprefix("Bash(").removesuffix(":*)") for rule in allowed) - return ( - "Read-only reviewer. The branch is already in the repository: never fetch, check out or " - f"write. Run only these commands, alone or piped into each other: {commands}. No " - "redirects, cd, variables or loops." - ) - - -def json_lines(text: str) -> list[dict]: - events = [] - for line in text.splitlines(): - try: - events.append(json.loads(line)) - except json.JSONDecodeError: - continue - return events - - -class Run: - """One reviewer's run on one commit: its command, and what it left.""" - - name = label = model = ident_noun = raw_suffix = "" - - def __init__(self, commit: str, base: str, out: Path, effort: str, tag: str = "") -> None: - self.base, self.effort = base, effort - self.short = commit[:12] - stem = f"{self.short}-{self.name}{tag}" - self.review_path = out / f"{stem}.md" - self.raw_path = out / f"{stem}.{self.raw_suffix}" - self.text = self.ident = self.tokens = self.error = "" - - def prompt(self, branch: str, text: str) -> str: - return text - - def command(self, prompt: str) -> list[str]: - raise NotImplementedError - - def stdin(self, prompt: str) -> dict: - raise NotImplementedError - - def read(self, stdout: str) -> None: - raise NotImplementedError - - def probe(self) -> tuple[bool, str]: - raise NotImplementedError - - def execute(self, prompt: str) -> None: - """Run the reviewer to its end and keep what it left; never raises.""" - # A review left by an earlier run must not pass for this one's. - self.review_path.unlink(missing_ok=True) - try: - done = subprocess.run( - self.command(prompt), cwd=ROOT, capture_output=True, text=True, - **self.stdin(prompt), - ) - except OSError as error: - self.error = f"could not start {self.name}: {error}" - return - self.raw_path.write_text(done.stdout) - self.read(done.stdout) - if self.error: - return - if done.returncode != 0: - self.error = f"exited {done.returncode}: {done.stderr.strip()[-400:]}" - elif not self.text.strip(): - self.error = "the reviewer printed no review" - - def task(self, stage: str, state: str) -> dict: - """The run's Yard task, in the state given.""" - head = f"{self.label} {self.model}, effort {self.effort}" - where = f"{self.short} against {self.base}" - detail = { - "active": f"{head}, reviewing {where}.", - "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " - f"tokens: {self.tokens}. Review: {self.review_path.name}", - "open": f"{head}, on {where} failed: {self.error}", - }[state] - return { - "id": f"review-{self.name}-{self.short}", "kind": "task", "stage": stage, - "title": f"{self.label} review of {self.short}", "state": state, "detail": detail, - } - - -class ClaudeRun(Run): - name, label, model = "claude", "Claude /code-review", CLAUDE_MODEL - ident_noun, raw_suffix = "session", "json" - - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self.ident = str(uuid.uuid4()) - - def prompt(self, branch: str, text: str) -> str: - return f"/code-review {self.effort} {branch} against {self.base}. {text}" - - def command(self, prompt: str, output: str = "json") -> list[str]: - return [ - "claude", "-p", "--session-id", self.ident, prompt, - "--model", self.model, "--effort", self.effort, "--output-format", output, - "--strict-mcp-config", "--permission-mode", "dontAsk", - "--tools", ",".join(CLAUDE_TOOLS), "--setting-sources", "project", - "--settings", str(SETTINGS), "--append-system-prompt", read_only_rule(), - ] - - def stdin(self, prompt: str) -> dict: - # The prompt is an argument; the session must not wait on a terminal. - return {"stdin": subprocess.DEVNULL} - - def read(self, stdout: str) -> None: - try: - data = json.loads(stdout) - except json.JSONDecodeError: - self.error = "Claude printed no JSON result" - return - self.text = data.get("result") or "" - if data.get("is_error") or data.get("subtype") not in (None, "success"): - self.error = f"Claude ended with {data.get('subtype')}: {self.text[:400]}" - return - # The top-level usage of a print-mode result can read zero; each model's own counts, - # subagents included, are in modelUsage. - models = data.get("modelUsage") or {} - - def total(key: str) -> int: - return sum(usage.get(key, 0) for usage in models.values()) - - self.tokens = ( - f"input {total('inputTokens')}, cache read {total('cacheReadInputTokens')}, " - f"cache write {total('cacheCreationInputTokens')}, output {total('outputTokens')}; " - f"models that ran: {', '.join(models) or 'unknown'}" - ) - self.review_path.write_text(self.text) - - def task(self, stage: str, state: str) -> dict: - return {**super().task(stage, state), - "assignee": {"host": "claude-code", "session": self.ident}} - - def probe(self) -> tuple[bool, str]: - """Start a short session and read what its start event says it can call.""" - command = self.command("Say ok.", output="stream-json") - try: - done = subprocess.run( - [*command, "--verbose", "--no-session-persistence"], cwd=ROOT, - capture_output=True, text=True, stdin=subprocess.DEVNULL, - ) - except OSError as error: - return True, f"Claude could not start: {error}" - events = json_lines(done.stdout) - start = next((e for e in events if e.get("subtype") == "init"), None) - answered = any(e.get("type") == "result" and not e.get("is_error") for e in events) - if not start or not answered: - return True, f"Claude did not start or answer: {done.stderr.strip()[-400:]}" - tools, servers = start.get("tools") or [], start.get("mcp_servers") or [] - skills = start.get("skills") or start.get("slash_commands") or [] - # The start event names the Agent tool by its older name, Task. - extra = set(tools) - {*CLAUDE_TOOLS, "Task"} - bad = not tools or bool(extra) or bool(servers) or "code-review" not in skills - return bad, ( - f"Claude tools: {', '.join(tools) or 'none'}; MCP servers: {servers}; " - f"/code-review {'present' if 'code-review' in skills else 'missing'}" - ) +from probe import probe +from reviewers import EFFORTS, HERE, ROOT, RUNS, Run, Target - -class CodexRun(Run): - name, label, model = "codex", "Codex", CODEX_MODEL - ident_noun, raw_suffix = "thread", "jsonl" - - def command(self, prompt: str) -> list[str]: - return [ - "codex", "exec", "--json", "--ignore-user-config", - "--disable", "apps", "--disable", "browser_use", "--disable", "computer_use", - "--sandbox", "read-only", "-C", str(ROOT), "-m", self.model, - "-c", f'model_reasoning_effort="{self.effort}"', - "-o", str(self.review_path), "-", - ] - - def stdin(self, prompt: str) -> dict: - return {"input": prompt} - - def read(self, stdout: str) -> None: - for event in json_lines(stdout): - kind = event.get("type") - if kind == "thread.started": - self.ident = event.get("thread_id", "") - elif kind == "turn.completed": - usage = event.get("usage") or {} - self.tokens = ( - f"input {usage.get('input_tokens', 0)}, cached " - f"{usage.get('cached_input_tokens', 0)}, output " - f"{usage.get('output_tokens', 0)}, reasoning " - f"{usage.get('reasoning_output_tokens', 0)}" - ) - elif kind == "turn.failed": - self.error = (event.get("error") or {}).get("message", "the turn failed") - elif kind == "error" and not self.error: - self.error = event.get("message", "Codex reported an error") - if self.review_path.exists(): - self.text = self.review_path.read_text() - - def probe(self) -> tuple[bool, str]: - """Ask Codex to write a file in the tree, and check that the sandbox refused it.""" - target = ROOT / PROBE_FILE - self.execute(f"Run exactly `touch {PROBE_FILE}` once, then say whether it worked.") - wrote = target.exists() - target.unlink(missing_ok=True) - message = f"Codex write in the tree: {'allowed' if wrote else 'refused'}" - if self.error: - message += f"; the run failed: {self.error}" - # A Codex that never ran wrote nothing either: the run itself must succeed. - return wrote or bool(self.error), message +# The variable each host sets to the session an agent runs in, as Yard Log names it. +SESSIONS = {"claude-code": "CLAUDE_CODE_SESSION_ID", "codex": "CODEX_THREAD_ID"} class Yard: - """Writes each run's task into the branch's Yard Log, or nothing without --stage or loft.""" + """Writes each run's task into the branch's Yard Log, or nothing without --stage.""" - def __init__(self, stage: str | None, session: str | None, host: str) -> None: + def __init__(self, stage: str | None, session: str | None, host: str | None) -> None: self.stage, self.session, self.host = stage, session, host - if stage and shutil.which("loft") is None: - print("loft is not on PATH: the runs are not recorded in Yard Log", file=sys.stderr) - self.stage = None - def record(self, runs: list[Run], state: str | None = None) -> None: - if not self.stage or not self.session: - return + def record(self, runs: list[Run], state: str | None = None) -> bool: + """Write the runs' tasks; whether Yard Log took them, or nothing was asked.""" + if not self.stage: + return True batch = [run.task(self.stage, state or ("open" if run.error else "done")) for run in runs] done = subprocess.run( - ["loft", "yard", "write", "--input", "-", "--session", self.session, - "--host", self.host, "--tree", str(ROOT), "--format", "json"], + ["loft", "yard", "write", "--input", "-", "--session", str(self.session), + "--host", str(self.host), "--tree", str(ROOT), "--format", "json"], input=json.dumps(batch), capture_output=True, text=True, ) if done.returncode != 0: print(f"Yard Log refused the tasks: {done.stdout or done.stderr}", file=sys.stderr) - - -RUNS = {"claude": ClaudeRun, "codex": CodexRun} + return done.returncode == 0 def git(*args: str) -> str: @@ -287,43 +65,85 @@ def usage_error(message: str) -> None: sys.exit(2) +def changed(returncode: int) -> bool: + """What `git diff --quiet` says by its exit code; a code above 1 is a failure to compare.""" + if returncode > 1: + raise ValueError(f"git could not compare the commits (exit {returncode})") + return returncode == 1 + + +def host_and_session(host: str | None, session: str | None) -> tuple[str | None, str | None]: + """The author's host and session: as given, else as the environment of the host names.""" + if host is None: + host = next((h for h, variable in SESSIONS.items() if os.environ.get(variable)), None) + if host is not None and session is None: + session = os.environ.get(SESSIONS[host]) + return host, session + + def arguments() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--branch", help="the branch reviewed; the current one when not given") - parser.add_argument("--base", default="develop", help="what it is reviewed against") + parser.add_argument("--base", default="develop", help="what the commit is reviewed against") parser.add_argument("--context", type=Path, help="a file of what the author tells reviewers") parser.add_argument("--out", type=Path, required=True, help="a directory outside the tree") parser.add_argument("--effort", choices=EFFORTS, default=EFFORTS[0]) parser.add_argument("--stage", help="the Yard Log stage whose tasks record the runs") + parser.add_argument("--session", help="the author's session; its host's own when not given") parser.add_argument( - "--session", help="the author's session, which writes the tasks; in Claude Code, its own" + "--host", choices=tuple(SESSIONS), help="the author's host; the one running this by default" ) - parser.add_argument("--host", default="claude-code", choices=("claude-code", "codex")) parser.add_argument("--only", choices=tuple(RUNS), help="run one reviewer alone") - parser.add_argument("--dry-run", action="store_true", help="print the commands; run nothing") - parser.add_argument("--probe", action="store_true", help="check the reviewers' setup") + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--dry-run", action="store_true", help="print the commands; run nothing") + mode.add_argument("--probe", action="store_true", help="check the reviewers' setup") args = parser.parse_args() args.out = args.out.resolve() if args.out == ROOT or ROOT in args.out.parents: usage_error(f"--out must lie outside the tree, not in {ROOT}") - if args.host == "claude-code": - args.session = args.session or os.environ.get("CLAUDE_CODE_SESSION_ID") - if args.stage and not args.session: - usage_error("--stage needs --session, the author's session that writes the tasks") + args.host, args.session = host_and_session(args.host, args.session) + if args.stage and not (args.host and args.session): + usage_error("--stage needs the author's --host and --session; neither could be inferred") + if args.stage and shutil.which("loft") is None: + usage_error("--stage needs loft on PATH, to record the runs in Yard Log") return args -def prompt_for(args: argparse.Namespace, branch: str, commit: str) -> str: +def target_of(base: str, to_review: bool) -> Target: + """The checked-out commit against the base. To be reviewed, the tree must be clean, since the + reviewers read its files, and the commit must differ from the base.""" + try: + head = git("rev-parse", "--verify", "HEAD^{commit}") + base_commit = git("rev-parse", "--verify", f"{base}^{{commit}}") + branch = git("rev-parse", "--abbrev-ref", "HEAD") + dirty = git("status", "--porcelain") + except subprocess.CalledProcessError as error: + usage_error(f"git: {error.stderr.strip()}; fetch {base} first") + target = Target(base, base_commit, head, branch) + if not to_review: + return target + if dirty: + usage_error("the tree holds uncommitted changes, which the reviewers would read; commit " + "or stash them") + quiet = subprocess.run(["git", "diff", "--quiet", target.range], cwd=ROOT) + try: + if not changed(quiet.returncode): + usage_error(f"{branch} holds no change against {base}: there is nothing to review") + except ValueError as error: + usage_error(f"{error}: {target.range}") + return target + + +def prompt_for(args: argparse.Namespace, target: Target) -> str: context = args.context.read_text().strip() if args.context else "" return (HERE / "prompt.md").read_text().format( - base=args.base, branch=branch, commit=commit, context=context or "Nothing more." + base=target.base, branch=target.branch, range=target.range, diff=target.diff, + context=context or "Nothing more.", ) -def probe(runs: list[Run]) -> int: - """Check, both at once, that each reviewer can do nothing but read.""" +def run_probes(runs: list[Run]) -> int: with ThreadPoolExecutor(len(runs)) as pool: - results = list(pool.map(lambda run: run.probe(), runs)) + results = list(pool.map(probe, runs)) for _, message in results: print(message) failed = any(bad for bad, _ in results) @@ -331,44 +151,37 @@ def probe(runs: list[Run]) -> int: return 1 if failed else 0 -def unchanged(base: str, commit: str) -> bool: - quiet = subprocess.run(["git", "diff", "--quiet", f"{base}...{commit}"], cwd=ROOT) - return quiet.returncode == 0 - - def main() -> int: args = arguments() - branch = args.branch or git("rev-parse", "--abbrev-ref", "HEAD") - try: - commit = git("rev-parse", "--verify", f"{branch}^{{commit}}") - git("rev-parse", "--verify", f"{args.base}^{{commit}}") - except subprocess.CalledProcessError: - usage_error(f"{branch} or {args.base} is not a commit here; fetch it first") + target = target_of(args.base, to_review=not (args.probe or args.dry_run)) names = [args.only] if args.only else list(RUNS) - tag = "-probe" if args.probe else "" - runs = [RUNS[name](commit, args.base, args.out, args.effort, tag) for name in names] + runs = [RUNS[name](target, args.out, args.effort) for name in names] if args.probe: args.out.mkdir(parents=True, exist_ok=True) - return probe(runs) - text = prompt_for(args, branch, commit) - prompts = {run.name: run.prompt(branch, text) for run in runs} + return run_probes(runs) + text = prompt_for(args, target) + prompts = {run.name: run.prompt(text) for run in runs} if args.dry_run: for run in runs: print(shlex.join(run.command(prompts[run.name]))) if "codex" in prompts: print(f"\nCodex reads this prompt on standard input:\n\n{prompts['codex']}") return 0 - if unchanged(args.base, commit): - usage_error(f"{branch} holds no change against {args.base}: there is nothing to review") args.out.mkdir(parents=True, exist_ok=True) yard = Yard(args.stage, args.session, args.host) - yard.record(runs, "active") + if not yard.record(runs, "active"): + return 1 + + def review(run: Run) -> bool: + # Each run records its own end as soon as it ends, whatever the other one does. + run.execute(prompts[run.name]) + return yard.record([run]) + with ThreadPoolExecutor(len(runs)) as pool: - list(pool.map(lambda run: run.execute(prompts[run.name]), runs)) - yard.record(runs) + recorded = list(pool.map(review, runs)) for run in runs: print(f"{run.label}: {run.error or run.review_path}", file=sys.stderr) - return 1 if any(run.error for run in runs) else 0 + return 1 if any(run.error for run in runs) or not all(recorded) else 0 if __name__ == "__main__": diff --git a/scripts/agent-review/reviewers.py b/scripts/agent-review/reviewers.py new file mode 100644 index 00000000..5181eb8e --- /dev/null +++ b/scripts/agent-review/reviewers.py @@ -0,0 +1,259 @@ +"""The two reviewers review.py runs: how each is started, and what its run left. + +A run counts as a review only when its reviewer read the round's diff: the exact +`git diff ...` the prompt names, run with success. Anything less, from a refused +command to output the runner cannot read, fails the run with its reason, and never raises. +""" + +from __future__ import annotations + +import json +import secrets +import subprocess +import uuid +from pathlib import Path + +CLAUDE_MODEL = "claude-opus-5-5" +CODEX_MODEL = "gpt-6.2-astra" +# The reasoning effort of both models, which is also /code-review's level; the first is the floor. +EFFORTS = ("high", "xhigh") + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +SETTINGS = HERE / "reviewer-settings.json" +CLAUDE_TOOLS = ("Agent", "Bash", "Read", "Skill") +NO_DIFF = "the reviewer never read the diff" + + +def read_only_rule() -> str: + """The Claude reviewer's system rule, naming the commands its settings allow.""" + allowed = json.loads(SETTINGS.read_text())["permissions"]["allow"] + commands = ", ".join(rule.removeprefix("Bash(").removesuffix(":*)") for rule in allowed) + return ( + "Read-only reviewer. The branch is already in the repository: never fetch, check out or " + f"write. Run only these commands, alone or piped into each other: {commands}. No " + "redirects, cd, variables or loops." + ) + + +def json_lines(text: str) -> list[dict]: + """The JSON objects of a stream, one per line; any other line is skipped.""" + events = [] + for line in text.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(event, dict): + events.append(event) + return events + + +class Target: + """What a round reviews: the base and head commits, and the names they are known by.""" + + def __init__(self, base: str, base_commit: str, head: str, branch: str) -> None: + self.base, self.base_commit, self.head, self.branch = base, base_commit, head, branch + self.short = head[:12] + self.range = f"{base_commit}...{head}" + self.diff = f"git diff {self.range}" + + def is_diff(self, command: str) -> bool: + """Whether a shell command a reviewer ran reads this round's diff.""" + return "git diff" in command and self.range in command + + +class Run: + """One reviewer's run on a target: its command, and what it left.""" + + name = label = model = ident_noun = raw_suffix = "" + + def __init__(self, target: Target, out: Path, effort: str) -> None: + self.target, self.effort = target, effort + # Each invocation has its own files and its own Yard task, so no run overwrites another. + self.key = f"{target.short}-{secrets.token_hex(3)}" + self.review_path = out / f"{self.key}-{self.name}.md" + self.raw_path = out / f"{self.key}-{self.name}.{self.raw_suffix}" + self.text = self.ident = self.tokens = self.error = "" + self.read_the_diff = False + self.events: list[dict] = [] + + def prompt(self, text: str) -> str: + return text + + def command(self, prompt: str) -> list[str]: + raise NotImplementedError + + def stdin(self, prompt: str) -> dict: + raise NotImplementedError + + def read(self, stdout: str) -> None: + raise NotImplementedError + + def execute(self, prompt: str) -> None: + """Run the reviewer to its end and keep what it left; a failure is kept, never raised.""" + try: + done = subprocess.run( + self.command(prompt), cwd=ROOT, capture_output=True, text=True, + **self.stdin(prompt), + ) + self.raw_path.write_text(done.stdout) + self.read(done.stdout) + self.judge(done.returncode, done.stderr) + except Exception as error: # A run's failure is its task's reason, not a traceback. + self.error = self.error or f"{type(error).__name__}: {error}" + + def judge(self, returncode: int, stderr: str) -> None: + """Set the run's error from what it left, when what it left is not a review.""" + if self.error: + return + if returncode != 0: + self.error = f"exited {returncode}: {stderr.strip()[-400:]}" + elif not self.text.strip(): + self.error = "the reviewer printed no review" + elif not self.read_the_diff: + self.error = f"{NO_DIFF} ({self.target.diff})" + + def task(self, stage: str, state: str) -> dict: + """The run's Yard task, in the state given.""" + head = f"{self.label} {self.model}, effort {self.effort}" + where = f"{self.target.short} against {self.target.base}" + detail = { + "active": f"{head}, reviewing {where}.", + "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " + f"tokens: {self.tokens}. Review: {self.review_path.name}", + "open": f"{head}, on {where} failed: {self.error}", + }[state] + return { + "id": f"review-{self.name}-{self.key}", "kind": "task", "stage": stage, + "title": f"{self.label} review of {self.target.short}", "state": state, + "detail": detail, + } + + +class ClaudeRun(Run): + name, label, model = "claude", "Claude /code-review", CLAUDE_MODEL + ident_noun, raw_suffix = "session", "jsonl" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.ident = str(uuid.uuid4()) + + def prompt(self, text: str) -> str: + target = self.target + return f"/code-review {self.effort} {target.branch} against {target.base}. {text}" + + def command(self, prompt: str, rule: bool = True) -> list[str]: + # The stream shows each command the reviewer ran, and so whether it read the diff. + # Without the rule, the session keeps its permissions but is not told them, as the probe + # needs it: a model told which commands it may run declines to try another. + told = ["--append-system-prompt", read_only_rule()] if rule else [] + return [ + "claude", "-p", "--session-id", self.ident, prompt, + "--model", self.model, "--effort", self.effort, + "--output-format", "stream-json", "--verbose", + "--strict-mcp-config", "--permission-mode", "dontAsk", + "--tools", ",".join(CLAUDE_TOOLS), "--setting-sources", "project", + "--settings", str(SETTINGS), *told, + ] + + def stdin(self, prompt: str) -> dict: + # The prompt is an argument; the session must not wait on a terminal. + return {"stdin": subprocess.DEVNULL} + + def read(self, stdout: str) -> None: + self.events = json_lines(stdout) + result = next((e for e in reversed(self.events) if e.get("type") == "result"), None) + if result is None: + self.error = "Claude printed no result" + return + self.text = result.get("result") or "" + if result.get("is_error") or result.get("subtype") != "success": + self.error = f"Claude ended with {result.get('subtype')}: {self.text[:400]}" + return + self.read_the_diff = any(self.target.is_diff(c) for c in succeeded_commands(self.events)) + # The top-level usage of a print-mode result can read zero; each model's own counts, + # subagents included, are in modelUsage. + models = result.get("modelUsage") or {} + + def total(key: str) -> int: + return sum(usage.get(key, 0) for usage in models.values()) + + self.tokens = ( + f"input {total('inputTokens')}, cache read {total('cacheReadInputTokens')}, " + f"cache write {total('cacheCreationInputTokens')}, output {total('outputTokens')}; " + f"models that ran: {', '.join(models) or 'unknown'}" + ) + self.review_path.write_text(self.text) + + +def succeeded_commands(events: list[dict]) -> list[str]: + """The Bash commands of a Claude stream, its subagents' included, whose result was no error.""" + calls, succeeded = {}, set() + for event in events: + content = (event.get("message") or {}).get("content") + for block in content if isinstance(content, list) else []: + if block.get("type") == "tool_use" and block.get("name") == "Bash": + calls[block.get("id")] = (block.get("input") or {}).get("command", "") + elif block.get("type") == "tool_result" and not block.get("is_error"): + succeeded.add(block.get("tool_use_id")) + return [command for id_, command in calls.items() if id_ in succeeded] + + +class CodexRun(Run): + name, label, model = "codex", "Codex", CODEX_MODEL + ident_noun, raw_suffix = "thread", "jsonl" + + def command(self, prompt: str) -> list[str]: + return [ + "codex", "exec", "--json", "--ignore-user-config", + "--disable", "apps", "--disable", "browser_use", "--disable", "computer_use", + "--sandbox", "read-only", "-C", str(ROOT), "-m", self.model, + "-c", f'model_reasoning_effort="{self.effort}"', + "-o", str(self.review_path), "-", + ] + + def stdin(self, prompt: str) -> dict: + return {"input": prompt} + + def read(self, stdout: str) -> None: + self.events = json_lines(stdout) + completed, errors = False, [] + for event in self.events: + kind = event.get("type") + if kind == "thread.started": + self.ident = event.get("thread_id", "") + elif kind == "turn.completed": + completed = True + self.tokens = codex_tokens(event.get("usage") or {}) + elif kind == "turn.failed": + self.error = (event.get("error") or {}).get("message", "the turn failed") + elif kind == "error": + # A stream that reconnects reports an error and goes on; only a turn that never + # completes makes it the run's failure. + errors.append(event.get("message", "Codex reported an error")) + if not completed and not self.error: + self.error = errors[-1] if errors else "Codex completed no turn" + self.read_the_diff = any( + self.target.is_diff(item.get("command", "")) and item.get("exit_code") == 0 + for item in codex_commands(self.events) + ) + if self.review_path.exists(): + self.text = self.review_path.read_text() + + +def codex_tokens(usage: dict) -> str: + return ( + f"input {usage.get('input_tokens', 0)}, cached {usage.get('cached_input_tokens', 0)}, " + f"output {usage.get('output_tokens', 0)}, reasoning " + f"{usage.get('reasoning_output_tokens', 0)}" + ) + + +def codex_commands(events: list[dict]) -> list[dict]: + """The shell commands a Codex stream completed, each with its command and exit code.""" + items = [event.get("item") or {} for event in events if event.get("type") == "item.completed"] + return [item for item in items if item.get("type") == "command_execution"] + + +RUNS = {"claude": ClaudeRun, "codex": CodexRun} From 53805a9297bcd0475da720036c91a9a4eb3d4905 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:38:05 +0000 Subject: [PATCH 11/49] docs(contributing): the review's commands as the runner now takes them CONTRIBUTING.md points at the agent review and the template's record of it; the checklist lists the changed files over the range reviewed; review.md runs the runner on the clean checked-out commit, names --host and the probe's --out, says what the probe proves, and says that the page's token totals do not count the reviewers yet. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 5 +++ docs/contributing/review-checklist.md | 8 ++--- docs/contributing/review.md | 48 ++++++++++++++++----------- 3 files changed, 38 insertions(+), 23 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fee42e31..ef736f6b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -121,6 +121,11 @@ On `main`, which carries only published states, CI also runs `loft verify`. Every commit stays green. Open pull requests against `develop`; `main` carries released, published states only. +Before a person is asked to review it, a change passes the agent review that +[`docs/contributing/review.md`](docs/contributing/review.md) describes, two read-only reviewers +run by `scripts/agent-review/review.py`, and the pull request template records the round. Where a +reviewer cannot run for you, say so in the template instead of leaving its row empty. + ## Releases Releases are cut by the maintainer: a tag `vX.Y.Z` on `main` runs the release workflow, which diff --git a/docs/contributing/review-checklist.md b/docs/contributing/review-checklist.md index 6c914146..f8dbb3ae 100644 --- a/docs/contributing/review-checklist.md +++ b/docs/contributing/review-checklist.md @@ -12,10 +12,10 @@ made is a finding, not something to go and run. - What is reviewed: a pull request, a branch, a commit range or a local diff, and against which base (`develop` unless stated). -- Read the list of changed files first (`git diff --stat`), then the patch by area: `spec/`, - `loft.trace.yaml` and `changes/`; each crate under `crates/`; the Yard page and its tests; - `plugins/` and the skill sources; `schemas/` and `testdata/`; `scripts/`, `.github/` and - `docs/`. +- Read the list of changed files first (`git diff --stat ...`, over the range + reviewed), then the patch by area: `spec/`, `loft.trace.yaml` and `changes/`; each crate under + `crates/`; the Yard page and its tests; `plugins/` and the skill sources; `schemas/` and + `testdata/`; `scripts/`, `.github/` and `docs/`. - Read the guidance of each area touched: the section of `AGENTS.md` that owns it, and the skill references it names. diff --git a/docs/contributing/review.md b/docs/contributing/review.md index c7c3ee18..567d9c6f 100644 --- a/docs/contributing/review.md +++ b/docs/contributing/review.md @@ -47,11 +47,12 @@ If a reviewer cannot run, say so in the pull request instead of quietly dropping ## The reviewers -The constants at the top of `review.py` pin both models and the effort, the floor for both -reviewers and `/code-review`'s level; `--dry-run` prints them. A person may ask for more effort on -a run (`--effort`), never less. The models are this repository's choice, not whatever a command -line calls newest: a newer one takes over only once a person decides it does, by changing those -constants. Codex runs with `--ignore-user-config`, so no personal configuration reaches it. +The constants at the top of [`reviewers.py`](../../scripts/agent-review/reviewers.py) pin both +models and the effort, the floor for both reviewers and `/code-review`'s level; `--dry-run` prints +them. A person may ask for more effort on a run (`--effort`), never less. The models are this +repository's choice, not whatever a command line calls newest: a newer one takes over only once a +person decides it does, by changing those constants. Codex runs with `--ignore-user-config`, so +no personal configuration reaches it. The [prompt](../../scripts/agent-review/prompt.md) points both at the checklist and names the exact diff command. The author adds, in a file passed with `--context`, what they cannot infer: @@ -65,19 +66,22 @@ Never put a credential, a token or the contents of an `.env` file into a prompt. ## Running them -From the root of the worktree whose branch is reviewed, with the branch and its base present -locally (the reviewers can neither fetch nor check out): +From the worktree whose branch is reviewed, clean and at the commit to review, with its base +present locally (the reviewers read the worktree's files, and can neither fetch nor check out): ```sh scripts/agent-review/review.py --context --out \ - [--branch ] [--base develop] [--stage --session ] + [--base develop] [--stage ] [--host claude-code|codex] [--session ] ``` -Both reviewers run at once, and each review is saved under `--out` beside the raw output of its -run; the script exits 1 when either failed, naming the reason. `--only` runs one alone. +Both reviewers run at once, told the diff of the two commits, and each review is saved under +`--out`, with the raw output of its run, under names of its own invocation. A run counts as a +review only when its output shows the reviewer ran that diff with success; the script exits 1 +when either run failed, naming the reason. `--only` runs one alone; `--dry-run` prints the +commands and the prompt. -- The Claude reviewer runs under `--permission-mode dontAsk`, with the tools `CLAUDE_TOOLS` - names, no MCP server, project settings alone and +- The Claude reviewer runs under `--permission-mode dontAsk`, with the tools `CLAUDE_TOOLS` names + in `reviewers.py`, no MCP server, project settings alone and [`reviewer-settings.json`](../../scripts/agent-review/reviewer-settings.json), whose deny list removes the edit and web tools even where the tool list names them. `dontAsk` refuses every command the allow list does not hold, so the prompt names the diff command exactly: a @@ -87,16 +91,22 @@ run; the script exits 1 when either failed, naming the reason. `--only` runs one - The Codex reviewer runs in Codex's `read-only` sandbox, with apps, the browser and computer use turned off. Do not use `codex review`: it takes neither a sandbox nor a prompt with a base. -**Check the setup** with `--probe` once on each machine, and after each upgrade of Claude Code or -Codex: it fails when the Claude reviewer can call more than it should or lacks `/code-review`, or -when the Codex reviewer could write in the tree. +**Check the setup** once on each machine, and after each upgrade of Claude Code or Codex, with +`scripts/agent-review/review.py --probe --out `. It fails unless +`dontAsk` refuses a write the Claude reviewer tries, that session can call no more than it should +and has `/code-review`, Codex's read-only sandbox refuses a write and allows a read, and the +Codex reviewer answers. ## Recording a round -**In Yard Log.** With `--stage`, the script records each run as a task of that stage (in Claude -Code `--session` defaults to the author's own). The author keeps the round's findings in the -stage's note of issues, whose table gives how each was found (`Src`), its verdict and evidence, -and its fix: +**In Yard Log.** With `--stage`, the script records each run as a task of that stage, written as +the author's session, which `--host` and `--session` name and which default to the host the +script runs under and its session; it exits 1 when Yard Log refuses a task. Each task's detail +gives its run's tokens. The page's token totals do not count them yet: they hold the sessions the +Loft plugin's hooks see, and the reviewers run without the plugin. + +The author keeps the round's findings in the stage's note of issues, whose table gives how each +was found (`Src`), its verdict and evidence, and its fix: | # | Src | Finding | Verdict | Evidence | Fix | | --- | --- | --- | --- | --- | --- | From 1bab8e10772db5b4025153c8a4599c978b370796 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:39:22 +0000 Subject: [PATCH 12/49] test(agent-review): the runner's tests on fixture output, in the gates and CI The runner's tests run on fixture output alone and reach no reviewer: a run counts only when it read the round's diff, output it cannot read fails the run without raising, a Codex stream error followed by a completed turn is no failure, each invocation has its own files and task with no path of the machine in it, a refused Yard write is reported, git that cannot compare is no change, the host comes from the environment, and each probe passes only on a refusal it saw. They run on the system's Python 3.9 as on newer ones, and join the gates and CI. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + AGENTS.md | 1 + CONTRIBUTING.md | 1 + scripts/agent-review/test_review.py | 183 ++++++++++++++++++++++++++++ 4 files changed, 187 insertions(+) create mode 100644 scripts/agent-review/test_review.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1b185bd..bdd3d13f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: - run: cargo fmt --all -- --check - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo nextest run --workspace + # The agent review's runner, on fixture output: no reviewer is reached. + - run: python3 -m unittest discover -s scripts/agent-review # The repository's own specification stays canonical and free of errors and warnings. # These runs of `loft` send nothing: `.cargo/config.toml` starts every process Cargo runs # with telemetry off. A runner is new on every run, so its events would count runs as diff --git a/AGENTS.md b/AGENTS.md index 9e61fe00..77536c23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -368,6 +368,7 @@ The thinking behind the Software Plant is at . cargo run -q -p loft-cli -- fmt --check cargo run -q -p loft-cli -- check --fail-on warning cargo run -q -p loft-cli -- reconcile --fail-on warning + python3 -m unittest discover -s scripts/agent-review ``` Install the runner with `cargo install cargo-nextest --locked`, and the architecture check with diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef736f6b..8ca21af1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -112,6 +112,7 @@ cargo nextest run --workspace cargo run -q -p loft-cli -- fmt --check cargo run -q -p loft-cli -- check --fail-on warning cargo run -q -p loft-cli -- reconcile --fail-on warning +python3 -m unittest discover -s scripts/agent-review ``` Building needs Rust 1.97 or newer, `cargo install cargo-nextest --locked` provides the test diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py new file mode 100644 index 00000000..a88bcafb --- /dev/null +++ b/scripts/agent-review/test_review.py @@ -0,0 +1,183 @@ +"""Tests of the review runner on fixture output: no reviewer, model or network is reached. + +Run from the repository root with `python3 -m unittest discover -s scripts/agent-review`. +""" + +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import probe +import review +from reviewers import ClaudeRun, CodexRun, Target, json_lines + +BASE, HEAD = "a" * 40, "b" * 40 +TARGET = Target("develop", BASE, HEAD, "feature") +DIFF = f"git diff {BASE}...{HEAD}" + + +def lines(*events: dict) -> str: + return "\n".join(json.dumps(event) for event in events) + + +def claude_stream(command: str, failed: bool = False, **result) -> str: + """A Claude stream in which the reviewer ran one Bash command and then answered.""" + return lines( + {"type": "system", "subtype": "init"}, + {"type": "assistant", "message": {"content": [ + {"type": "tool_use", "id": "t1", "name": "Bash", "input": {"command": command}}]}}, + {"type": "user", "message": {"content": [ + {"type": "tool_result", "tool_use_id": "t1", "is_error": failed}]}}, + {"type": "result", "subtype": "success", "is_error": False, "result": "No findings.", + "modelUsage": {"claude-opus-5-5": {"inputTokens": 3, "outputTokens": 5}}, **result}, + ) + + +def codex_stream(*items: dict, completed: bool = True, errors: int = 0) -> str: + events = [{"type": "thread.started", "thread_id": "th1"}] + events += [{"type": "error", "message": "Reconnecting... 1/5"}] * errors + events += [{"type": "item.completed", "item": item} for item in items] + if completed: + events.append({"type": "turn.completed", "usage": {"input_tokens": 7}}) + return lines(*events) + + +def command(text: str, exit_code: int) -> dict: + shell = f"/bin/zsh -lc '{text}'" + return {"type": "command_execution", "command": shell, "exit_code": exit_code} + + +class Fixture(unittest.TestCase): + def setUp(self) -> None: + self.dir = tempfile.TemporaryDirectory() + self.out = Path(self.dir.name) + + def tearDown(self) -> None: + self.dir.cleanup() + + +class ClaudeRunTests(Fixture): + def test_a_run_that_read_the_diff_is_a_review(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + run.read(claude_stream(DIFF)) + run.judge(0, "") + self.assertEqual(run.error, "") + self.assertEqual(run.review_path.read_text(), "No findings.") + self.assertIn("input 3", run.tokens) + + def test_a_run_whose_diff_was_refused_is_no_review(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + run.read(claude_stream(DIFF, failed=True)) + run.judge(0, "") + self.assertIn("never read the diff", run.error) + + def test_a_run_that_read_another_range_is_no_review(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + run.read(claude_stream("git diff develop...feature")) + run.judge(0, "") + self.assertIn("never read the diff", run.error) + + def test_output_that_is_no_stream_fails_the_run_without_raising(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + run.read("[]") + self.assertEqual(run.error, "Claude printed no result") + + def test_a_failure_after_the_reviewer_ran_is_the_runs_error(self) -> None: + run = ClaudeRun(TARGET, self.out / "missing", "high") + with mock.patch.object(run, "command", return_value=[sys.executable, "-c", "print(1)"]): + run.execute("prompt") + self.assertIn("FileNotFoundError", run.error) + + +class CodexRunTests(Fixture): + def reviewed(self, stdout: str) -> CodexRun: + run = CodexRun(TARGET, self.out, "high") + run.review_path.write_text("No findings.") + run.read(stdout) + run.judge(0, "") + return run + + def test_a_run_that_read_the_diff_is_a_review(self) -> None: + self.assertEqual(self.reviewed(codex_stream(command(DIFF, 0))).error, "") + + def test_a_stream_error_before_a_completed_turn_is_no_failure(self) -> None: + self.assertEqual(self.reviewed(codex_stream(command(DIFF, 0), errors=1)).error, "") + + def test_a_run_whose_turn_never_completed_fails(self) -> None: + run = self.reviewed(codex_stream(command(DIFF, 0), completed=False, errors=1)) + self.assertEqual(run.error, "Reconnecting... 1/5") + + def test_a_run_whose_diff_failed_is_no_review(self) -> None: + self.assertIn("never read the diff", self.reviewed(codex_stream(command(DIFF, 1))).error) + + +class RecordTests(Fixture): + def test_each_invocation_has_files_and_a_task_of_its_own(self) -> None: + first, second = CodexRun(TARGET, self.out, "high"), CodexRun(TARGET, self.out, "high") + self.assertNotEqual(first.review_path, second.review_path) + self.assertNotEqual(first.task("s", "active")["id"], second.task("s", "active")["id"]) + + def test_a_task_names_no_path_of_the_machine(self) -> None: + run = CodexRun(TARGET, self.out, "high") + self.assertNotIn(str(self.out), run.task("s", "done")["detail"]) + + def test_a_yard_write_that_loft_refuses_is_reported(self) -> None: + loft = self.out / "loft" + loft.write_text("#!/bin/sh\nexit 1\n") + loft.chmod(0o755) + yard = review.Yard("stage", "session", "claude-code") + with mock.patch.dict(os.environ, {"PATH": str(self.out)}), mock.patch("sys.stderr"): + self.assertFalse(yard.record([CodexRun(TARGET, self.out, "high")], "active")) + + def test_no_stage_records_nothing_and_succeeds(self) -> None: + self.assertTrue(review.Yard(None, None, None).record([], "active")) + + +class ArgumentTests(unittest.TestCase): + def test_git_that_cannot_compare_the_commits_is_no_change(self) -> None: + self.assertTrue(review.changed(1)) + self.assertFalse(review.changed(0)) + with self.assertRaises(ValueError): + review.changed(128) + + def test_the_host_and_session_come_from_the_host_that_runs_the_script(self) -> None: + with mock.patch.dict(os.environ, {"CODEX_THREAD_ID": "th"}, clear=True): + self.assertEqual(review.host_and_session(None, None), ("codex", "th")) + with mock.patch.dict(os.environ, {}, clear=True): + self.assertEqual(review.host_and_session(None, None), (None, None)) + + +class ProbeTests(unittest.TestCase): + def claude(self, denied: str, tools: tuple = ("Task", "Bash", "Read", "Skill")) -> bool: + events = json_lines(lines( + {"type": "system", "subtype": "init", "tools": list(tools), "mcp_servers": [], + "skills": ["code-review"]}, + {"type": "result", "is_error": False, + "permission_denials": [{"tool_input": {"command": denied}}] if denied else []}, + )) + return probe.claude_verdict(events, "p1", wrote=False)[0] + + def test_claude_passes_when_dont_ask_refused_its_write(self) -> None: + self.assertFalse(self.claude("touch p1")) + + def test_claude_fails_when_it_never_tried_the_write(self) -> None: + self.assertTrue(self.claude("")) + + def test_claude_fails_when_it_can_call_another_tool(self) -> None: + self.assertTrue(self.claude("touch p1", tools=("Task", "Bash", "Read", "Skill", "Edit"))) + + def test_codex_passes_only_when_the_sandbox_refused_the_write(self) -> None: + self.assertFalse(probe.codex_verdict(False, 1, 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, 0, 0, "")[0]) + self.assertTrue(probe.codex_verdict(True, 1, 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, 1, 0, "not signed in")[0]) + + +if __name__ == "__main__": + unittest.main() From 2f517cec71edbead06b651b9e68a8649fd9ccfbb Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:53:37 +0000 Subject: [PATCH 13/49] scripts: review exactly the pinned diff, recheck the tree, and probe for the exact refusal A run reads the round's diff only when it ran exactly `git diff ...`, unwrapped from Codex's shell: statistics, a path filter or a pipe no longer count, and /code-review is pointed at the commit range rather than the branch name. The tree, read with its untracked files whatever git's configuration hides, is checked again as each run ends, and a run during which it moved fails; when the branch itself changed, its task is not finalized into another branch's Yard Log. The records say no more than happened: a failed run's text is kept as -failed.md, Claude's task is assigned to its reviewer's session again, a reason names no directory of the machine, both hosts' variables set is a host to name rather than guess, any git exit but 0 or 1 is a failure to compare, and an empty --stage, or one beside --probe or --dry-run, is refused. Each run's files are reserved by exclusive creation, so no run overwrites another's. The probe requires the exact refusal: the denied Bash call that is its touch, and the sandbox's own words for a refused write, under an empty Codex home as the review ignores the user's configuration. Each probe writes only in a directory it created. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/probe.py | 71 +++++++++------- scripts/agent-review/review.py | 66 ++++++++++++--- scripts/agent-review/reviewers.py | 67 +++++++++++++-- scripts/agent-review/test_review.py | 126 ++++++++++++++++++++++++---- 4 files changed, 263 insertions(+), 67 deletions(-) diff --git a/scripts/agent-review/probe.py b/scripts/agent-review/probe.py index 717a1cef..8bb11b18 100644 --- a/scripts/agent-review/probe.py +++ b/scripts/agent-review/probe.py @@ -1,22 +1,27 @@ """The setup check of review.py --probe. The Claude reviewer is asked to write a file in the tree, and passes only when `dontAsk` refused -the attempt and its session could call no more than it should. Codex's sandbox is tried without -a model, since `codex exec --json` shows no event for a command the sandbox refused: under the -read-only policy a write must fail and a read succeed; and the Codex reviewer must answer a turn. +exactly that command and its session could call no more than it should. Codex's sandbox is tried +without a model, since `codex exec --json` shows no event for a command the sandbox refused: +under the read-only policy, and no personal configuration, a write must be refused by the +sandbox itself and a read succeed; and the Codex reviewer must answer a turn. Each probe writes +only inside a directory it created for itself, so it can remove nothing it did not make. """ from __future__ import annotations -import secrets +import os +import shutil import subprocess +import tempfile +from pathlib import Path -from reviewers import ( - CLAUDE_TOOLS, NO_DIFF, ROOT, ClaudeRun, CodexRun, Run, json_lines, -) +from reviewers import CLAUDE_TOOLS, NO_DIFF, ROOT, ClaudeRun, CodexRun, Run, json_lines # The start event names the Agent tool by its older name, Task. CLAUDE_TOOL_NAMES = {*CLAUDE_TOOLS, "Task"} +# What a sandbox says when it refuses a write: macOS's Seatbelt, then Linux's. +REFUSALS = ("Operation not permitted", "Permission denied", "Read-only file system") def write_request(path: str) -> str: @@ -34,11 +39,11 @@ def claude_verdict(events: list[dict], path: str, wrote: bool) -> tuple[bool, st return True, "Claude did not start or answer" tools, servers = start.get("tools") or [], start.get("mcp_servers") or [] skills = start.get("skills") or start.get("slash_commands") or [] - denied = [ - (d.get("tool_input") or {}).get("command", "") - for d in result.get("permission_denials") or [] - ] - refused = any(path in command for command in denied) + refused = any( + denial.get("tool_name") == "Bash" + and (denial.get("tool_input") or {}).get("command", "").strip() == f"touch {path}" + for denial in result.get("permission_denials") or [] + ) extra = set(tools) - CLAUDE_TOOL_NAMES bad = wrote or not refused or not tools or bool(extra) or bool(servers) bad = bad or "code-review" not in skills @@ -49,28 +54,32 @@ def claude_verdict(events: list[dict], path: str, wrote: bool) -> tuple[bool, st ) -def sandboxed(command: list[str]) -> int: - """The exit code of a command run under Codex's read-only sandbox policy.""" - done = subprocess.run( - ["codex", "sandbox", "-c", 'sandbox_mode="read-only"', "--", *command], - cwd=ROOT, capture_output=True, text=True, - ) - return done.returncode +def sandboxed(command: list[str]) -> subprocess.CompletedProcess: + """A command run under Codex's read-only sandbox policy, with no personal configuration: an + empty Codex home, as the review runs with --ignore-user-config.""" + with tempfile.TemporaryDirectory() as home: + return subprocess.run( + ["codex", "sandbox", "-c", 'sandbox_mode="read-only"', "--", *command], + cwd=ROOT, capture_output=True, text=True, env={**os.environ, "CODEX_HOME": home}, + ) -def codex_verdict(wrote: bool, write_code: int, read_code: int, error: str) -> tuple[bool, str]: - """Whether Codex failed the probe, and what it showed.""" - shown = "made" if wrote else "refused by the sandbox" if write_code != 0 else "not refused" +def codex_verdict(wrote: bool, write: subprocess.CompletedProcess, read_code: int, + error: str) -> tuple[bool, str]: + """Whether Codex failed the probe, and what it showed: a write fails the probe unless the + sandbox itself refused it, not a command that could not start.""" + refused = write.returncode != 0 and any(words in write.stderr for words in REFUSALS) + shown = "made" if wrote else "refused by the sandbox" if refused else "not refused" read = "allowed" if read_code == 0 else "refused" message = f"Codex write in the tree: {shown}; read: {read}" if error: message += f"; the reviewer did not answer: {error}" - return wrote or write_code == 0 or read_code != 0 or bool(error), message + return wrote or not refused or read_code != 0 or bool(error), message def probe_claude(run: ClaudeRun, path: str) -> tuple[bool, str]: # At low effort, since a model that reasons long may decline a write it expects refused. - check = ClaudeRun(run.target, run.review_path.parent, "low") + check = ClaudeRun(run.target, run.out, "low") command = check.command(write_request(path), rule=False) + ["--no-session-persistence"] try: done = subprocess.run( @@ -83,23 +92,23 @@ def probe_claude(run: ClaudeRun, path: str) -> tuple[bool, str]: def probe_codex(run: CodexRun, path: str) -> tuple[bool, str]: try: - write_code = sandboxed(["touch", path]) - read_code = sandboxed(["cat", "AGENTS.md"]) + write = sandboxed(["touch", path]) + read_code = sandboxed(["cat", "AGENTS.md"]).returncode except OSError as error: return True, f"Codex could not start: {error}" run.execute("Say ok.") # The run is no review, so only its own failure counts, not the lack of a diff. error = "" if run.error.startswith(NO_DIFF) else run.error - return codex_verdict((ROOT / path).exists(), write_code, read_code, error) + return codex_verdict((ROOT / path).exists(), write, read_code, error) def probe(run: Run) -> tuple[bool, str]: - """Probe one reviewer on a path of its own that nothing in the tree holds.""" - path = f"agent-review-probe-{secrets.token_hex(4)}" + """Probe one reviewer on a path inside a directory created for this probe alone.""" + own = Path(tempfile.mkdtemp(prefix=".agent-review-probe-", dir=ROOT)) + path = str((own / "written").relative_to(ROOT)) try: if isinstance(run, ClaudeRun): return probe_claude(run, path) return probe_codex(run, path) finally: - # The path is new to this probe, so whatever lies there now the reviewer wrote. - (ROOT / path).unlink(missing_ok=True) + shutil.rmtree(own, ignore_errors=True) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index da293085..126e7f9b 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -66,8 +66,9 @@ def usage_error(message: str) -> None: def changed(returncode: int) -> bool: - """What `git diff --quiet` says by its exit code; a code above 1 is a failure to compare.""" - if returncode > 1: + """What `git diff --quiet` says by its exit code: 1 a change, 0 none, and any other code, a + signal's included, a failure to compare.""" + if returncode not in (0, 1): raise ValueError(f"git could not compare the commits (exit {returncode})") return returncode == 1 @@ -75,7 +76,12 @@ def changed(returncode: int) -> bool: def host_and_session(host: str | None, session: str | None) -> tuple[str | None, str | None]: """The author's host and session: as given, else as the environment of the host names.""" if host is None: - host = next((h for h, variable in SESSIONS.items() if os.environ.get(variable)), None) + hosts = [h for h, variable in SESSIONS.items() if os.environ.get(variable)] + if len(hosts) > 1: + # One host started from the other inherits its variable, so neither tells. + raise ValueError(f"both {' and '.join(SESSIONS[h] for h in hosts)} are set: name the " + "author's host with --host") + host = hosts[0] if hosts else None if host is not None and session is None: session = os.environ.get(SESSIONS[host]) return host, session @@ -100,22 +106,52 @@ def arguments() -> argparse.Namespace: args.out = args.out.resolve() if args.out == ROOT or ROOT in args.out.parents: usage_error(f"--out must lie outside the tree, not in {ROOT}") - args.host, args.session = host_and_session(args.host, args.session) - if args.stage and not (args.host and args.session): + if args.stage is None: + return args + if not args.stage.strip(): + usage_error("--stage is empty: name the stage, or leave the option out to record nothing") + if args.probe or args.dry_run: + usage_error("--stage records a review; --probe and --dry-run record nothing") + try: + args.host, args.session = host_and_session(args.host, args.session) + except ValueError as error: + usage_error(str(error)) + if not (args.host and args.session): usage_error("--stage needs the author's --host and --session; neither could be inferred") - if args.stage and shutil.which("loft") is None: + if shutil.which("loft") is None: usage_error("--stage needs loft on PATH, to record the runs in Yard Log") return args +def tree() -> tuple[str, str, str]: + """The checked-out commit, its branch, and what the tree holds beyond it, untracked files + included whatever git's configuration hides.""" + return ( + git("rev-parse", "--verify", "HEAD^{commit}"), + git("rev-parse", "--abbrev-ref", "HEAD"), + git("status", "--porcelain", "--untracked-files=all"), + ) + + +def moved(target: Target) -> str: + """How the tree moved from the target since the run began, or nothing.""" + try: + head, branch, dirty = tree() + except subprocess.CalledProcessError as error: + return f"git could not read the tree: {error.stderr.strip()}" + if branch != target.branch: + return f"the branch {target.branch} is no longer checked out ({branch} is)" + if head != target.head: + return f"HEAD moved from {target.short} to {head[:12]}" + return "the tree holds uncommitted changes" if dirty else "" + + def target_of(base: str, to_review: bool) -> Target: """The checked-out commit against the base. To be reviewed, the tree must be clean, since the reviewers read its files, and the commit must differ from the base.""" try: - head = git("rev-parse", "--verify", "HEAD^{commit}") + head, branch, dirty = tree() base_commit = git("rev-parse", "--verify", f"{base}^{{commit}}") - branch = git("rev-parse", "--abbrev-ref", "HEAD") - dirty = git("status", "--porcelain") except subprocess.CalledProcessError as error: usage_error(f"git: {error.stderr.strip()}; fetch {base} first") target = Target(base, base_commit, head, branch) @@ -168,13 +204,23 @@ def main() -> int: print(f"\nCodex reads this prompt on standard input:\n\n{prompts['codex']}") return 0 args.out.mkdir(parents=True, exist_ok=True) + for run in runs: + run.reserve() yard = Yard(args.stage, args.session, args.host) if not yard.record(runs, "active"): return 1 def review(run: Run) -> bool: - # Each run records its own end as soon as it ends, whatever the other one does. + # Each run records its own end as soon as it ends, whatever the other one does, once the + # tree is checked again: the reviewer read its files all along. run.execute(prompts[run.name]) + how = moved(target) + if how: + run.fail(f"the tree moved during the run: {how}") + if how.startswith("the branch"): + # Yard Log is found by the branch checked out, so the task stays as it was written. + print(f"{run.label}: task {run.task('', 'open')['id']} stays active", file=sys.stderr) + return False return yard.record([run]) with ThreadPoolExecutor(len(runs)) as pool: diff --git a/scripts/agent-review/reviewers.py b/scripts/agent-review/reviewers.py index 5181eb8e..daa390e0 100644 --- a/scripts/agent-review/reviewers.py +++ b/scripts/agent-review/reviewers.py @@ -8,7 +8,9 @@ from __future__ import annotations import json +import re import secrets +import shlex import subprocess import uuid from pathlib import Path @@ -59,8 +61,26 @@ def __init__(self, base: str, base_commit: str, head: str, branch: str) -> None: self.diff = f"git diff {self.range}" def is_diff(self, command: str) -> bool: - """Whether a shell command a reviewer ran reads this round's diff.""" - return "git diff" in command and self.range in command + """Whether a shell command a reviewer ran is exactly this round's diff: no statistics, + no path filter and no pipe count, nor any other range.""" + return unwrapped(command).strip() == self.diff + + +def unwrapped(command: str) -> str: + """A command without the shell Codex runs it through (`/bin/zsh -lc '…'`).""" + try: + words = shlex.split(command) + except ValueError: + return command + if len(words) == 3 and words[0].endswith("sh") and words[1] in ("-c", "-lc"): + return words[2] + return command + + +def path_free(text: str) -> str: + """Text with each absolute path cut to its last part, so that no record names the machine's + directories.""" + return re.sub(r"(?:/[^/\s'\"]+)+/([^/\s'\"]+)", r"\1", text) class Run: @@ -69,15 +89,27 @@ class Run: name = label = model = ident_noun = raw_suffix = "" def __init__(self, target: Target, out: Path, effort: str) -> None: - self.target, self.effort = target, effort - # Each invocation has its own files and its own Yard task, so no run overwrites another. - self.key = f"{target.short}-{secrets.token_hex(3)}" - self.review_path = out / f"{self.key}-{self.name}.md" - self.raw_path = out / f"{self.key}-{self.name}.{self.raw_suffix}" + self.target, self.effort, self.out = target, effort, out + self.name_files(secrets.token_hex(3)) self.text = self.ident = self.tokens = self.error = "" self.read_the_diff = False self.events: list[dict] = [] + def name_files(self, suffix: str) -> None: + self.key = f"{self.target.short}-{suffix}" + self.review_path = self.out / f"{self.key}-{self.name}.md" + self.raw_path = self.out / f"{self.key}-{self.name}.{self.raw_suffix}" + + def reserve(self) -> None: + """Claim the run's files by creating its raw output exclusively, drawing another name + while one is taken, so that no run overwrites another's files or Yard task.""" + while True: + try: + self.raw_path.open("x").close() + return + except FileExistsError: + self.name_files(secrets.token_hex(3)) + def prompt(self, text: str) -> str: return text @@ -102,6 +134,19 @@ def execute(self, prompt: str) -> None: self.judge(done.returncode, done.stderr) except Exception as error: # A run's failure is its task's reason, not a traceback. self.error = self.error or f"{type(error).__name__}: {error}" + self.set_aside() + + def fail(self, reason: str) -> None: + """Fail a run after it ended, as when the tree moved under it.""" + self.error = self.error or reason + self.set_aside() + + def set_aside(self) -> None: + """Rename a failed run's review, so that what it left never passes for a review.""" + if self.error and self.review_path.exists(): + failed = self.review_path.with_name(f"{self.key}-{self.name}-failed.md") + self.review_path.rename(failed) + self.review_path = failed def judge(self, returncode: int, stderr: str) -> None: """Set the run's error from what it left, when what it left is not a review.""" @@ -122,7 +167,7 @@ def task(self, stage: str, state: str) -> dict: "active": f"{head}, reviewing {where}.", "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " f"tokens: {self.tokens}. Review: {self.review_path.name}", - "open": f"{head}, on {where} failed: {self.error}", + "open": f"{head}, on {where} failed: {path_free(self.error)}", }[state] return { "id": f"review-{self.name}-{self.key}", "kind": "task", "stage": stage, @@ -141,7 +186,7 @@ def __init__(self, *args, **kwargs) -> None: def prompt(self, text: str) -> str: target = self.target - return f"/code-review {self.effort} {target.branch} against {target.base}. {text}" + return f"/code-review {self.effort} the commits {target.range}. {text}" def command(self, prompt: str, rule: bool = True) -> list[str]: # The stream shows each command the reviewer ran, and so whether it read the diff. @@ -186,6 +231,10 @@ def total(key: str) -> int: ) self.review_path.write_text(self.text) + def task(self, stage: str, state: str) -> dict: + return {**super().task(stage, state), + "assignee": {"host": "claude-code", "session": self.ident}} + def succeeded_commands(events: list[dict]) -> list[str]: """The Bash commands of a Claude stream, its subagents' included, whose result was no error.""" diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index a88bcafb..ab017922 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -117,15 +117,46 @@ def test_a_run_whose_diff_failed_is_no_review(self) -> None: self.assertIn("never read the diff", self.reviewed(codex_stream(command(DIFF, 1))).error) +class DiffTests(unittest.TestCase): + def test_only_the_exact_diff_counts_as_reading_it(self) -> None: + self.assertTrue(TARGET.is_diff(DIFF)) + self.assertTrue(TARGET.is_diff(command(DIFF, 0)["command"])) + for form in (f"git diff --stat {BASE}...{HEAD}", f"git diff --name-only {BASE}...{HEAD}", + f"{DIFF} -- one/file", f"{DIFF} | head -20", "git diff develop...feature"): + with self.subTest(form=form): + self.assertFalse(TARGET.is_diff(form)) + self.assertFalse(TARGET.is_diff(command(form, 0)["command"])) + + class RecordTests(Fixture): - def test_each_invocation_has_files_and_a_task_of_its_own(self) -> None: - first, second = CodexRun(TARGET, self.out, "high"), CodexRun(TARGET, self.out, "high") - self.assertNotEqual(first.review_path, second.review_path) + def test_a_name_already_taken_is_drawn_again(self) -> None: + with mock.patch("secrets.token_hex", side_effect=["aaaaaa", "aaaaaa", "bbbbbb"]): + first, second = CodexRun(TARGET, self.out, "high"), CodexRun(TARGET, self.out, "high") + first.reserve() + second.reserve() + self.assertNotEqual(first.raw_path, second.raw_path) self.assertNotEqual(first.task("s", "active")["id"], second.task("s", "active")["id"]) def test_a_task_names_no_path_of_the_machine(self) -> None: - run = CodexRun(TARGET, self.out, "high") - self.assertNotIn(str(self.out), run.task("s", "done")["detail"]) + run = ClaudeRun(TARGET, self.out / "missing", "high") + with mock.patch.object(run, "command", return_value=[sys.executable, "-c", "print(1)"]): + run.execute("prompt") + self.assertNotIn(self.dir.name, run.task("s", "open")["detail"]) + done = CodexRun(TARGET, self.out, "high").task("s", "done")["detail"] + self.assertNotIn(self.dir.name, done) + + def test_a_failed_run_leaves_no_file_that_passes_for_a_review(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + run.read(claude_stream("git diff develop...feature")) + run.judge(0, "") + run.set_aside() + self.assertFalse((self.out / f"{run.key}-claude.md").exists()) + self.assertTrue(run.review_path.name.endswith("-claude-failed.md")) + + def test_a_claude_task_is_assigned_to_the_reviewers_session(self) -> None: + run = ClaudeRun(TARGET, self.out, "high") + assignee = run.task("s", "active")["assignee"] + self.assertEqual(assignee, {"host": "claude-code", "session": run.ident}) def test_a_yard_write_that_loft_refuses_is_reported(self) -> None: loft = self.out / "loft" @@ -139,12 +170,50 @@ def test_no_stage_records_nothing_and_succeeds(self) -> None: self.assertTrue(review.Yard(None, None, None).record([], "active")) +def stub_git(head: str = HEAD, branch: str = "feature", dirty: str = ""): + """A git that answers the runner's questions about the tree as given.""" + def git(*args: str) -> str: + if args[0] == "status": + return dirty + if args[:2] == ("rev-parse", "--abbrev-ref"): + return branch + return head if args[-1] == "HEAD^{commit}" else BASE + return git + + +class TargetTests(unittest.TestCase): + def target(self, quiet: int, **tree) -> review.Target: + done = mock.Mock(returncode=quiet) + with mock.patch("review.git", stub_git(**tree)), \ + mock.patch("review.subprocess.run", return_value=done), mock.patch("sys.stderr"): + return review.target_of("develop", to_review=True) + + def test_a_clean_tree_that_differs_from_its_base_is_reviewed(self) -> None: + self.assertEqual(self.target(1).range, f"{BASE}...{HEAD}") + + def test_a_tree_that_cannot_be_reviewed_is_refused(self) -> None: + for quiet, tree in ((1, {"dirty": "?? new.rs"}), (0, {}), (128, {}), (-9, {})): + with self.subTest(quiet=quiet, tree=tree), self.assertRaises(SystemExit) as stop: + self.target(quiet, **tree) + self.assertEqual(stop.exception.code, 2) + + def test_a_tree_that_moved_during_the_run_says_how(self) -> None: + for tree, words in (({"branch": "other"}, "no longer checked out"), + ({"head": "c" * 40}, "HEAD moved"), + ({"dirty": " M a.rs"}, "uncommitted")): + with self.subTest(tree=tree), mock.patch("review.git", stub_git(**tree)): + self.assertIn(words, review.moved(TARGET)) + with mock.patch("review.git", stub_git()): + self.assertEqual(review.moved(TARGET), "") + + class ArgumentTests(unittest.TestCase): - def test_git_that_cannot_compare_the_commits_is_no_change(self) -> None: + def test_git_that_cannot_compare_the_commits_is_an_error(self) -> None: self.assertTrue(review.changed(1)) self.assertFalse(review.changed(0)) - with self.assertRaises(ValueError): - review.changed(128) + for code in (128, -9): + with self.subTest(code=code), self.assertRaises(ValueError): + review.changed(code) def test_the_host_and_session_come_from_the_host_that_runs_the_script(self) -> None: with mock.patch.dict(os.environ, {"CODEX_THREAD_ID": "th"}, clear=True): @@ -152,31 +221,54 @@ def test_the_host_and_session_come_from_the_host_that_runs_the_script(self) -> N with mock.patch.dict(os.environ, {}, clear=True): self.assertEqual(review.host_and_session(None, None), (None, None)) + def test_a_host_started_from_the_other_must_be_named(self) -> None: + both = {"CODEX_THREAD_ID": "th", "CLAUDE_CODE_SESSION_ID": "s"} + with mock.patch.dict(os.environ, both, clear=True): + with self.assertRaises(ValueError): + review.host_and_session(None, None) + self.assertEqual(review.host_and_session("codex", None), ("codex", "th")) + + def test_a_stage_that_would_record_nothing_is_refused(self) -> None: + for extra in (["--stage", ""], ["--stage", "s", "--probe"], ["--stage", "s", "--dry-run"]): + argv = ["review.py", "--out", tempfile.gettempdir(), *extra] + with self.subTest(extra=extra), mock.patch.object(sys, "argv", argv), \ + mock.patch("sys.stderr"), self.assertRaises(SystemExit) as stop: + review.arguments() + self.assertEqual(stop.exception.code, 2) + class ProbeTests(unittest.TestCase): - def claude(self, denied: str, tools: tuple = ("Task", "Bash", "Read", "Skill")) -> bool: + def claude(self, denied: str, tool: str = "Bash", + tools: tuple = ("Task", "Bash", "Read", "Skill")) -> bool: + denials = [{"tool_name": tool, "tool_input": {"command": denied}}] if denied else [] events = json_lines(lines( {"type": "system", "subtype": "init", "tools": list(tools), "mcp_servers": [], "skills": ["code-review"]}, - {"type": "result", "is_error": False, - "permission_denials": [{"tool_input": {"command": denied}}] if denied else []}, + {"type": "result", "is_error": False, "permission_denials": denials}, )) return probe.claude_verdict(events, "p1", wrote=False)[0] def test_claude_passes_when_dont_ask_refused_its_write(self) -> None: self.assertFalse(self.claude("touch p1")) - def test_claude_fails_when_it_never_tried_the_write(self) -> None: + def test_claude_fails_unless_the_refusal_was_its_write(self) -> None: self.assertTrue(self.claude("")) + self.assertTrue(self.claude("cat p1")) + self.assertTrue(self.claude("touch p1", tool="Read")) def test_claude_fails_when_it_can_call_another_tool(self) -> None: self.assertTrue(self.claude("touch p1", tools=("Task", "Bash", "Read", "Skill", "Edit"))) - def test_codex_passes_only_when_the_sandbox_refused_the_write(self) -> None: - self.assertFalse(probe.codex_verdict(False, 1, 0, "")[0]) - self.assertTrue(probe.codex_verdict(False, 0, 0, "")[0]) - self.assertTrue(probe.codex_verdict(True, 1, 0, "")[0]) - self.assertTrue(probe.codex_verdict(False, 1, 0, "not signed in")[0]) + def test_codex_passes_only_when_the_sandbox_itself_refused_the_write(self) -> None: + def write(code: int, stderr: str = "") -> mock.Mock: + return mock.Mock(returncode=code, stderr=stderr) + refused = write(1, "touch: p1: Operation not permitted") + self.assertFalse(probe.codex_verdict(False, refused, 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, write(0), 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, write(71, "execvp() failed"), 0, "")[0]) + self.assertTrue(probe.codex_verdict(True, refused, 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, refused, 1, "")[0]) + self.assertTrue(probe.codex_verdict(False, refused, 0, "not signed in")[0]) if __name__ == "__main__": From 52f7a25f1f3603891d9781a45b6207b8114949c1 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 12:53:37 +0000 Subject: [PATCH 14/49] ci(release): run the review runner's suite in the release gate too, and document the recheck Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 1 + docs/contributing/review.md | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fda1c116..5ca3825c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,6 +43,7 @@ jobs: - run: scripts/deslop.sh install - run: scripts/deslop.sh - run: cargo nextest run --workspace + - run: python3 -m unittest discover -s scripts/agent-review - run: cargo run -q -p loft-cli -- fmt --check - run: cargo run -q -p loft-cli -- check --fail-on warning - run: cargo run -q -p loft-cli -- reconcile --fail-on warning diff --git a/docs/contributing/review.md b/docs/contributing/review.md index 567d9c6f..1880d59b 100644 --- a/docs/contributing/review.md +++ b/docs/contributing/review.md @@ -76,8 +76,10 @@ scripts/agent-review/review.py --context --out Date: Thu, 3 Dec 2026 13:01:36 +0000 Subject: [PATCH 15/49] scripts: refuse a --stage the author does not own before any review runs A task assigned to a reviewer's session is written by its stage's owner alone, so a stage that is missing or someone else's is now a usage error before either reviewer starts. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 29 +++++++++++++++++++++++++++++ scripts/agent-review/test_review.py | 7 +++++++ 2 files changed, 36 insertions(+) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 126e7f9b..8754a503 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -33,12 +33,38 @@ SESSIONS = {"claude-code": "CLAUDE_CODE_SESSION_ID", "codex": "CODEX_THREAD_ID"} +def stage_refusal(read: dict, stage: str, host: str, session: str) -> str: + """Why the author cannot record the runs in a stage of the Yard Log `read` holds: the stage + must exist and be the author's own, since a task assigned to a reviewer is written by its + stage's owner alone. Nothing when it can.""" + found = next((s for s in read.get("stages") or [] if s.get("id") == stage), None) + if found is None: + return f"the branch's Yard Log holds no stage {stage}" + owner = found.get("owner") or {} + if (owner.get("host"), owner.get("session")) != (host, session): + return f"the stage {stage} is not the author's own: name a stage the author owns" + return "" + + class Yard: """Writes each run's task into the branch's Yard Log, or nothing without --stage.""" def __init__(self, stage: str | None, session: str | None, host: str | None) -> None: self.stage, self.session, self.host = stage, session, host + def refusal(self) -> str: + """Why the runs cannot be recorded in the stage, before any run starts; nothing when + they can, or when none is asked for.""" + if not self.stage: + return "" + done = subprocess.run( + ["loft", "yard", "read", "--tree", str(ROOT), "--format", "json"], + capture_output=True, text=True, + ) + if done.returncode != 0: + return f"loft could not read the branch's Yard Log: {done.stderr.strip()[-400:]}" + return stage_refusal(json.loads(done.stdout), self.stage, str(self.host), str(self.session)) + def record(self, runs: list[Run], state: str | None = None) -> bool: """Write the runs' tasks; whether Yard Log took them, or nothing was asked.""" if not self.stage: @@ -207,6 +233,9 @@ def main() -> int: for run in runs: run.reserve() yard = Yard(args.stage, args.session, args.host) + refusal = yard.refusal() + if refusal: + usage_error(refusal) if not yard.record(runs, "active"): return 1 diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index ab017922..c1114257 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -166,6 +166,13 @@ def test_a_yard_write_that_loft_refuses_is_reported(self) -> None: with mock.patch.dict(os.environ, {"PATH": str(self.out)}), mock.patch("sys.stderr"): self.assertFalse(yard.record([CodexRun(TARGET, self.out, "high")], "active")) + def test_only_a_stage_the_author_owns_records_the_runs(self) -> None: + mine = {"host": "claude-code", "session": "me"} + read = {"stages": [{"id": "review", "owner": mine}]} + self.assertEqual(review.stage_refusal(read, "review", "claude-code", "me"), "") + self.assertIn("not the author's own", review.stage_refusal(read, "review", "codex", "me")) + self.assertIn("no stage", review.stage_refusal(read, "other", "claude-code", "me")) + def test_no_stage_records_nothing_and_succeeds(self) -> None: self.assertTrue(review.Yard(None, None, None).record([], "active")) From c220e1e0eacabe94d13111453b7d7aedf3d5566d Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:02:03 +0000 Subject: [PATCH 16/49] scripts: name how the tree moved by kind, and write nothing when git cannot read it moved() gives a kind beside its words, so finish() decides by kind rather than by the start of a message: a run that ended on another branch, or on a tree git could not read, writes nothing to Yard Log. finish() is tested for each case. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 45 +++++++++++++++++++---------- scripts/agent-review/test_review.py | 39 +++++++++++++++++++++---- 2 files changed, 63 insertions(+), 21 deletions(-) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 8754a503..68cdb4aa 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -159,17 +159,38 @@ def tree() -> tuple[str, str, str]: ) -def moved(target: Target) -> str: - """How the tree moved from the target since the run began, or nothing.""" +# How the tree can have moved from a target, by whether Yard Log may still take the run's end: +# it is found through the branch checked out, so only a tree on the same branch may. +SAME_BRANCH, ELSEWHERE = ("head", "dirty"), ("branch", "unreadable") + + +def moved(target: Target) -> tuple[str, str]: + """How the tree moved from the target since the run began, as a kind and in words, or two + empty strings.""" try: head, branch, dirty = tree() except subprocess.CalledProcessError as error: - return f"git could not read the tree: {error.stderr.strip()}" + return "unreadable", f"git could not read the tree: {error.stderr.strip()}" if branch != target.branch: - return f"the branch {target.branch} is no longer checked out ({branch} is)" + return "branch", f"the branch {target.branch} is no longer checked out ({branch} is)" if head != target.head: - return f"HEAD moved from {target.short} to {head[:12]}" - return "the tree holds uncommitted changes" if dirty else "" + return "head", f"HEAD moved from {target.short} to {head[:12]}" + if dirty: + return "dirty", "the tree holds uncommitted changes" + return "", "" + + +def finish(run: Run, target: Target, yard: Yard) -> bool: + """Check the tree again once a run ended, since the reviewer read its files all along, and + record the run's end; whether Yard Log took it. A run during which the tree moved fails, and + one that ended on another branch, or a tree git could not read, writes nothing.""" + kind, how = moved(target) + if kind: + run.fail(f"the tree moved during the run: {how}") + if kind in ELSEWHERE: + print(f"{run.label}: task {run.task('', 'open')['id']} stays active", file=sys.stderr) + return False + return yard.record([run]) def target_of(base: str, to_review: bool) -> Target: @@ -240,17 +261,9 @@ def main() -> int: return 1 def review(run: Run) -> bool: - # Each run records its own end as soon as it ends, whatever the other one does, once the - # tree is checked again: the reviewer read its files all along. + # Each run records its own end as soon as it ends, whatever the other one does. run.execute(prompts[run.name]) - how = moved(target) - if how: - run.fail(f"the tree moved during the run: {how}") - if how.startswith("the branch"): - # Yard Log is found by the branch checked out, so the task stays as it was written. - print(f"{run.label}: task {run.task('', 'open')['id']} stays active", file=sys.stderr) - return False - return yard.record([run]) + return finish(run, target, yard) with ThreadPoolExecutor(len(runs)) as pool: recorded = list(pool.map(review, runs)) diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index c1114257..c6daef7e 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -7,6 +7,7 @@ import json import os +import subprocess import sys import tempfile import unittest @@ -205,13 +206,41 @@ def test_a_tree_that_cannot_be_reviewed_is_refused(self) -> None: self.assertEqual(stop.exception.code, 2) def test_a_tree_that_moved_during_the_run_says_how(self) -> None: - for tree, words in (({"branch": "other"}, "no longer checked out"), - ({"head": "c" * 40}, "HEAD moved"), - ({"dirty": " M a.rs"}, "uncommitted")): + for tree, kind in (({"branch": "other"}, "branch"), ({"head": "c" * 40}, "head"), + ({"dirty": " M a.rs"}, "dirty")): with self.subTest(tree=tree), mock.patch("review.git", stub_git(**tree)): - self.assertIn(words, review.moved(TARGET)) + self.assertEqual(review.moved(TARGET)[0], kind) with mock.patch("review.git", stub_git()): - self.assertEqual(review.moved(TARGET), "") + self.assertEqual(review.moved(TARGET), ("", "")) + + +class FinishTests(Fixture): + def finish(self, git) -> tuple[bool, CodexRun, mock.Mock]: + run, yard = CodexRun(TARGET, self.out, "high"), mock.Mock() + yard.record.return_value = True + with mock.patch("review.git", git), mock.patch("sys.stderr"): + return review.finish(run, TARGET, yard), run, yard + + def test_a_run_on_an_unmoved_tree_records_its_end(self) -> None: + recorded, run, yard = self.finish(stub_git()) + self.assertTrue(recorded) + self.assertEqual(run.error, "") + yard.record.assert_called_once_with([run]) + + def test_a_run_during_which_head_moved_fails_and_records_its_end(self) -> None: + recorded, run, yard = self.finish(stub_git(head="c" * 40)) + self.assertIn("the tree moved during the run", run.error) + yard.record.assert_called_once_with([run]) + + def test_a_run_that_ended_elsewhere_writes_nothing(self) -> None: + def unreadable(*args: str) -> str: + raise subprocess.CalledProcessError(128, "git", stderr="not a repository") + for git in (stub_git(branch="other"), unreadable): + with self.subTest(git=git): + recorded, run, yard = self.finish(git) + self.assertFalse(recorded) + self.assertIn("the tree moved during the run", run.error) + yard.record.assert_not_called() class ArgumentTests(unittest.TestCase): From 290d52afdf5ff430ec980b8fc2cf176e81cda711 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:02:23 +0000 Subject: [PATCH 17/49] scripts: run the probe's Codex turn in a directory of its own The probe's turn is no review, so it no longer writes under names of --out, where it left a -failed.md beside the reviews and could overwrite one. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/probe.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/agent-review/probe.py b/scripts/agent-review/probe.py index 8bb11b18..3018586f 100644 --- a/scripts/agent-review/probe.py +++ b/scripts/agent-review/probe.py @@ -96,9 +96,12 @@ def probe_codex(run: CodexRun, path: str) -> tuple[bool, str]: read_code = sandboxed(["cat", "AGENTS.md"]).returncode except OSError as error: return True, f"Codex could not start: {error}" - run.execute("Say ok.") - # The run is no review, so only its own failure counts, not the lack of a diff. - error = "" if run.error.startswith(NO_DIFF) else run.error + # The run is no review, so it writes into a directory of its own, never beside the reviews in + # --out, and only its own failure counts, not the lack of a diff. + with tempfile.TemporaryDirectory() as out: + answer = CodexRun(run.target, Path(out), run.effort) + answer.execute("Say ok.") + error = "" if answer.error.startswith(NO_DIFF) else answer.error return codex_verdict((ROOT / path).exists(), write, read_code, error) From 803d6919ce1fa59a23f1fb3a8d3ae57fa5b328a0 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:02:44 +0000 Subject: [PATCH 18/49] scripts: label the machine's directories in a failure reason rather than cut paths A reason recorded in Yard Log has the output directory, the tree and the home directory, in each spelling the system gives them, replaced by , and ~. The pattern it replaces mangled relative paths and addresses, and kept a user's name in a two-part or spaced path. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/reviewers.py | 19 +++++++++++++------ scripts/agent-review/test_review.py | 13 ++++++++++++- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/scripts/agent-review/reviewers.py b/scripts/agent-review/reviewers.py index daa390e0..d4b68310 100644 --- a/scripts/agent-review/reviewers.py +++ b/scripts/agent-review/reviewers.py @@ -8,7 +8,7 @@ from __future__ import annotations import json -import re +import os import secrets import shlex import subprocess @@ -77,10 +77,17 @@ def unwrapped(command: str) -> str: return command -def path_free(text: str) -> str: - """Text with each absolute path cut to its last part, so that no record names the machine's - directories.""" - return re.sub(r"(?:/[^/\s'\"]+)+/([^/\s'\"]+)", r"\1", text) +def path_free(text: str, out: Path) -> str: + """Text with the machine's directories it may name, the output directory, the tree and the + home directory, in each spelling the system gives them, replaced by a label, so that no + record names where the run happened.""" + labels = {} + for directory, label in ((out, ""), (ROOT, ""), (Path.home(), "~")): + for spelling in {str(directory), os.path.realpath(directory)}: + labels.setdefault(spelling, label) + for spelling in sorted(labels, key=len, reverse=True): + text = text.replace(spelling, labels[spelling]) + return text class Run: @@ -167,7 +174,7 @@ def task(self, stage: str, state: str) -> dict: "active": f"{head}, reviewing {where}.", "done": f"{head}, reviewed {where}; {self.ident_noun} {self.ident}; " f"tokens: {self.tokens}. Review: {self.review_path.name}", - "open": f"{head}, on {where} failed: {path_free(self.error)}", + "open": f"{head}, on {where} failed: {path_free(self.error, self.out)}", }[state] return { "id": f"review-{self.name}-{self.key}", "kind": "task", "stage": stage, diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index c6daef7e..3c84e912 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -16,7 +16,7 @@ import probe import review -from reviewers import ClaudeRun, CodexRun, Target, json_lines +from reviewers import ClaudeRun, CodexRun, Target, json_lines, path_free BASE, HEAD = "a" * 40, "b" * 40 TARGET = Target("develop", BASE, HEAD, "feature") @@ -146,6 +146,17 @@ def test_a_task_names_no_path_of_the_machine(self) -> None: done = CodexRun(TARGET, self.out, "high").task("s", "done")["detail"] self.assertNotIn(self.dir.name, done) + def test_a_reason_names_no_directory_of_the_machine_and_keeps_the_rest(self) -> None: + home = str(Path.home()) + reason = (f"'{self.out}/run.md' and '{home}/My Reviews/x.md': see " + "crates/loft-cli/src/main.rs and https://api.example.com/v1/responses") + cleaned = path_free(reason, self.out) + self.assertNotIn(home, cleaned) + self.assertNotIn(self.dir.name, cleaned) + self.assertIn("'/run.md' and '~/My Reviews/x.md'", cleaned) + kept = "crates/loft-cli/src/main.rs and https://api.example.com/v1/responses" + self.assertIn(kept, cleaned) + def test_a_failed_run_leaves_no_file_that_passes_for_a_review(self) -> None: run = ClaudeRun(TARGET, self.out, "high") run.read(claude_stream("git diff develop...feature")) From f317b26c34bb0d45215d115135e6a85a47c6653b Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:03:11 +0000 Subject: [PATCH 19/49] scripts: take touch's exit 1 as the probe's refused write, not the sandbox's wording A touch that could not start, which also writes nothing, exits otherwise and fails the probe, and a sandbox whose refusal reads in another language no longer does. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/probe.py | 11 ++++++----- scripts/agent-review/test_review.py | 5 ++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/scripts/agent-review/probe.py b/scripts/agent-review/probe.py index 3018586f..53ff511c 100644 --- a/scripts/agent-review/probe.py +++ b/scripts/agent-review/probe.py @@ -20,8 +20,9 @@ # The start event names the Agent tool by its older name, Task. CLAUDE_TOOL_NAMES = {*CLAUDE_TOOLS, "Task"} -# What a sandbox says when it refuses a write: macOS's Seatbelt, then Linux's. -REFUSALS = ("Operation not permitted", "Permission denied", "Read-only file system") +# `touch` exits 1 when it ran and its write failed; a command the sandbox could not start exits +# otherwise (126, 127, or 71 from Seatbelt), in any language. +WRITE_FAILED = 1 def write_request(path: str) -> str: @@ -66,9 +67,9 @@ def sandboxed(command: list[str]) -> subprocess.CompletedProcess: def codex_verdict(wrote: bool, write: subprocess.CompletedProcess, read_code: int, error: str) -> tuple[bool, str]: - """Whether Codex failed the probe, and what it showed: a write fails the probe unless the - sandbox itself refused it, not a command that could not start.""" - refused = write.returncode != 0 and any(words in write.stderr for words in REFUSALS) + """Whether Codex failed the probe, and what it showed: a write fails the probe unless `touch` + ran and its write failed, not when the command could not start.""" + refused = write.returncode == WRITE_FAILED shown = "made" if wrote else "refused by the sandbox" if refused else "not refused" read = "allowed" if read_code == 0 else "refused" message = f"Codex write in the tree: {shown}; read: {read}" diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index 3c84e912..ccb87549 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -306,13 +306,16 @@ def test_claude_fails_unless_the_refusal_was_its_write(self) -> None: def test_claude_fails_when_it_can_call_another_tool(self) -> None: self.assertTrue(self.claude("touch p1", tools=("Task", "Bash", "Read", "Skill", "Edit"))) - def test_codex_passes_only_when_the_sandbox_itself_refused_the_write(self) -> None: + def test_codex_passes_only_when_touch_ran_and_its_write_failed(self) -> None: def write(code: int, stderr: str = "") -> mock.Mock: return mock.Mock(returncode=code, stderr=stderr) refused = write(1, "touch: p1: Operation not permitted") self.assertFalse(probe.codex_verdict(False, refused, 0, "")[0]) self.assertTrue(probe.codex_verdict(False, write(0), 0, "")[0]) self.assertTrue(probe.codex_verdict(False, write(71, "execvp() failed"), 0, "")[0]) + self.assertTrue(probe.codex_verdict(False, write(126, "Permission denied"), 0, "")[0]) + localized = write(1, "touch: p1: Vorgang nicht zulässig") + self.assertFalse(probe.codex_verdict(False, localized, 0, "")[0]) self.assertTrue(probe.codex_verdict(True, refused, 0, "")[0]) self.assertTrue(probe.codex_verdict(False, refused, 1, "")[0]) self.assertTrue(probe.codex_verdict(False, refused, 0, "not signed in")[0]) From e941bfc3c6f43ca452393a0a085581b6f9eaec29 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:03:18 +0000 Subject: [PATCH 20/49] scripts: draw each invocation's suffix from 48 bits rather than 24 Its files are reserved in --out alone, so a suffix two output directories share would name one Yard task for two runs; a longer suffix leaves that to chance alone. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/reviewers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/agent-review/reviewers.py b/scripts/agent-review/reviewers.py index d4b68310..86a9891c 100644 --- a/scripts/agent-review/reviewers.py +++ b/scripts/agent-review/reviewers.py @@ -97,7 +97,7 @@ class Run: def __init__(self, target: Target, out: Path, effort: str) -> None: self.target, self.effort, self.out = target, effort, out - self.name_files(secrets.token_hex(3)) + self.name_files(secrets.token_hex(6)) self.text = self.ident = self.tokens = self.error = "" self.read_the_diff = False self.events: list[dict] = [] @@ -115,7 +115,7 @@ def reserve(self) -> None: self.raw_path.open("x").close() return except FileExistsError: - self.name_files(secrets.token_hex(3)) + self.name_files(secrets.token_hex(6)) def prompt(self, text: str) -> str: return text From bd4061fd73403a44238036c78a5a0c5371413bb0 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:03:35 +0000 Subject: [PATCH 21/49] test(agent-review): make the untracked-files and --stage refusal tests fail without their fixes The stubbed git hides untracked files unless asked for all of them, as a configured git would, and each --stage refusal is checked by its own words rather than by exit 2 alone. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/test_review.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/scripts/agent-review/test_review.py b/scripts/agent-review/test_review.py index ccb87549..049a9a2f 100644 --- a/scripts/agent-review/test_review.py +++ b/scripts/agent-review/test_review.py @@ -5,6 +5,7 @@ from __future__ import annotations +import io import json import os import subprocess @@ -190,10 +191,11 @@ def test_no_stage_records_nothing_and_succeeds(self) -> None: def stub_git(head: str = HEAD, branch: str = "feature", dirty: str = ""): - """A git that answers the runner's questions about the tree as given.""" + """A git that answers the runner's questions about the tree as given, configured as one that + hides untracked files unless asked for all of them.""" def git(*args: str) -> str: if args[0] == "status": - return dirty + return dirty if "--untracked-files=all" in args else "" if args[:2] == ("rev-parse", "--abbrev-ref"): return branch return head if args[-1] == "HEAD^{commit}" else BASE @@ -276,12 +278,16 @@ def test_a_host_started_from_the_other_must_be_named(self) -> None: self.assertEqual(review.host_and_session("codex", None), ("codex", "th")) def test_a_stage_that_would_record_nothing_is_refused(self) -> None: - for extra in (["--stage", ""], ["--stage", "s", "--probe"], ["--stage", "s", "--dry-run"]): + for extra, words in ((["--stage", ""], "--stage is empty"), + (["--stage", "s", "--probe"], "record nothing"), + (["--stage", "s", "--dry-run"], "record nothing")): argv = ["review.py", "--out", tempfile.gettempdir(), *extra] with self.subTest(extra=extra), mock.patch.object(sys, "argv", argv), \ - mock.patch("sys.stderr"), self.assertRaises(SystemExit) as stop: + mock.patch("sys.stderr", new_callable=io.StringIO) as said, \ + self.assertRaises(SystemExit) as stop: review.arguments() self.assertEqual(stop.exception.code, 2) + self.assertIn(words, said.getvalue()) class ProbeTests(unittest.TestCase): From 29ba0ba9958e82f22a0a5df2b3d7cacb16c88d6f Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:04:04 +0000 Subject: [PATCH 22/49] scripts: say which hidden files the tree check does not see Co-Authored-By: Claude Opus 5.5 --- scripts/agent-review/review.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/agent-review/review.py b/scripts/agent-review/review.py index 68cdb4aa..0b180ee4 100755 --- a/scripts/agent-review/review.py +++ b/scripts/agent-review/review.py @@ -150,8 +150,9 @@ def arguments() -> argparse.Namespace: def tree() -> tuple[str, str, str]: - """The checked-out commit, its branch, and what the tree holds beyond it, untracked files - included whatever git's configuration hides.""" + """The checked-out commit, its branch, and what the tree holds beyond it: untracked files + included, though `status.showUntrackedFiles` hides them, but not what an exclude file, + `assume-unchanged` or `skip-worktree` hides (docs/contributing/review.md, residual risks).""" return ( git("rev-parse", "--verify", "HEAD^{commit}"), git("rev-parse", "--abbrev-ref", "HEAD"), From ffe05bdf28d0ef1329307277685bdfb4bfc6cd09 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:04:04 +0000 Subject: [PATCH 23/49] docs(contributing): what the tree check guarantees, the --stage refusals, and the residual risks The tree is checked at a run's two ends, so the author leaves it alone meanwhile; --stage names the author's own stage, and the script's refusals and the task a branch switch leaves active are described; a new section lists what the runner does not catch, by choice. Co-Authored-By: Claude Opus 5.5 --- docs/contributing/review.md | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/docs/contributing/review.md b/docs/contributing/review.md index 1880d59b..2cfbb1e3 100644 --- a/docs/contributing/review.md +++ b/docs/contributing/review.md @@ -77,10 +77,11 @@ scripts/agent-review/review.py --context --out Date: Thu, 3 Dec 2026 13:10:27 +0000 Subject: [PATCH 24/49] spec: record an outside run's tokens with loft yard usage A run no Loft hook sees, such as a reviewer a script starts, is recorded by a task assigned to its session; loft yard usage counts its requests toward that task's stage, through the page server or, without one, under its lock, and counts each event id once. Co-Authored-By: Claude Opus 5.5 --- .../yard-client/commands/loft-yard-usage.yaml | 96 +++++++++++++++++++ spec/products/yard-client/product.yaml | 1 + 2 files changed, 97 insertions(+) create mode 100644 spec/products/yard-client/commands/loft-yard-usage.yaml diff --git a/spec/products/yard-client/commands/loft-yard-usage.yaml b/spec/products/yard-client/commands/loft-yard-usage.yaml new file mode 100644 index 00000000..f6417604 --- /dev/null +++ b/spec/products/yard-client/commands/loft-yard-usage.yaml @@ -0,0 +1,96 @@ +key: 01a23c06-5aae-7458-92c1-3bf30da6b510 +slug: loft-yard-usage +name: "Record an outside run's tokens" +body: | + A run that no Loft hook sees, such as a reviewer that a script starts with `claude -p` or `codex exec` and no Loft plugin, still spends tokens on the branch's work. Its caller learns the run's counts from the run's own output and records them with `loft yard usage`, so that the session's totals and the page count the run as they count any session's requests. + + The run is recorded by a task assigned to its session, which says what it worked on, and its requests count toward that task's stage, as the main agent's requests of the run's session. Each request carries an event id, so that recording a run twice counts it once. + + ```json + {"host": "codex", "session": "", "task": "", "requests": [{"eventId": "", "model": "", "at": "2026-12-03T12:00:00Z", "tokens": {"input": 0, "cacheRead": 0, "cacheWrite": 0, "output": 0}}]} + ``` +tags: + - yard-command + - needs-repository +realizes: + - 01a16469-559e-73c4-85f2-71a7729da1ec + - 01a16469-559e-73c4-85f2-71b305365c69 +requirements: + - key: 01a23c06-5aae-7458-92c1-3bf41bbf0b87 + statement: + form: event_driven + when: "a caller runs `loft yard usage` with a document that names an outside run's host, session and task, and the run's requests" + system: "`loft yard usage`" + shall: "count each request's input, cache read, cache write and output tokens into the totals file of the run's session, toward the stage of the task, as that session's main agent's requests on the request's model." + criteria: + - key: 01a23c06-5aae-7458-92c1-3bf5a5f48d7f + name: "The totals file of the run's session holds the four counts of each request, under the stage of the task the document names." + - key: 01a23c06-5aae-7458-92c1-3bf6318b705c + name: "The totals file holds each request's counts under the main agent of the run's session and the model the request names." + - key: 01a23c06-5aae-7458-92c1-3bf7fbd04ddc + name: "A request that names no time ends at the time the command runs." + - key: 01a23c06-5aae-7458-92c1-3bf875993c40 + name: "A request whose event id was recorded before with the same document is counted once." + - key: 01a23c06-5aae-7458-92c1-3bf9d62b25cb + name: "A request that leaves out one of the four counts makes the totals' accounting partial." + - key: 01a23c06-5aae-7458-92c1-3bfa0f75fd34 + name: "The result names the session, the task, the stage and the number of requests counted." + - key: 01a23c06-5aae-7458-92c1-3bfb55e81285 + name: "Recording the requests leaves Yard Log's revision as it was." + - key: 01a23c06-5aae-7458-92c1-3bfcb379c1ea + statement: + form: state_driven + while: "a page server runs" + system: "`loft yard usage`" + shall: "record each request by posting its event to the page server." + criteria: + - key: 01a23c06-5aae-7458-92c1-3bfd9a93dd72 + name: "The page server's live totals of the run's session hold the requests once the command ends." + - key: 01a23c06-5aae-7458-92c1-3bfe28ff196d + statement: + form: state_driven + while: "no page server runs" + system: "`loft yard usage`" + shall: "hold the page server's lock while it appends each request's event to the session's event log and writes the session's totals file from that log." + criteria: + - key: 01a23c06-5aae-7458-92c1-3bffd707def1 + name: "The totals file holds the counts that the page server would count from the same events." + - key: 01a23c06-5aae-7458-92c1-3c00d785c4dd + name: "A page server that starts afterwards counts no request of the run a second time." + - key: 01a23c06-5aae-7458-92c1-3c0198f73268 + statement: + form: unwanted + if: "the task the document names is not a task of Yard Log assigned to the run's session" + system: "`loft yard usage`" + shall: "refuse the document and name the task." + criteria: + - key: 01a23c06-5aae-7458-92c1-3c0285523597 + name: "A task that Yard Log does not hold is refused." + - key: 01a23c06-5aae-7458-92c1-3c03ae65a61c + name: "A task assigned to another session, or to none, is refused." + - key: 01a23c06-5aae-7458-92c1-3c04382b6c7c + name: "No totals file and no event log is changed." + - key: 01a23c06-5aae-7458-92c1-3c054af4075f + statement: + form: unwanted + if: "the document lacks the run's host, session, task or requests, or a request lacks its event id or model, or gives a count that is not a whole number of at least zero" + system: "`loft yard usage`" + shall: "refuse the document and name the field." + criteria: + - key: 01a23c06-5aae-7458-92c1-3c06661e68f6 + name: "A document without requests is refused." + - key: 01a23c06-5aae-7458-92c1-3c07ff7b3f9e + name: "A request without an event id is refused." + - key: 01a23c06-5aae-7458-92c1-3c08cf7ce123 + name: "A negative count is refused." + - key: 01a23c06-5aae-7458-92c1-3c09091591af + name: "No totals file and no event log is changed." + - key: 01a23c06-5aae-7458-92c1-3c0a28072152 + statement: + form: unwanted + if: "the branch's Yard Log is closed" + system: "`loft yard usage`" + shall: "count no request and say that Yard Log is closed." + criteria: + - key: 01a23c06-5aae-7458-92c1-3c0bb6ba40ca + name: "No totals file and no event log is changed." diff --git a/spec/products/yard-client/product.yaml b/spec/products/yard-client/product.yaml index 175f8bb4..e913cca5 100644 --- a/spec/products/yard-client/product.yaml +++ b/spec/products/yard-client/product.yaml @@ -142,6 +142,7 @@ featureGroups: - 01a182b6-3c58-7235-ad04-3916200a0c81 - 01a1c32b-8dbe-7792-8bde-87963dd33a56 - 01a1d123-dd40-7261-9ea6-092fa0b7887b + - 01a23c06-5aae-7458-92c1-3bf30da6b510 constraints: - key: 01a16469-55a3-716f-a42c-3a407e6d0d19 name: "Yard Client shall change the working tree only under `.yard/`." From dbedbc2d87d28491d0e76adcc83fa0f8c0ef8f77 Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:13:36 +0000 Subject: [PATCH 25/49] docs(agents): move the release steps out of AGENTS.md, and hold it to Codex's 32 KiB Codex loads at most 32 KiB of a project's instructions and drops the rest, which cut off the Review section and everything after it. The release steps, needed only at a release, move word for word to docs/contributing/releasing.md, AGENTS.md keeps a pointer to them, and a guard fails once AGENTS.md is longer than Codex loads. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 113 +---------------- CONTRIBUTING.md | 2 +- crates/loft-cli/tests/guards/agents_budget.rs | 36 ++++++ crates/loft-cli/tests/guards/mod.rs | 6 +- docs/contributing/releasing.md | 115 ++++++++++++++++++ 5 files changed, 159 insertions(+), 113 deletions(-) create mode 100644 crates/loft-cli/tests/guards/agents_budget.rs create mode 100644 docs/contributing/releasing.md diff --git a/AGENTS.md b/AGENTS.md index 77536c23..e0134928 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -395,116 +395,9 @@ The thinking behind the Software Plant is at . ## Releasing -A release happens only with the maintainer's approval, and in this order: - -0. Run `.github/workflows/build.yml` on `develop` ("Run workflow" on its page, or - `gh workflow run build.yml --ref develop`) and wait for every platform to build. Ordinary CI - builds only the host platform, so a change that breaks a cross-build, such as a dependency - with C code, shows here first. -1. On a branch from `develop`, set the new version in every crate's `Cargo.toml`, in the workspace - dependencies, in both plugin manifests and in `PLUGIN_VERSION` of the Claude Code plugin's - `hooks/adapter/index.tsx` (`tests/project/plugins/mod.rs` fails until they agree), and run - `scripts/changelog.sh X.Y.Z`, which writes the version's dated entry in `CHANGELOG.md` from the - change files under `changes/`, above the entries of that version's prereleases, which stay as - they are, and removes the files. Read the entry it wrote before you commit it. Merge the branch - into `develop`, then `develop` into `main`. -2. On `main`, run `loft publish` over the committed `spec/`, commit `spec/labels.yaml` and - `loft.lock.json` together as the publish commit, and check that `loft verify` passes. A second - `loft publish` with nothing changed writes nothing; CI checks both on `main` only, since - `develop` carries unpublished candidates. Push `main`. -3. On `main`, run `scripts/release-check.sh vX.Y.Z`; it checks `HEAD` while the tag does not - exist, and refuses it while `changes/` still holds a change file. Then tag `vX.Y.Z` on `main` - and push the tag. -4. The tag starts `.github/workflows/release.yml`. It runs the release check and the gate, builds - `loft` for each supported platform through `build.yml`, packs the npm packages into tarballs, - runs `loft` through the launcher from them (`scripts/npm-smoke.sh`) and checks them with a dry - run, then waits for the maintainer to approve: on the run's page, "Review deployments", tick - `release`, "Approve and deploy". Once approved, the publish job runs the tarballs it downloaded - once more, `scripts/publish-crates.sh` publishes the crates to crates.io in dependency order, - without building them again (the check job's dry run built each from its package on the same - commit), `scripts/publish-npm.sh` publishes the platform packages and then `@ask-loft/loft`, and - the tag gets a GitHub release with the binaries, whose notes are the version's changelog entry. - Both registries trust the workflow through Trusted Publishing; no registry token is stored - anywhere. -5. Merge `main` back into `develop`, so the allocated labels and the release reach it. - -When `develop` holds work that is not ready to go out, a release is cut from `main` instead: -branch from `main`, run step 0 on that branch (`gh workflow run build.yml --ref `), make -the version change of step 1 on it and merge it into `main` alone, then go on from step 2. Step 5 -brings the release into `develop` and removes there the change files the release gathered; those -of the work that was not ready stay under `changes/` for the next release. - -If a step of the publish job fails, fix its cause and choose "Re-run failed jobs" on the run. -Each step skips what its registry or GitHub already holds, so the run publishes only the rest. - -`software-plant` is never published (`publish = false`). CI on `main` runs -`cargo publish --workspace --dry-run`, so a crate that would not package fails before a release. - -### Prerelease from `develop` - -A prerelease, `vX.Y.Z-alpha.N`, `-beta.N` or `-rc.N`, lets people try what `develop` holds before -the release `X.Y.Z`. It too happens only with the maintainer's approval: - -1. Run step 0 on `develop`. -2. On a branch from `develop`, set the version `X.Y.Z-alpha.N` everywhere step 1 sets one, and - add by hand a dated entry `## X.Y.Z-alpha.N (YYYY-MM-DD)` above the newest entry in - `CHANGELOG.md`: one short paragraph that says how to install it and what it lets people try. - The change files stay under `changes/` for the release. Merge it into `develop` and push - `develop`. -3. On `develop`, run `scripts/release-check.sh vX.Y.Z-alpha.N`, then tag `vX.Y.Z-alpha.N` there - and push the tag. There is no `loft publish`: `develop`'s specification is published by the - release that follows, so the workflow skips `loft verify`. -4. Approve the run as in step 4. npm publishes the packages under the dist-tag `alpha` (`beta`, - `rc`), so `npm install @ask-loft/loft@alpha` installs it and `latest` stays the last release; - the GitHub release is marked a prerelease; crates.io serves it only to those who name it. - -### A minor line beside `develop` - -When the next minor version, `X.Y`, needs to be tried for longer while `develop` goes on -releasing the version before it, it lives on its own line, the branch `develop-X.Y`, cut from -`develop` (git refuses `develop/X.Y` beside `develop`). Feature branches for `X.Y` are cut from -the line and merge into it. - -- After each release or prerelease of `develop`, merge `develop` into the line, so the line holds - everything `develop` has released. A command's schema that `develop` moved to a new version - meanwhile and the line changed too takes the next version on the line, since `develop`'s is - released first. -- The line's change files lie under `changes/` as `develop`'s do. A merge carries them as - files in either direction, and a release gathers only the files its branch holds, so a release - of `develop` merged into the line removes only its own. -- A prerelease of the line follows the steps of a prerelease from `develop` on the line instead: - step 0 on the line (`gh workflow run build.yml --ref develop-X.Y`), the version - `X.Y.0-alpha.N` set and its dated entry added above the newest entry in `CHANGELOG.md`, then - `scripts/release-check.sh vX.Y.0-alpha.N` and the tag on the line. The release check accepts a - prerelease on the line of its own major and minor numbers, and npm publishes it under the - dist-tag `next`, so `npm install @ask-loft/loft@next` installs it while `alpha`, `beta` and - `rc` stay with `develop`'s prereleases. -- Once `X.Y` is ready, and `develop`'s last release before it is out, merge the line into - `develop` and delete the line; `X.Y.0` is then released from `develop` and `main` as any - release is. - -### Release setup - -Set up once, and kept as it is: - -- The GitHub environment `release` requires the maintainer's approval, and only tags matching - `v*` may deploy to it. -- On crates.io, each published crate names the trusted publisher `Ask-Loft/loft`, workflow - `release.yml`, environment `release`. -- On npmjs.com, each of `@ask-loft/loft` and its platform packages names the same trusted - publisher, with "Allow npm publish" ticked and "Allow npm dist-tag" left off. - -A registry names a trusted publisher only for a package that already exists, and npm requires -2FA for a publish with a token. So a new crate or npm package, such as one for a new platform, is -published by hand the first time, from what the release run built: - -- A crate: `cargo publish -p ` from a checkout of the tag, logged in with `cargo login`. -- An npm package: `gh run download -n release`, then - `scripts/publish-npm.sh release/npm` logged in with `npm login`; npm asks for 2FA for each - package it publishes and skips those it holds. - -Then register its trusted publisher as above, and choose "Re-run failed jobs" on the run, which -completes the release. +A release happens only with the maintainer's approval, in the order +`docs/contributing/releasing.md` gives: a release, a prerelease from `develop`, a minor line +beside `develop`, and the release setup kept once. ## Public hygiene diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8ca21af1..925e6e6f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -131,7 +131,7 @@ reviewer cannot run for you, say so in the template instead of leaving its row e Releases are cut by the maintainer: a tag `vX.Y.Z` on `main` runs the release workflow, which publishes the crates to crates.io and the prebuilt binaries to npm after the maintainer approves -it. `AGENTS.md` lists the steps. +it. `docs/contributing/releasing.md` lists the steps. ## Public by default diff --git a/crates/loft-cli/tests/guards/agents_budget.rs b/crates/loft-cli/tests/guards/agents_budget.rs new file mode 100644 index 00000000..7b61278b --- /dev/null +++ b/crates/loft-cli/tests/guards/agents_budget.rs @@ -0,0 +1,36 @@ +//! `AGENTS.md` stays within what Codex loads of a project's instructions. Codex reads at most +//! 32 KiB of them and drops the rest without a word, so a guide that grows past the budget loses +//! its last sections for every Codex session. Move a section an agent seldom needs into a file +//! under `docs/contributing/`, as the release steps are, rather than raise the budget. + +use std::fs; + +use crate::common::workspace; + +/// The bytes of a project's instructions Codex loads. +const CODEX_INSTRUCTION_BUDGET: usize = 32 * 1024; + +/// Why `text`, the agent guide, does not fit the budget, or nothing when it does. +fn over_budget(text: &str) -> Option { + (text.len() > CODEX_INSTRUCTION_BUDGET).then(|| { + format!( + "AGENTS.md holds {} bytes, over the {CODEX_INSTRUCTION_BUDGET} that Codex loads of a \ + project's instructions; move a section an agent seldom needs under \ + docs/contributing/", + text.len() + ) + }) +} + +#[test] +fn the_agent_guide_fits_the_bytes_codex_loads_of_it() { + let text = fs::read_to_string(workspace().join("AGENTS.md")).expect("AGENTS.md reads"); + assert_eq!(over_budget(&text), None); +} + +#[test] +fn a_guide_one_byte_over_the_budget_is_refused() { + assert_eq!(over_budget(&"a".repeat(CODEX_INSTRUCTION_BUDGET)), None); + let refusal = over_budget(&"a".repeat(CODEX_INSTRUCTION_BUDGET + 1)).expect("refused"); + assert!(refusal.contains("32768")); +} diff --git a/crates/loft-cli/tests/guards/mod.rs b/crates/loft-cli/tests/guards/mod.rs index 7ca71f2a..27e563e4 100644 --- a/crates/loft-cli/tests/guards/mod.rs +++ b/crates/loft-cli/tests/guards/mod.rs @@ -1,6 +1,8 @@ -//! The guards over this repository's own source: its spelling, change files, test names and -//! modules, source limits, the ports it reaches the outside through, and the binary it ships. +//! The guards over this repository's own source: its agent guide's size, its spelling, change +//! files, test names and modules, source limits, the ports it reaches the outside through, and the +//! binary it ships. +mod agents_budget; mod american_english; mod change_files; mod citations; diff --git a/docs/contributing/releasing.md b/docs/contributing/releasing.md new file mode 100644 index 00000000..aa9e2dcc --- /dev/null +++ b/docs/contributing/releasing.md @@ -0,0 +1,115 @@ +# Releasing + +How a release of Loft is cut, from this repository, by the maintainer. The rules every change +follows are in [`AGENTS.md`](../../AGENTS.md); this file holds only what a release adds. + +A release happens only with the maintainer's approval, and in this order: + +0. Run `.github/workflows/build.yml` on `develop` ("Run workflow" on its page, or + `gh workflow run build.yml --ref develop`) and wait for every platform to build. Ordinary CI + builds only the host platform, so a change that breaks a cross-build, such as a dependency + with C code, shows here first. +1. On a branch from `develop`, set the new version in every crate's `Cargo.toml`, in the workspace + dependencies, in both plugin manifests and in `PLUGIN_VERSION` of the Claude Code plugin's + `hooks/adapter/index.tsx` (`tests/project/plugins/mod.rs` fails until they agree), and run + `scripts/changelog.sh X.Y.Z`, which writes the version's dated entry in `CHANGELOG.md` from the + change files under `changes/`, above the entries of that version's prereleases, which stay as + they are, and removes the files. Read the entry it wrote before you commit it. Merge the branch + into `develop`, then `develop` into `main`. +2. On `main`, run `loft publish` over the committed `spec/`, commit `spec/labels.yaml` and + `loft.lock.json` together as the publish commit, and check that `loft verify` passes. A second + `loft publish` with nothing changed writes nothing; CI checks both on `main` only, since + `develop` carries unpublished candidates. Push `main`. +3. On `main`, run `scripts/release-check.sh vX.Y.Z`; it checks `HEAD` while the tag does not + exist, and refuses it while `changes/` still holds a change file. Then tag `vX.Y.Z` on `main` + and push the tag. +4. The tag starts `.github/workflows/release.yml`. It runs the release check and the gate, builds + `loft` for each supported platform through `build.yml`, packs the npm packages into tarballs, + runs `loft` through the launcher from them (`scripts/npm-smoke.sh`) and checks them with a dry + run, then waits for the maintainer to approve: on the run's page, "Review deployments", tick + `release`, "Approve and deploy". Once approved, the publish job runs the tarballs it downloaded + once more, `scripts/publish-crates.sh` publishes the crates to crates.io in dependency order, + without building them again (the check job's dry run built each from its package on the same + commit), `scripts/publish-npm.sh` publishes the platform packages and then `@ask-loft/loft`, and + the tag gets a GitHub release with the binaries, whose notes are the version's changelog entry. + Both registries trust the workflow through Trusted Publishing; no registry token is stored + anywhere. +5. Merge `main` back into `develop`, so the allocated labels and the release reach it. + +When `develop` holds work that is not ready to go out, a release is cut from `main` instead: +branch from `main`, run step 0 on that branch (`gh workflow run build.yml --ref `), make +the version change of step 1 on it and merge it into `main` alone, then go on from step 2. Step 5 +brings the release into `develop` and removes there the change files the release gathered; those +of the work that was not ready stay under `changes/` for the next release. + +If a step of the publish job fails, fix its cause and choose "Re-run failed jobs" on the run. +Each step skips what its registry or GitHub already holds, so the run publishes only the rest. + +`software-plant` is never published (`publish = false`). CI on `main` runs +`cargo publish --workspace --dry-run`, so a crate that would not package fails before a release. + +## Prerelease from `develop` + +A prerelease, `vX.Y.Z-alpha.N`, `-beta.N` or `-rc.N`, lets people try what `develop` holds before +the release `X.Y.Z`. It too happens only with the maintainer's approval: + +1. Run step 0 on `develop`. +2. On a branch from `develop`, set the version `X.Y.Z-alpha.N` everywhere step 1 sets one, and + add by hand a dated entry `## X.Y.Z-alpha.N (YYYY-MM-DD)` above the newest entry in + `CHANGELOG.md`: one short paragraph that says how to install it and what it lets people try. + The change files stay under `changes/` for the release. Merge it into `develop` and push + `develop`. +3. On `develop`, run `scripts/release-check.sh vX.Y.Z-alpha.N`, then tag `vX.Y.Z-alpha.N` there + and push the tag. There is no `loft publish`: `develop`'s specification is published by the + release that follows, so the workflow skips `loft verify`. +4. Approve the run as in step 4. npm publishes the packages under the dist-tag `alpha` (`beta`, + `rc`), so `npm install @ask-loft/loft@alpha` installs it and `latest` stays the last release; + the GitHub release is marked a prerelease; crates.io serves it only to those who name it. + +## A minor line beside `develop` + +When the next minor version, `X.Y`, needs to be tried for longer while `develop` goes on +releasing the version before it, it lives on its own line, the branch `develop-X.Y`, cut from +`develop` (git refuses `develop/X.Y` beside `develop`). Feature branches for `X.Y` are cut from +the line and merge into it. + +- After each release or prerelease of `develop`, merge `develop` into the line, so the line holds + everything `develop` has released. A command's schema that `develop` moved to a new version + meanwhile and the line changed too takes the next version on the line, since `develop`'s is + released first. +- The line's change files lie under `changes/` as `develop`'s do. A merge carries them as + files in either direction, and a release gathers only the files its branch holds, so a release + of `develop` merged into the line removes only its own. +- A prerelease of the line follows the steps of a prerelease from `develop` on the line instead: + step 0 on the line (`gh workflow run build.yml --ref develop-X.Y`), the version + `X.Y.0-alpha.N` set and its dated entry added above the newest entry in `CHANGELOG.md`, then + `scripts/release-check.sh vX.Y.0-alpha.N` and the tag on the line. The release check accepts a + prerelease on the line of its own major and minor numbers, and npm publishes it under the + dist-tag `next`, so `npm install @ask-loft/loft@next` installs it while `alpha`, `beta` and + `rc` stay with `develop`'s prereleases. +- Once `X.Y` is ready, and `develop`'s last release before it is out, merge the line into + `develop` and delete the line; `X.Y.0` is then released from `develop` and `main` as any + release is. + +## Release setup + +Set up once, and kept as it is: + +- The GitHub environment `release` requires the maintainer's approval, and only tags matching + `v*` may deploy to it. +- On crates.io, each published crate names the trusted publisher `Ask-Loft/loft`, workflow + `release.yml`, environment `release`. +- On npmjs.com, each of `@ask-loft/loft` and its platform packages names the same trusted + publisher, with "Allow npm publish" ticked and "Allow npm dist-tag" left off. + +A registry names a trusted publisher only for a package that already exists, and npm requires +2FA for a publish with a token. So a new crate or npm package, such as one for a new platform, is +published by hand the first time, from what the release run built: + +- A crate: `cargo publish -p ` from a checkout of the tag, logged in with `cargo login`. +- An npm package: `gh run download -n release`, then + `scripts/publish-npm.sh release/npm` logged in with `npm login`; npm asks for 2FA for each + package it publishes and skips those it holds. + +Then register its trusted publisher as above, and choose "Re-run failed jobs" on the run, which +completes the release. From 562d4ecea83e2a9a6e3ff47c8fd08dc0aaa6f4fc Mon Sep 17 00:00:00 2001 From: Sergey Lobko-Lobanovsky Date: Thu, 3 Dec 2026 13:22:05 +0000 Subject: [PATCH 26/49] feat(yard): record an outside run's tokens with `loft yard usage` A run that no Loft hook sees, such as a reviewer a script starts, is recorded by the task assigned to its session: each request becomes a model request's event naming the task, posted to the page server while one runs, else recorded as the page server records it, under its lock. Co-Authored-By: Claude Opus 5.5 --- crates/loft-cli/src/yard/args.rs | 15 ++ crates/loft-cli/src/yard/commands/mod.rs | 1 + crates/loft-cli/src/yard/commands/usage.rs | 240 ++++++++++++++++++ crates/loft-cli/src/yard/mod.rs | 8 +- crates/loft-cli/src/yard/serve/mod.rs | 9 + crates/loft-cli/tests/common/commands.rs | 14 +- crates/loft-cli/tests/yard/mod.rs | 1 + crates/loft-cli/tests/yard/outside_runs.rs | 271 +++++++++++++++++++++ schemas/yard-usage.json | 256 +++++++++++++++++++ testdata/yard/usage.json | 13 + 10 files changed, 825 insertions(+), 3 deletions(-) create mode 100644 crates/loft-cli/src/yard/commands/usage.rs create mode 100644 crates/loft-cli/tests/yard/outside_runs.rs create mode 100644 schemas/yard-usage.json create mode 100644 testdata/yard/usage.json diff --git a/crates/loft-cli/src/yard/args.rs b/crates/loft-cli/src/yard/args.rs index 2101e403..bbe0df11 100644 --- a/crates/loft-cli/src/yard/args.rs +++ b/crates/loft-cli/src/yard/args.rs @@ -287,6 +287,21 @@ pub struct UpgradeArgs { pub output: Output, } +#[derive(Args)] +pub struct UsageArgs { + /// The file that holds the outside run and its requests as JSON, or `-` for standard input. + #[arg(long, value_name = "FILE")] + pub input: PathBuf, + /// A directory of the worktree whose Yard Log holds the run's task, in place of the + /// command's own directory. + #[arg(long, value_name = "DIR")] + pub tree: Option, + #[command(flatten)] + pub beyond: Beyond, + #[command(flatten)] + pub output: Output, +} + #[derive(Args)] pub struct ContinueArgs { /// The agent host; omitted by legacy Claude callers. diff --git a/crates/loft-cli/src/yard/commands/mod.rs b/crates/loft-cli/src/yard/commands/mod.rs index 568046ce..cfa182c9 100644 --- a/crates/loft-cli/src/yard/commands/mod.rs +++ b/crates/loft-cli/src/yard/commands/mod.rs @@ -12,6 +12,7 @@ pub mod protocol; pub mod published; pub mod read; pub mod task; +pub mod usage; pub mod wait; pub mod withdraw; pub mod write; diff --git a/crates/loft-cli/src/yard/commands/usage.rs b/crates/loft-cli/src/yard/commands/usage.rs new file mode 100644 index 00000000..9a64730f --- /dev/null +++ b/crates/loft-cli/src/yard/commands/usage.rs @@ -0,0 +1,240 @@ +//! `loft yard usage` (the Record an outside run's tokens Feature): the tokens of a run that no +//! Loft hook saw, such as a reviewer a script started, counted into its session's totals toward +//! the stage of the task it is recorded by. Each request becomes a model request's event that +//! names the task, so that the page server's own rule counts it toward the task's stage as the +//! main agent's of the run's session: posted to the page server while one runs, else recorded as +//! the page server records it, under its lock. Yard Log itself is read, never written. + +use std::path::Path; + +use serde_json::{Map, Value, json}; +use yardlog::{Agent, Handle, Time, YardLog}; +use yardlog_store::Held; +use yardlog_store::home::Home; + +use crate::finish::Finished; +use crate::yard::args::UsageArgs; +use crate::yard::branch::{self, Branch}; +use crate::yard::failure::{self, Failure}; +use crate::yard::{input, now, page, serve}; + +const SCHEMA: &str = "loft-yard-usage/1"; +const OUTCOME: &str = "recorded"; + +/// The four counts of a request, as a model request's event names them. +const COUNTS: [&str; 4] = ["input", "cacheRead", "cacheWrite", "output"]; + +/// An outside run, as the document names it. +struct Run { + host: String, + session: String, + task: Handle, + requests: Vec, +} + +/// One of the run's requests. +struct Request { + event_id: String, + model: String, + at: Option