Skip to content

Commit de42af8

Browse files
chore: sync engineering assets (#145)
Touchmark-Hub: bedrock-python@github.com/1408350934 Touchmark-Stream: sync Touchmark-Content: sha256:23099ac284f7b1b9f155582d914a922a25594b5509d48472f901b749e4984206 Touchmark-Hub-Commit: 0cd925edd6132a4cd33e0859176ca1d32a11651b Co-authored-by: bedrock-python-assets-write[bot] <339090477+bedrock-python-assets-write[bot]@users.noreply.github.com>
1 parent eb29d57 commit de42af8

26 files changed

Lines changed: 878 additions & 10 deletions

File tree

‎.agents/review/README.md‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# AI review
2+
3+
The author of a pull request reviews the branch with an AI agent before asking people to review it, fixes what the review finds or dismisses it with a reason, and says so in the pull request's "AI Review" section. The people who review the pull request then look at what an AI cannot judge, and do not run it through an AI themselves ("Working with it" below).
4+
5+
It works the same in every agent: the same prompts, the same record. The reviewers always start in a fresh context, without the conversation that produced the change, on a model no weaker than the author's ("Fresh reviewers" in `review.md`). The agent that wrote the change only takes their findings and settles them with the user.
6+
7+
These files come from the `ai-review` pack of your organisation's engineering-assets hub.
8+
9+
| File | What |
10+
|---|---|
11+
| [`review.md`](review.md) | the review: scope, directions, verifying and ranking findings, the record |
12+
| [`directions/`](directions/) | one prompt per direction: what to look for and what counts as evidence |
13+
| [`pure-refactor.md`](pure-refactor.md) | a check that a change claimed to keep behaviour keeps it |
14+
| [`check.py`](check.py) | says whether the branch's review covers its last commit; a pre-push hook runs it |
15+
16+
## Directions
17+
18+
| Direction | Looks for |
19+
|---|---|
20+
| [Correctness](directions/correctness.md) | logic errors, edge inputs, swallowed and unnoticed errors, races, transactions, resources |
21+
| [Security](directions/security.md) | secrets, injection, access checks, data exposure, insecure defaults, new dependencies |
22+
| [Performance](directions/performance.md) | N+1 and unbounded queries, blocking calls in async code, work that grows with the data |
23+
| [Design & Style](directions/design.md) | why each new thing exists, what already exists, layers, simplicity, naming, comments |
24+
| [Tests](directions/tests.md) | new behaviour without a test, tests that check nothing, tests bent to fit |
25+
| [Compatibility](directions/compatibility.md) | API and schema contracts, migrations, rollout, stored data, configuration, flags, stale docs |
26+
27+
A repository adds its own focus areas in a `## Review` section of `.agents/project.md`, one line each: `- <direction>: <what to check>`. A name that is none of the directions above becomes a direction of its own, with its own line in the pull request.
28+
29+
## Running it
30+
31+
The agent runs the review by itself once the last change of a task is committed (`AGENTS.md`), so nobody has to remember. Unlike the starter review, it is not read-only: it writes the record in `local/`, and the agent then fixes the findings the user agrees with. By hand:
32+
33+
| Agent | Review | Pure-refactor check |
34+
|---|---|---|
35+
| Claude Code | `/review-change` | `/review-change pure-refactor` |
36+
| Codex | `$review-change` | `$review-change pure-refactor` |
37+
| Cursor | `/review-change` | `/review-change pure-refactor` |
38+
| OpenCode | "review my branch" | "check that my branch keeps behaviour" |
39+
| any chat | paste `review.md`, the direction files and `git diff <base>...HEAD` (`<base>` as in `review.md`) | paste `pure-refactor.md` and the diff |
40+
41+
The request may name directions (`/review-change security performance`), ask for `full` (the whole branch again, not a follow-up over the changes since the last review), or give `staged`, `working` or a path.
42+
43+
The skill is `.agents/skills/review-change/`, where Codex, Cursor and OpenCode find it. In Claude Code, `/review-change` of the `claude` pack follows it whenever this directory exists, and the `reviewer` subagent is the fresh reviewer it starts for each direction.
44+
45+
## The record
46+
47+
Every run updates the branch's one record, `local/reviews/<branch>.md` (`local/` is gitignored): the commit the last complete run covered, the reviewers' model, the result per direction and each finding with its status: fixed, dismissed with the reason, or open. The next run reviews only what changed since that commit and does not bring back what was dismissed. The format is in [`review.md`](review.md).
48+
49+
## In the pull request
50+
51+
The description ends with an "AI Review" section, built from the record and nothing else, in the language `.agents/project.md` names for pull requests. With the `claude` pack, `/pr` adds it. Put the section into the repository's pull request template, so that people see it is expected:
52+
53+
```markdown
54+
#### AI Review
55+
56+
Commit `a1b2c3d`, Claude Opus 5.5
57+
58+
- [x] Correctness - 2 fixed
59+
- [x] Security - no findings
60+
- [x] Performance - 1 fixed, 1 dismissed
61+
- [x] Design & Style - 3 fixed
62+
- [x] Tests - no findings
63+
- [x] Compatibility - not applicable: no API, schema or configuration change
64+
65+
<details><summary>Dismissed (1)</summary>
66+
67+
- `src/keys.py:42` - N+1 when loading keys: the list holds at most 5 keys
68+
</details>
69+
```
70+
71+
- The first line is the record's `commit` (short sha) and `model`. When the user declined a follow-up over later fixes, it adds ", fixes after it not reviewed again".
72+
- One line per direction of the record, in its order and under its name, the repository's own directions and Pure-refactor check included. A direction that was not run is unchecked: `- [ ] Tests - not run`.
73+
- The block of dismissed findings lists each dismissed blocking or should-fix finding with its reason; no dismissed findings, no block. Nits never go there, and a finding about a secret names its place and kind, never the value.
74+
75+
## Working with it
76+
77+
- **The AI review is the author's job.** Before the pull request is opened for review (a draft opened only so that CI runs is not), the author reviews the branch, fixes what the review finds or dismisses it with a reason, and fills the "AI Review" section. A pull request without it, or with its boxes unchecked, is not ready for review. After the fixes, and after changes made in review, the author runs a follow-up on the new commits: it checks the fixes and the lines they touched, not the whole branch again. Commits that only fix findings may go without one: the author's call, and the section says so.
78+
- **People review what an AI cannot judge**: does the change solve the task, are the model and the contracts right, is the rollout plan right, what does it do to its neighbours, will the next person understand it, and are the dismissed findings fair.
79+
- **No AI-generated comments on someone else's pull request.** Do not run a colleague's change through an AI and post what it says. Using an AI to understand the code is fine; the comment is your own.
80+
- **A bug the AI review should have caught** gets a review thread that starts with `ai-miss:`. Besides the fix, the author turns the miss into a rule where the review reads it, and links it in the reply: a line in the `Review` section of `.agents/project.md` if it is about this repository, otherwise a pull request or an issue to the hub on `packs/ai-review/.agents/review/directions/`.
81+
82+
## Wiring
83+
84+
Optional, once per repository, in its own files, in a pull request merged after the sync pull request that brings `.agents/review/`: until then the hook finds no script and fails every push. `check.py` needs Python 3.9 or later and only its standard library, so it runs in a repository of any language.
85+
86+
- A pre-push hook in `.pre-commit-config.yaml`. It never blocks a push, since unfinished branches are pushed to run CI, and only says when the review is missing or behind the branch:
87+
88+
```yaml
89+
- repo: local
90+
hooks:
91+
- id: ai-review
92+
name: ai review
93+
entry: python .agents/review/check.py
94+
language: python
95+
pass_filenames: false
96+
always_run: true
97+
verbose: true
98+
stages: [pre-push]
99+
```
100+
101+
- The way the repository installs its hooks installs `pre-push` too. Plain `pre-commit install` does once `default_install_hook_types` lists it (with `commit-msg` where a hook needs it); a README or Makefile that names hook types needs `--hook-type pre-push`. Where `pre-push` was not installed before, `default_stages: [pre-commit]` keeps the other hooks on commit instead of running them again on push; a repository whose hooks already run on push keeps them as they are. Hooks that declare their own stages, such as `trailing-whitespace` and `end-of-file-fixer` from pre-commit-hooks, run on push as well. After the change, everyone installs the hooks once more.
102+
- Without pre-commit, a `.git/hooks/pre-push` that runs `python .agents/review/check.py` does the same for one clone, but it checks the checked-out branch, which a plain `git push` pushes; pre-commit tells it the branch being pushed.

‎.agents/review/check.py‎

Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
"""
2+
Tells whether the AI review of a branch covers its last commit, from the record the review writes to
3+
local/reviews/<branch>.md (see README.md next to this file).
4+
5+
check.py say whether the review is missing or behind the branch; always exit 0
6+
check.py --strict the same, but exit 1 unless the branch is reviewed up to its last commit
7+
check.py --refresh when a rebase left the reviewed changes as they were under new commits,
8+
move the record's commit to them
9+
10+
As the pre-push hook it checks the branch being pushed and never blocks the push: unfinished branches
11+
are pushed to run CI. By hand it checks the branch checked out.
12+
13+
Only the standard library: it runs from pre-commit in a repository of any language.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import argparse
19+
import codecs
20+
import hashlib
21+
import os
22+
import re
23+
import shutil
24+
import subprocess
25+
import sys
26+
from dataclasses import dataclass
27+
from pathlib import Path
28+
29+
RECORDS = Path("local", "reviews")
30+
COMMIT = re.compile(r"^commit:[ \t]*([0-9a-f]{7,64})[ \t]*(?=\r?$)", re.MULTILINE)
31+
# agents write the record in UTF-8; PowerShell 5.1 redirection writes UTF-16
32+
BOMS = ((codecs.BOM_UTF16_LE, "utf-16"), (codecs.BOM_UTF16_BE, "utf-16"), (codecs.BOM_UTF8, "utf-8-sig"))
33+
# the diffs are read by this script, not a person: no colour, external diff or textconv a config may turn on
34+
PLAIN_DIFF = ("diff", "--no-color", "--no-ext-diff", "--no-textconv")
35+
HUNK_LINES = re.compile(rb"^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@")
36+
HOW = (
37+
"run it in your agent (/review-change, $review-change; .agents/review/README.md)"
38+
" before opening or updating the pull request"
39+
)
40+
41+
REVIEWED, BEHIND, SKIPPED = "reviewed", "behind", "skipped"
42+
43+
44+
@dataclass(frozen=True)
45+
class Branch:
46+
name: str
47+
head: str
48+
base: str | None
49+
top: Path
50+
51+
52+
@dataclass(frozen=True)
53+
class Record:
54+
path: Path
55+
text: str
56+
codec: str | None
57+
58+
59+
def main() -> int:
60+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
61+
parser.add_argument(
62+
"--strict", action="store_true", help="exit 1 unless the branch is reviewed up to its last commit"
63+
)
64+
parser.add_argument(
65+
"--refresh", action="store_true", help="move the record's commit to the same changes under new commits"
66+
)
67+
args = parser.parse_args()
68+
69+
try:
70+
status, message = check(refresh=args.refresh)
71+
except Exception as error: # noqa: BLE001, RUF100 - the hook must never block a push, so a broken check only says so
72+
status, message = BEHIND, f"AI review: the check failed: {error!r}"
73+
if status == SKIPPED and not args.strict:
74+
return 0
75+
sys.stdout.write(message + "\n")
76+
return 1 if args.strict and status != REVIEWED else 0
77+
78+
79+
def check(*, refresh: bool) -> tuple[str, str]:
80+
branch, skipped = branch_to_check()
81+
if branch is None:
82+
return SKIPPED, skipped
83+
relative = RECORDS / f"{branch.name}.md"
84+
path = branch.top / relative
85+
if not path.is_file():
86+
return BEHIND, f"AI review of {branch.name}: not run yet; {HOW}"
87+
record = Record(path, *read_record(path))
88+
reviewed, missing = reviewed_commit(record.text, relative)
89+
if reviewed is None:
90+
return BEHIND, f"AI review of {branch.name}: {missing}; {HOW}"
91+
if reviewed == branch.head:
92+
return REVIEWED, f"AI review: {branch.name} is reviewed up to its last commit"
93+
if git("merge-base", "--is-ancestor", reviewed, branch.head) is not None:
94+
return since_review(branch, reviewed)
95+
return after_rewrite(branch, reviewed, record, refresh=refresh)
96+
97+
98+
def branch_to_check() -> tuple[Branch | None, str]:
99+
"""The branch to check, or none and why it is skipped."""
100+
top = git("rev-parse", "--show-toplevel")
101+
if top is None:
102+
return None, "AI review: not in a git work tree, or git is missing"
103+
name, head = pushed_branch()
104+
if name is None or head is None:
105+
return None, "AI review: no branch to check (detached HEAD)"
106+
base = base_ref()
107+
if name in default_names(base):
108+
return None, f"AI review: {name} is the default branch"
109+
return Branch(name, head, base, Path(top)), ""
110+
111+
112+
def reviewed_commit(text: str, relative: Path) -> tuple[str | None, str]:
113+
"""The commit the record names, or none and what is wrong with the record."""
114+
found = COMMIT.search(text)
115+
if found is None:
116+
return None, f"{relative.as_posix()} names no commit"
117+
reviewed = git("rev-parse", "--verify", "--quiet", f"{found.group(1)}^{{commit}}")
118+
if reviewed is None:
119+
return None, f"the reviewed commit {found.group(1)[:8]} is not in this clone"
120+
return reviewed, ""
121+
122+
123+
def since_review(branch: Branch, reviewed: str) -> tuple[str, str]:
124+
changed = branch_files_changed(reviewed, branch.head, branch.base)
125+
if not changed:
126+
return REVIEWED, f"AI review: {branch.name} is reviewed; nothing of its own changed since {reviewed[:8]}"
127+
return (
128+
BEHIND,
129+
f"AI review of {branch.name}: {len(changed)} file(s) changed since the review at {reviewed[:8]}; {HOW}",
130+
)
131+
132+
133+
def after_rewrite(branch: Branch, reviewed: str, record: Record, *, refresh: bool) -> tuple[str, str]:
134+
# a rebase keeps the reviewed changes under new commits: compare the changes, not the commits
135+
if branch.base is None or not same_changes(reviewed, branch.head, branch.base):
136+
return (
137+
BEHIND,
138+
f"AI review of {branch.name}: rewritten since the review at {reviewed[:8]}, with other changes; {HOW}",
139+
)
140+
if refresh and record.codec is not None:
141+
record.path.write_bytes(COMMIT.sub(f"commit: {branch.head}", record.text, count=1).encode(record.codec))
142+
return (
143+
REVIEWED,
144+
f"AI review: {branch.name} carries the reviewed changes; the record now names {branch.head[:8]}",
145+
)
146+
return REVIEWED, f"AI review: {branch.name} carries the changes reviewed at {reviewed[:8]} under new commits"
147+
148+
149+
def pushed_branch() -> tuple[str | None, str | None]:
150+
local = os.environ.get("PRE_COMMIT_LOCAL_BRANCH")
151+
if local:
152+
# pre-commit's pre-push: the branch being pushed and its sha, which need not be the checked-out ones
153+
head = os.environ.get("PRE_COMMIT_TO_REF") or git("rev-parse", "--verify", "--quiet", local)
154+
if not local.startswith("refs/heads/"):
155+
# `git push origin HEAD` names no branch: it is the checked-out one when the shas agree
156+
if head is None or head != git("rev-parse", "--verify", "--quiet", "HEAD"):
157+
return None, None
158+
local = git("symbolic-ref", "--quiet", "HEAD")
159+
if not local:
160+
return None, None
161+
return local.removeprefix("refs/heads/"), head
162+
ref = git("symbolic-ref", "--quiet", "HEAD")
163+
if not ref:
164+
return None, None
165+
return ref.removeprefix("refs/heads/"), git("rev-parse", "--verify", "--quiet", ref)
166+
167+
168+
def base_ref() -> str | None:
169+
named = git("symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD")
170+
candidates = [named] if named else ["origin/master", "origin/main"]
171+
return next((ref for ref in candidates if git("rev-parse", "--verify", "--quiet", ref)), None)
172+
173+
174+
def default_names(base: str | None) -> set[str]:
175+
names = {"master", "main"}
176+
if base:
177+
names.add(base.split("/", 1)[-1])
178+
return names
179+
180+
181+
def read_record(path: Path) -> tuple[str, str | None]:
182+
"""The record's text and the codec to write it back with; no codec when it is not UTF-8 or UTF-16."""
183+
raw = path.read_bytes()
184+
for bom, codec in BOMS:
185+
if raw.startswith(bom):
186+
return raw.decode(codec, errors="replace"), codec
187+
try:
188+
return raw.decode("utf-8"), "utf-8"
189+
except UnicodeDecodeError:
190+
return raw.decode("utf-8", errors="replace"), None
191+
192+
193+
def same_changes(reviewed: str, head: str, base: str) -> bool:
194+
before = changes_id(reviewed, base)
195+
return before is not None and before == changes_id(head, base)
196+
197+
198+
def changes_id(commit: str, base: str) -> str | None:
199+
fork = git("merge-base", base, commit)
200+
if fork is None:
201+
return None
202+
diff = run(*PLAIN_DIFF, fork, commit)
203+
if not diff:
204+
return None
205+
# on a new base the same changes differ only in blob ids and line numbers; whitespace and context
206+
# lines still count, so a re-indented or moved line is a change to review again
207+
lines = [HUNK_LINES.sub(b"@@", line) for line in diff.split(b"\n") if not line.startswith(b"index ")]
208+
return hashlib.sha256(b"\n".join(lines)).hexdigest()
209+
210+
211+
def branch_files_changed(reviewed: str, head: str, base: str | None) -> set[str]:
212+
changed = set((git(*PLAIN_DIFF, "--name-only", reviewed, head) or "").splitlines())
213+
if base is None:
214+
return changed
215+
# a merge of the default branch brings other people's changes: only the branch's own files count
216+
own = set((git(*PLAIN_DIFF, "--name-only", f"{base}...{head}") or "").splitlines())
217+
return changed & own
218+
219+
220+
def git(*args: str) -> str | None:
221+
output = run(*args)
222+
return None if output is None else output.decode("utf-8", errors="replace").strip()
223+
224+
225+
def run(*args: str) -> bytes | None:
226+
executable = shutil.which("git")
227+
if not executable:
228+
return None
229+
result = subprocess.run([executable, *args], capture_output=True, check=False) # noqa: S603, RUF100
230+
return result.stdout if result.returncode == 0 else None
231+
232+
233+
if __name__ == "__main__":
234+
sys.exit(main())

0 commit comments

Comments
 (0)