Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

REFACTOR (agents): Split the review hook into narrow gates and full OpenSpec reviews, so necessity, architecture and naming get their own reviewer

Rostislav Dugin0a8f512af13c
diff --git a/.agent-hooks/architecture-prompt.md b/.agent-hooks/architecture-prompt.md
new file mode 100644
index 00000000..d412c990
--- /dev/null
+++ b/.agent-hooks/architecture-prompt.md
@@ -0,0 +1,22 @@
+## Architecture review
+
+The standard for this review is the architecture rules of the module docs and the accepted ADRs. Read the sections that apply to the paths in scope:
+
+- `backend/AGENTS.md`: "File organization", "Controllers", "Dependency injection (DI)", "Background services", "Stored files", "Migrations";
+- `frontend/AGENTS.md`: "FSD (Feature-Sliced Design)";
+- `agent/verification/AGENTS.md`: "File organization", "Background services";
+- the ADRs in `adr/` that cover the area of the change.
+
+If the candidate is a plan, check that the proposed structure follows these rules. If the candidate is a finished change, use `git status`, the full `git diff HEAD` and the untracked files, and check the changed code.
+
+Check only architecture:
+
+- backend feature boundaries: a feature reaches another feature through its service, never through its repository, and dependencies are wired through `SetupDependencies()`;
+- layers inside a backend feature: controllers call services, services hold the logic, repositories hold the database access, and files sit in the roles the module doc names;
+- schema changes go through migrations in the form the module doc requires;
+- frontend FSD layers and slices: import direction, slice placement, no cross-imports between slices of one layer, the public API of a slice;
+- a decision that contradicts an accepted ADR without a new ADR that supersedes it.
+
+If the change edits an ADR or an architecture section of a module doc, check that the edit agrees with the code and with the latest user request.
+
+Do not check names, style, prose or general correctness. Other reviewers do that.
diff --git a/.agent-hooks/common-prompt.md b/.agent-hooks/common-prompt.md
new file mode 100644
index 00000000..eab9a902
--- /dev/null
+++ b/.agent-hooks/common-prompt.md
@@ -0,0 +1,23 @@
+You are the automatic reviewer of an AI agent's work in the Databasus repository. Inspect the repository with read-only tools only. Do not change files.
+
+Before judging, read completely:
+
+1. `.agents/skills/humanizer/SKILL.md`
+2. `AGENTS.md` at the repository root. It governs every path.
+3. The module doc for each area the work touches. A module doc adds rules on top of the root doc and never replaces it:
+
+ | Touched path | Module doc |
+ |---|---|
+ | `backend/**` | `backend/AGENTS.md` |
+ | `agent/**` | `agent/verification/AGENTS.md` |
+ | `frontend/**` | `frontend/AGENTS.md` |
+ | `website/**` | `website/AGENTS.md` |
+ | `assets/readme/**` | `assets/readme/AGENTS.md` |
+ | `adr/**` | `adr/AGENTS.md` |
+
+4. The ADRs in `adr/` that the work relies on or contradicts.
+5. When the repository has `openspec/`: the main specs under `openspec/specs` that relate to the task, and the artifacts of active changes under `openspec/changes`.
+
+Paths that were already changed before the latest request belong to unfinished work of the user or another agent. Do not review them and do not block on them unless the candidate touched them within this request.
+
+Report only concrete, material problems the main agent can fix. Do not block on personal preferences, speculation or unrelated changes. Report only violations of a rule written in a document you read. If the result is acceptable, return `ok: true` with an empty `reason`. Otherwise return `ok: false` and a short reason: which files, plan sections or response passages are affected, which document is violated, and what to fix. Write the reason in English.
diff --git a/.agent-hooks/diff-prompt.md b/.agent-hooks/diff-prompt.md
new file mode 100644
index 00000000..13184b10
--- /dev/null
+++ b/.agent-hooks/diff-prompt.md
@@ -0,0 +1,15 @@
+## Diff review
+
+The candidate is the agent's final response, and the change is the working tree diff.
+
+Use `git status` and the full `git diff HEAD` including staged changes, and read new untracked files directly.
+
+- Check that the diff is focused, technically sound, complete, and matches the latest user request and the accepted plan, if there was one.
+- Look for bugs: wrong behavior, missed edge cases, broken error handling, races, resource leaks, security problems.
+- Check the material claims of the candidate's response against the repository, including claims that tests and linters ran and passed. A claim that cannot be true for this diff is a problem.
+- Check tests against the testing rules of the module docs: new behavior has a test at the level the module doc prefers, test names describe the scenario, and test data is cleaned up.
+- Check that code, comments, log messages, API strings and documentation are in English, except the places "Language in code" in `AGENTS.md` lists.
+- Check documentation consistency per the section "Documentation consistency" in `AGENTS.md`: if the change touches a command, rule, path or order of steps that `AGENTS.md`, the module docs, `adr/`, `docs/`, the repository's own skills or a README describe, those places are updated too. Search the repository for mentions of what changed. `openspec/` is outside this check.
+- Check edits to agent instructions per the same section. If an edit adds to `AGENTS.md` or an own skill an inventory of what exists, the state of the code, a description of how something works or a retelling of another document, return `ok: false` and name the place to move it to from that section's table. Do not block an edit that adds or changes a rule of agent behavior under this point.
+- Apply the humanizer rules to all prose in the diff and in the candidate's response.
+- Architecture and names are checked by separate reviewers. Do not duplicate them.
diff --git a/.agent-hooks/implementation-prompt.md b/.agent-hooks/implementation-prompt.md
new file mode 100644
index 00000000..b5bd2638
--- /dev/null
+++ b/.agent-hooks/implementation-prompt.md
@@ -0,0 +1,37 @@
+## Full implementation review
+
+The candidate is the implementation of an OpenSpec change whose tasks in `tasks.md` are all checked. Read the change's `proposal.md`, `design.md`, `tasks.md` and delta specs. The hook already ran the linters of the touched modules, and the hook tests when the hooks changed, and they passed. The hook does not run the Go test suites: check the agent's claims about tests against the repository.
+
+An implementation usually spans several requests, so the shared rule about paths changed before the latest request does not apply here: review everything that belongs to the change. Part of the implementation may already be committed; find it with `git log` and `git show` over the paths from the specs and `design.md`. Do not review edits unrelated to the change.
+
+This review answers with a `findings` list instead of the `ok` and `reason` from the shared instructions. Every finding has a category, a path and a description:
+
+- `bug`: wrong behavior, a race between a check and a write, a transaction error, secrets or personal data in logs or error texts, a wrong response code;
+- `spec_mismatch`: the code differs from a requirement, a scenario or a decision in `design.md`;
+- `missing_test`: a scenario has no test, or the test passes without the described behavior;
+- `docs`: a task is not fully done, documentation disagrees with the code or with other documents, or an edit to agent instructions breaks the section "Documentation consistency" in `AGENTS.md`;
+- `minor`: a detail that does not stop the change from being accepted.
+
+In `file` write the path and, if you can, the line: `path:line`. In `summary` describe the problem and the fix in English. Return only problems, without retelling what is fine. If there are no problems, return an empty list.
+
+### Role: delta spec
+
+Review only the requirements of your delta spec.
+
+- For every requirement and scenario find the code and the test: the file and the test name. Check that the test proves the scenario rather than passing by accident.
+- Check the decisions in `design.md` that relate to these requirements against the code.
+- Look for bugs in the code that implements the requirements.
+
+### Role: documentation and tasks
+
+- For every task in `tasks.md` check that everything it says was done, including its verification. A claim that cannot be true for this code is a problem.
+- Check documentation consistency per the section "Documentation consistency" in `AGENTS.md`: `AGENTS.md`, the module docs, `adr/`, `docs/`, the repository's own skills, the READMEs and code comments agree with each other and with the code. Search the repository for mentions of what the change changed.
+- Check the edits to agent instructions the change made, per the same section. Report an inventory of what exists, the state of the code, a description of how something works or a retelling of another document in `AGENTS.md` or an own skill as a `docs` finding, and name the place to move it to from that section's table. A rule of agent behavior that is written nowhere else is not a finding.
+
+### Role: repeat review
+
+The previous review of this change blocked the turn, and the agent fixed the findings. The previous findings and the paths changed after the previous review are passed below.
+
+- For every previous finding, check that it is fixed or that the agent rejected it with a sound reason in the response. Return an unfixed finding without such a reason again.
+- Check that the edits after the previous review broke nothing.
+- Do not review the whole change again.
diff --git a/.agent-hooks/implementation-result.schema.json b/.agent-hooks/implementation-result.schema.json
new file mode 100644
index 00000000..97d9a53b
--- /dev/null
+++ b/.agent-hooks/implementation-result.schema.json
@@ -0,0 +1,27 @@
+{
+ "type": "object",
+ "properties": {
+ "findings": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "category": {
+ "type": "string",
+ "enum": ["bug", "spec_mismatch", "missing_test", "docs", "minor"]
+ },
+ "file": {
+ "type": "string"
+ },
+ "summary": {
+ "type": "string"
+ }
+ },
+ "required": ["category", "file", "summary"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "required": ["findings"],
+ "additionalProperties": false
+}
diff --git a/.agent-hooks/naming-prompt.md b/.agent-hooks/naming-prompt.md
new file mode 100644
index 00000000..3e2cd473
--- /dev/null
+++ b/.agent-hooks/naming-prompt.md
@@ -0,0 +1,14 @@
+## Naming review
+
+The candidate is the agent's final response, and the change is the working tree diff. Use `git status` and the full `git diff HEAD` including staged changes, and read new untracked files directly.
+
+The standard for this review:
+
+- the sections "Naming" and "Functions, methods and types" of the root `AGENTS.md`;
+- the naming rules of the module doc for each changed area, including test naming.
+
+The rules and the bad/good examples live in those documents. Compare names against them, not against your own taste.
+
+Check only names the diff added or changed: functions and methods, types, variables and fields, constants, props, files. Do not check a name the diff did not touch, even if it sits in a changed function or next to an edit.
+
+Do not check architecture, correctness, tests or prose. Other reviewers do that. In the reason name the file, the name and the rule it breaks, and suggest a name that follows the rule.
diff --git a/.agent-hooks/necessity-prompt.md b/.agent-hooks/necessity-prompt.md
new file mode 100644
index 00000000..a6e4277e
--- /dev/null
+++ b/.agent-hooks/necessity-prompt.md
@@ -0,0 +1,12 @@
+## Necessity review
+
+The candidate is a plan or an OpenSpec proposal the user has not seen yet. Whether the solution is correct is not checked here. Check whether the task should be done in this form. The standard is the section "The best code is unwritten" in `AGENTS.md`.
+
+If the candidate is an OpenSpec proposal, read the change's artifacts under `openspec/changes`, first of all `proposal.md` and `design.md`.
+
+- Product: which user need the task covers. Check whether an existing feature, a manual process or an external service already covers it, and whether a much smaller option covers the same need.
+- Code: search the repository and its dependencies for something that already does what is needed, or nearly. Check whether a small refactoring with reuse replaces the new code, table, endpoint, package or dependency.
+- If such an option exists and the candidate silently bypasses it, return `ok: false`. In the reason name the option, explain what makes it simpler and what is lost with it, and point to where it lives in the repository. The candidate passes if it shows the user this option with its pros and cons, or explains why the option does not fit.
+- Do not demand dropping the task: the user decides. Do not suggest again an option the user already rejected in the request.
+- Count only a noticeably simpler option: less code, fewer entities, screens or maintenance. The option must be verified against the repository. Small simplifications and guesses do not count.
+- Plan correctness, prose and architecture are checked by other reviewers.
diff --git a/.agent-hooks/plan-prompt.md b/.agent-hooks/plan-prompt.md
new file mode 100644
index 00000000..bb4fe80b
--- /dev/null
+++ b/.agent-hooks/plan-prompt.md
@@ -0,0 +1,11 @@
+## Plan review
+
+The candidate is a plan the user has not seen yet.
+
+- Check that the plan solves what the latest user request actually asks, at the right layer and scope. The plan drops no requirement from the request.
+- Check that the names, file placement and behavior the plan proposes follow `AGENTS.md` and the module docs.
+- Reject a plan that keeps backward compatibility the user did not ask for, treats a symptom and leaves the cause, or misses a clearly more complete approach.
+- Whether the task is needed and whether a much simpler option exists is checked by a separate reviewer.
+- Reject implementation work done in a mode that only allowed planning.
+- Apply the humanizer rules to the plan's prose.
+- Architecture is checked by a separate reviewer. Mention architecture only when a violation breaks the request itself.
diff --git a/.agent-hooks/proposal-prompt.md b/.agent-hooks/proposal-prompt.md
new file mode 100644
index 00000000..e3134c3a
--- /dev/null
+++ b/.agent-hooks/proposal-prompt.md
@@ -0,0 +1,46 @@
+## Full proposal review
+
+The candidate is an OpenSpec proposal whose artifacts are all written and none of whose tasks in `tasks.md` is checked. No code exists for it yet. Read the change's `proposal.md`, `design.md`, `tasks.md` and delta specs, and the main specs under `openspec/specs` the change touches. The hook already ran `openspec validate --strict`, and it passed.
+
+A proposal is often written over several requests, so the shared rule about paths changed before the latest request does not apply here: review every artifact of the change. Do not review other files in the working tree.
+
+This review answers with a `findings` list instead of the `ok` and `reason` from the shared instructions. Every finding has a category, a path and a description:
+
+- `gap`: a requirement is incomplete or cannot be verified, a case is missing, a scenario does not say what exactly is observed;
+- `mismatch`: the artifacts contradict each other, the main specs, the code, the architecture rules of the module docs or an accepted ADR; the design relies on a function, table or file that does not exist in the repository or works differently;
+- `tasks`: a scenario is not covered by a task with a test, a task has no verification, the task order cannot be followed;
+- `simplify`: the same result for the user is reachable noticeably more simply, and the user loses nothing;
+- `scope`: an option where the user loses a feature, screen, scenario or setting, in exchange for saving a noticeable part of the work;
+- `minor`: a detail that does not stop the proposal from being accepted.
+
+What the user gets decides between `simplify` and `scope`. If the user loses a feature, screen, scenario or setting, it is `scope`, even when the option looks clearly better. Otherwise it is `simplify`.
+
+In `file` write the path and, if you can, the line: `path:line`. In `summary` describe the problem and the fix in English. For `simplify` and `scope` name the option and where it lives in the repository; for `scope` also what the user loses and what is saved. Return only problems, without retelling what is fine. If there are no problems, return an empty list.
+
+### Role: delta spec
+
+Review only the requirements of your delta spec.
+
+- Every requirement is complete and testable: it is clear who acts, under which condition, and what is observed.
+- Requirements do not contradict the main specs, `proposal.md` or `design.md`.
+- Claims about existing code, tables, commands and files are true. Check them against the repository.
+
+### Role: proposal and design
+
+- Look for a way to reach the same result noticeably more simply, per the section "The best code is unwritten" in `AGENTS.md`: something that already exists in the repository or its dependencies, a small refactoring instead of new code, a narrower option.
+- Check the decisions in `design.md` against the architecture rules of the module docs and the accepted ADRs in `adr/`.
+- Check that the decisions agree with each other and with `proposal.md`, and that the facts about the code are true.
+
+### Role: tasks
+
+- Check that every scenario of the delta specs is covered by a task with a test.
+- Check that every task has a verification: a test, a command or a repository search.
+- Check that the task order can be followed: no task relies on something that appears only in a later one.
+
+### Role: repeat review
+
+The previous review of this proposal blocked the turn, and the agent fixed the findings. The previous findings and the change's files that changed after the previous review are passed below.
+
+- For every previous finding except `scope` and `minor`, check that it is fixed or that the agent rejected it with a sound reason in the response. Return an unfixed finding without such a reason again.
+- Check that the edits after the previous review introduced no new contradictions.
+- Do not review the whole proposal again.
diff --git a/.agent-hooks/proposal-result.schema.json b/.agent-hooks/proposal-result.schema.json
new file mode 100644
index 00000000..99adef2d
--- /dev/null
+++ b/.agent-hooks/proposal-result.schema.json
@@ -0,0 +1,27 @@
+{
+ "type": "object",
+ "properties": {
+ "findings": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "category": {
+ "type": "string",
+ "enum": ["gap", "mismatch", "tasks", "simplify", "scope", "minor"]
+ },
+ "file": {
+ "type": "string"
+ },
+ "summary": {
+ "type": "string"
+ }
+ },
+ "required": ["category", "file", "summary"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "required": ["findings"],
+ "additionalProperties": false
+}
diff --git a/.agent-hooks/review-prompt.md b/.agent-hooks/review-prompt.md
deleted file mode 100644
index ec163b33..00000000
--- a/.agent-hooks/review-prompt.md
+++ /dev/null
@@ -1,28 +0,0 @@
-You are the final review gate for an AI coding agent working in the Databasus repository. Inspect the repository with read-only tools and decide whether the candidate result can be accepted.
-
-Read these files completely before judging the result:
-
-1. `.claude/agents/reviewer.md` — its steps 1–3 define how to resolve scope, which docs govern which paths, and the rules violated most often. Apply them. Ignore its step 4 (linting) and step 5 (report format); this gate reports through the JSON schema instead.
-2. `.agents/skills/humanizer/SKILL.md`
-3. `AGENTS.md`
-4. Every module `AGENTS.md` that governs a path in scope, as mapped in `.claude/agents/reviewer.md`
-5. Relevant main specifications under `openspec/specs`
-6. Relevant active change artifacts under `openspec/changes`, including `proposal.md`, `design.md`, delta specs, and `tasks.md`
-
-Use `git status` and the complete diff against `HEAD`, and read untracked files directly. Do not edit files.
-
-For a plan review, the candidate is a plan that has not been shown to the user yet. Check that it solves what the latest user request actually asks, at the right layer and scope, and that the names, file placement and behavior it proposes follow the governing docs. Reject a plan that preserves backward compatibility the user did not ask for.
-
-For a planning review, check the candidate response and planning artifacts against the latest user request, existing specifications, and each other. The proposal, design, delta specs, and tasks must describe one coherent change. Reject implementation work performed during a planning-only workflow.
-
-For an implementation review, check whether the diff is focused, technically sound, complete, and consistent with the accepted plan and specifications. When there is no plan or OpenSpec change, judge the diff against the latest user request alone. Verify material claims in the candidate response against the repository, including claims that tests and linters ran and passed.
-
-In plan and implementation reviews alike, judge the approach, not only its execution. Reject a result that removes a symptom the user happened to see while leaving the root cause they asked about. Also reject one that works at the wrong layer or scope, or misses a case or a break it should have flagged, and one where a clearly simpler or more complete approach exists.
-
-In every mode, apply the humanizer rules to every piece of prose intended for the user or the repository.
-
-When implementation or an accepted plan clearly captures the latest explicit user intent but OpenSpec is stale, return `ok: false` and tell the main agent which specification or change artifacts to update. Do not ask the user to approve an obvious synchronization fix. When the evidence does not show that the specification is stale, require the result to follow the specification.
-
-Paths that already had changes before the latest request belong to the user's own unfinished work. Do not review or block on them unless the candidate touched them for this request.
-
-Report only concrete, material problems that the main agent can fix. Do not block on personal preferences, speculative concerns, or unrelated pre-existing changes. If the result is acceptable, return `ok: true` with an empty reason. Otherwise return `ok: false` and a concise reason that names the affected files, plan sections or response passages, the governing doc, and the required correction.
diff --git a/.agent-hooks/review_gate.py b/.agent-hooks/review_gate.py
index 7674ea90..2d58417e 100755
--- a/.agent-hooks/review_gate.py
+++ b/.agent-hooks/review_gate.py
@@ -1,15 +1,36 @@
#!/usr/bin/env python3
-"""Review gate shared by the Claude Code and Codex hooks.
+"""Review hooks for Claude Code and Codex, wired in .claude/settings.json and .codex/hooks.json.
-Actions:
- snapshot UserPromptSubmit: remember the request and the working tree it started from.
- plan-gate Claude PreToolUse on ExitPlanMode: review the plan before the user sees it.
- claude Claude Stop: review the finished turn.
- codex Codex Stop: review the finished turn.
+Usage: review_gate.py <action> --client <claude|codex>
-Every review runs a separate read-only Claude process. A failed review is never accepted.
+Actions:
+ session-start SessionStart: tells the agent to load the communication skill in a fresh context.
+ snapshot UserPromptSubmit: remembers the request and the working tree it started from.
+ plan Reviews a plan before the user sees it.
+ necessity Checks a plan or an OpenSpec proposal: is the task needed, is there a much simpler option.
+ diff Reviews a finished change.
+ architecture Checks a plan or a change against the architecture rules of the module docs and the ADRs.
+ naming Checks names in code the request changed against the naming rules of AGENTS.md
+ and the module docs. Runs when a .go, .ts or .tsx file under backend/, agent/,
+ frontend/src/ or website/ changed.
+ implementation Full review of an OpenSpec change whose tasks are all checked: first the read-only
+ checks of the touched modules, then parallel reviewers by spec and for documentation,
+ after a block a repeat over the previous findings only.
+ proposal Full review of a finished OpenSpec proposal with no checked task: first
+ openspec validate --strict, then parallel reviewers by spec, for proposal and design
+ and for tasks. While it runs, necessity, diff, architecture and naming skip a turn
+ that only wrote the artifacts.
+
+Every review runs a separate read-only process of the same agent.
+The review prompt lives in .agent-hooks/<action>-prompt.md, the shared part in common-prompt.md:
+they say what the reviewer reads and checks.
+A review that could not run never accepts the result.
"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+from collections.abc import Callable
+from dataclasses import dataclass, replace
import hashlib
import json
import os
@@ -17,20 +38,95 @@ from pathlib import Path
import re
import subprocess
import sys
+import tempfile
AUTOMATIC_REVIEW_PREFIX = "AUTOMATIC REVIEW:"
MAX_REVISIONS = 3
-REVIEW_TIMEOUT_SECONDS = 540
-REVIEWER_MODEL = "claude-opus-5"
-REVIEWER_EFFORT = "low"
+MAX_FULL_REVIEW_REVISIONS = 2
+MAX_PARALLEL_REVIEWERS = 6
+CHECK_TIMEOUT_SECONDS = 900
+CHECK_OUTPUT_LINES = 80
+OPENSPEC_TIMEOUT_SECONDS = 60
REVIEWER_ACTIVE_ENV = "AGENT_REVIEW_HOOK_ACTIVE"
-EXPLICIT_PLANNING_COMMANDS = (
+HOOKS_DIR = Path(__file__).resolve().parent
+GATES = ("plan", "necessity", "diff", "architecture", "naming", "implementation", "proposal")
+GATES_YIELDING_TO_PROPOSAL_REVIEW = ("necessity", "diff", "architecture", "naming")
+CODE_DIRS = ("backend/", "agent/", "frontend/src/", "website/")
+CODE_SUFFIXES = (".go", ".ts", ".tsx")
+TASK_PATTERN = re.compile(r"^\s*[-*] \[([ xX])\]", re.MULTILINE)
+
+
+@dataclass(frozen=True)
+class Reviewer:
+ claude_model: str
+ claude_effort: str
+ codex_model: str
+ codex_effort: str
+ schema_path: Path
+ timeout_seconds: int
+
+
+# The strongest model plans and writes code, and the reviewer runs one step below at low effort:
+# smart enough to check and quick to answer. The full proposal and implementation reviews run
+# once per change and look for what the quick checks miss, so their effort is higher.
+QUICK_REVIEWER = Reviewer(
+ claude_model="opus",
+ claude_effort="low",
+ codex_model="gpt-6.1-sol",
+ codex_effort="low",
+ schema_path=HOOKS_DIR / "review-result.schema.json",
+ timeout_seconds=540,
+)
+IMPLEMENTATION_REVIEWER = Reviewer(
+ claude_model="opus",
+ claude_effort="medium",
+ codex_model="gpt-6.1-sol",
+ codex_effort="high",
+ schema_path=HOOKS_DIR / "implementation-result.schema.json",
+ timeout_seconds=1800,
+)
+PROPOSAL_REVIEWER = replace(IMPLEMENTATION_REVIEWER, schema_path=HOOKS_DIR / "proposal-result.schema.json")
+OPENSPEC_PLANNING_COMMANDS = (
"/opsx:propose",
"/opsx:update",
"$openspec-propose",
"$openspec-update-change",
)
+PLANNING_COMMANDS = (*OPENSPEC_PLANNING_COMMANDS, "/plan")
+HUMANIZER_CONTEXT = (
+ "Mandatory first step: load the communication skill (.agents/skills/humanizer/SKILL.md) "
+ "before any other action and apply it to all prose you write. "
+ "Project rules: AGENTS.md."
+)
+
+
+@dataclass(frozen=True)
+class Check:
+ directory: str
+ arguments: tuple
+
+
+# The hook only runs checks that leave files untouched: `make lint` starts with
+# `golangci-lint fmt` and would rewrite files a parallel agent is editing.
+# `make test` resets the test containers other agents share, so it never runs here.
+MODULE_CHECKS = (
+ ("backend/", (Check("backend", ("golangci-lint", "run", "./cmd/...", "./internal/...")),)),
+ (
+ "agent/",
+ (Check("agent/verification", ("golangci-lint", "run", "./cmd/...", "./internal/...", "./e2e/...")),),
+ ),
+ ("frontend/", (Check(".", ("pnpm", "--dir", "frontend", "lint")),)),
+ (
+ "website/",
+ (
+ Check(".", ("npm", "--prefix", "website", "run", "lint")),
+ Check(".", ("npm", "--prefix", "website", "run", "build")),
+ ),
+ ),
+ # Under test PATH holds stubs, so the hook tests run on this interpreter rather than python3 from PATH.
+ (".agent-hooks/", (Check(".", (sys.executable, "-m", "unittest", "discover", "-s", ".agent-hooks", "-p", "*_test.py")),)),
+)
def read_payload():
@@ -41,6 +137,14 @@ def read_payload():
return value if isinstance(value, dict) else {}
+def get_field(payload, *names):
+ for name in names:
+ value = payload.get(name)
+ if value not in (None, ""):
+ return value
+ return None
+
+
def emit(value):
json.dump(value, sys.stdout, ensure_ascii=False)
sys.stdout.write("\n")
@@ -57,11 +161,11 @@ def run_git(root, *args):
def find_root(payload):
- cwd = Path(payload.get("cwd") or Path.cwd()).resolve()
+ cwd = Path(get_field(payload, "workspaceRoot", "cwd") or Path.cwd()).resolve()
try:
return Path(run_git(cwd, "rev-parse", "--show-toplevel").decode().strip())
except (OSError, subprocess.CalledProcessError):
- return Path(__file__).resolve().parent.parent
+ return HOOKS_DIR.parent
def get_untracked_paths(root):
@@ -76,9 +180,9 @@ def get_changed_paths(root):
paths = set(get_untracked_paths(root))
try:
output = run_git(root, "diff", "--name-only", "-z", "HEAD", "--")
- paths.update(path for path in output.decode(errors="replace").split("\0") if path)
except (OSError, subprocess.CalledProcessError):
- pass
+ output = run_git(root, "diff", "--name-only", "-z", "--cached", "--")
+ paths.update(path for path in output.decode(errors="replace").split("\0") if path)
return sorted(paths)
@@ -93,29 +197,32 @@ def get_workspace_fingerprint(root):
for relative_path in get_untracked_paths(root):
path = root / relative_path
+ digest.update(relative_path.encode())
if path.is_symlink():
- digest.update(relative_path.encode())
digest.update(os.readlink(path).encode())
continue
if not path.is_file():
continue
- digest.update(relative_path.encode())
try:
with path.open("rb") as source:
- while chunk := source.read(1024 * 1024):
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
except OSError:
digest.update(b"unreadable")
return digest.hexdigest()
-def get_state_path(root, payload):
- session_id = re.sub(r"[^A-Za-z0-9_.-]", "_", str(payload.get("session_id") or "unknown"))
+def get_state_dir(root):
try:
git_dir = Path(run_git(root, "rev-parse", "--absolute-git-dir").decode().strip())
except (OSError, subprocess.CalledProcessError):
git_dir = root / ".git"
- return git_dir / "agent-review-hooks" / f"{session_id}.json"
+ return git_dir / "agent-review-hooks"
+
+
+def get_session_key(payload):
+ session_id = get_field(payload, "session_id", "sessionId") or "unknown"
+ return re.sub(r"[^A-Za-z0-9_.-]", "_", str(session_id))
def load_state(path):
@@ -133,54 +240,148 @@ def save_state(path, state):
temporary.replace(path)
-def snapshot(payload, root, state_path):
- prompt = str(payload.get("prompt") or "")
- if prompt.startswith(AUTOMATIC_REVIEW_PREFIX) and load_state(state_path):
+class Session:
+ def __init__(self, root, payload):
+ self.root = root
+ self.payload = payload
+ self.state_dir = get_state_dir(root)
+ self.key = get_session_key(payload)
+
+ @property
+ def request_path(self):
+ return self.state_dir / f"{self.key}.json"
+
+ def gate_path(self, gate):
+ return self.state_dir / f"{self.key}.{gate}.json"
+
+ def load_request(self):
+ return load_state(self.request_path)
+
+
+def start_session():
+ emit(
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "SessionStart",
+ "additionalContext": HUMANIZER_CONTEXT,
+ }
+ }
+ )
+
+
+def snapshot(session):
+ prompt = str(get_field(session.payload, "prompt", "userPrompt") or "")
+ if prompt.startswith(AUTOMATIC_REVIEW_PREFIX) and session.load_request():
return
+
+ baseline_paths = get_changed_paths(session.root)
save_state(
- state_path,
+ session.request_path,
{
- "baseline": get_workspace_fingerprint(root),
- "baseline_paths": get_changed_paths(root),
- "blocks": 0,
- "plan_blocks": 0,
- "is_accepted": False,
+ "baseline": get_workspace_fingerprint(session.root),
+ "baseline_paths": baseline_paths,
+ "baseline_files": get_file_hashes(session.root, baseline_paths),
+ "openspec_files": get_openspec_file_hashes(session.root),
"prompt": prompt,
},
)
+ for gate in GATES:
+ try:
+ session.gate_path(gate).unlink()
+ except FileNotFoundError:
+ pass
+
+
+def has_command(request, commands):
+ prompt = str(request.get("prompt") or "").lower()
+ return any(command in prompt for command in commands)
+
+
+def is_planning(payload, request):
+ if get_field(payload, "permission_mode", "permissionMode") == "plan":
+ return True
+ return has_command(request, PLANNING_COMMANDS)
+
+
+def get_active_changes(root):
+ changes_dir = root / "openspec" / "changes"
+ if not changes_dir.is_dir():
+ return []
+ return sorted(path for path in changes_dir.iterdir() if path.is_dir() and path.name != "archive")
+
+
+def get_change_state_path(root, gate, change_name):
+ return get_state_dir(root) / gate / f"{change_name}.json"
+
+def get_changes_with_findings(root):
+ return {
+ change_dir.name
+ for change_dir in get_active_changes(root)
+ if load_state(get_change_state_path(root, "implementation", change_dir.name)).get("findings")
+ }
-def is_planning_request(prompt):
- lowered = prompt.lower()
- return any(command in lowered for command in EXPLICIT_PLANNING_COMMANDS)
+def get_openspec_proposal_hashes(root, excluded_changes=frozenset()):
+ hashes = {}
+ for change_dir in get_active_changes(root):
+ if change_dir.name in excluded_changes:
+ continue
+
+ # tasks.md is left out: implementing the change also checks its tasks.
+ paths = [change_dir / "proposal.md", change_dir / "design.md", *change_dir.glob("specs/**/*.md")]
+ for path in paths:
+ try:
+ hashes[str(path.relative_to(root))] = hashlib.sha256(path.read_bytes()).hexdigest()
+ except OSError:
+ continue
+ return hashes
+
+
+# The agent may write an OpenSpec proposal without a command in the request, for example
+# after "write this up as a spec", so the turn is also recognized by changed artifacts.
+# Edits to a change that has unaccepted full review findings follow those findings
+# and do not count as a new proposal.
+def is_openspec_planning(request, root):
+ if has_command(request, OPENSPEC_PLANNING_COMMANDS):
+ return True
-def get_stop_review_mode(payload, state, paths):
- if payload.get("permission_mode") == "plan":
- return "planning"
+ baseline = request.get("openspec_files")
+ if not isinstance(baseline, dict):
+ return False
- if is_planning_request(str(state.get("prompt") or "")):
- return "planning"
+ current = get_openspec_proposal_hashes(root, get_changes_with_findings(root))
+ return any(baseline.get(path) != digest for path, digest in current.items())
- new_paths = set(paths) - set(state.get("baseline_paths") or [])
- if new_paths and all(path.startswith("openspec/") for path in new_paths):
- return "planning"
- return "implementation"
+
+def read_plan(tool_input):
+ plan = str(tool_input.get("plan") or "").strip()
+ if plan:
+ return plan
+ try:
+ return Path(str(tool_input.get("planFilePath") or "")).read_text().strip()
+ except OSError:
+ return ""
-def build_review_prompt(root, state, mode, candidate, paths):
- instructions = (Path(__file__).parent / "review-prompt.md").read_text()
- original_prompt = str(state.get("prompt") or "(not captured)")
- path_list = "\n".join(f"- {path}" for path in paths) or "- none"
- baseline_path_list = "\n".join(f"- {path}" for path in state.get("baseline_paths") or []) or "- none"
+def build_review_prompt(session, gate, subject, candidate, paths):
+ request = session.load_request()
+ instructions = "\n\n".join(
+ [
+ (HOOKS_DIR / "common-prompt.md").read_text(),
+ (HOOKS_DIR / f"{gate}-prompt.md").read_text(),
+ ]
+ )
+ baseline_paths = "\n".join(f"- {path}" for path in request.get("baseline_paths") or []) or "- none"
+ changed_paths = "\n".join(f"- {path}" for path in paths) or "- none"
return f"""{instructions}
-Review mode: {mode}
-Repository root: {root}
+Under review: {subject}
+Repository root: {session.root}
Latest user request:
<user_request>
-{original_prompt}
+{request.get("prompt") or "(not captured)"}
</user_request>
Candidate:
@@ -188,59 +389,105 @@ Candidate:
{candidate}
</candidate>
-Paths that already had changes before this request:
-{baseline_path_list}
+Paths changed before this request:
+{baseline_paths}
Currently changed paths:
-{path_list}
+{changed_paths}
"""
-def parse_review_result(text):
+def load_reviewer_output(text):
value = json.loads(text)
if isinstance(value, dict) and isinstance(value.get("structured_output"), dict):
value = value["structured_output"]
if not isinstance(value, dict):
- raise ValueError("reviewer returned a non-object result")
+ raise ValueError("the reviewer returned a non-object result")
+ return value
+
+
+def parse_review_result(value):
if not isinstance(value.get("ok"), bool) or not isinstance(value.get("reason"), str):
- raise ValueError("reviewer result does not match the required schema")
+ raise ValueError("the reviewer result does not match the schema")
return value
-def run_reviewer(root, prompt):
- schema = (Path(__file__).parent / "review-result.schema.json").read_text()
+def get_reviewer_environment():
+ environment = os.environ.copy()
+ environment[REVIEWER_ACTIVE_ENV] = "1"
+ for name in ("CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID"):
+ environment.pop(name, None)
+ return environment
+
+
+def run_codex_reviewer(root, prompt, model, effort, schema_path, timeout_seconds):
+ with tempfile.TemporaryDirectory(prefix="codex-review-") as temporary_dir:
+ output_path = Path(temporary_dir) / "result.json"
+ command = [
+ "codex",
+ "exec",
+ "--ephemeral",
+ "--disable",
+ "hooks",
+ "--model",
+ model,
+ "--config",
+ f'model_reasoning_effort="{effort}"',
+ "--sandbox",
+ "read-only",
+ "--cd",
+ str(root),
+ "--output-schema",
+ str(schema_path),
+ "--output-last-message",
+ str(output_path),
+ "--color",
+ "never",
+ "-",
+ ]
+ process = subprocess.run(
+ command,
+ input=prompt,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=get_reviewer_environment(),
+ timeout=timeout_seconds,
+ )
+ if process.returncode != 0:
+ raise RuntimeError(process.stderr.strip() or f"codex exited with code {process.returncode}")
+ return load_reviewer_output(output_path.read_text())
+
+
+def run_claude_reviewer(root, prompt, model, effort, schema_path, timeout_seconds):
command = [
"claude",
"--print",
"--model",
- REVIEWER_MODEL,
+ model,
"--effort",
- REVIEWER_EFFORT,
+ effort,
"--permission-mode",
"plan",
- # The reviewer loads this repository's hooks too; its own stop must never be gated.
+ # The reviewer loads this repository's hooks too, and its own turn must never be gated.
"--settings",
'{"disableAllHooks": true}',
"--tools",
"Read,Glob,Grep,Bash",
"--allowed-tools",
- "Read,Glob,Grep,Bash(git status *),Bash(git diff *),Bash(git log *),Bash(git show *),Bash(git ls-files *),Bash(git rev-parse *)",
- "--max-turns",
- "30",
+ "Read,Glob,Grep,Bash(git status *),Bash(git diff *),Bash(git log *),Bash(git show *),"
+ "Bash(git ls-files *),Bash(git rev-parse *)",
"--no-session-persistence",
"--prompt-suggestions",
"false",
"--output-format",
"json",
"--json-schema",
- schema,
+ schema_path.read_text(),
]
- environment = os.environ.copy()
- environment[REVIEWER_ACTIVE_ENV] = "1"
- environment.pop("CLAUDECODE", None)
- environment.pop("CLAUDE_CODE_SESSION_ID", None)
- environment.pop("CODEX_SESSION_ID", None)
- environment.pop("CODEX_THREAD_ID", None)
+ environment = get_reviewer_environment()
+ environment["CLAUDE_CODE_EFFORT_LEVEL"] = effort
+
process = subprocess.run(
command,
cwd=root,
@@ -249,146 +496,607 @@ def run_reviewer(root, prompt):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=environment,
- timeout=REVIEW_TIMEOUT_SECONDS,
+ timeout=timeout_seconds,
)
if process.returncode != 0:
- raise RuntimeError(process.stderr.strip() or process.stdout.strip() or f"claude exited with {process.returncode}")
- return parse_review_result(process.stdout)
+ raise RuntimeError(process.stderr.strip() or process.stdout.strip() or f"claude exited with code {process.returncode}")
+ return load_reviewer_output(process.stdout)
+
+def run_reviewer(root, prompt, client, reviewer):
+ if client == "codex":
+ return run_codex_reviewer(
+ root, prompt, reviewer.codex_model, reviewer.codex_effort, reviewer.schema_path, reviewer.timeout_seconds
+ )
+ return run_claude_reviewer(
+ root, prompt, reviewer.claude_model, reviewer.claude_effort, reviewer.schema_path, reviewer.timeout_seconds
+ )
+
+
+def describe_reviewer_error(error):
+ message = str(error).strip()[-1200:] or "unknown reviewer error"
+ return f"The automatic reviewer could not run: {message}"
-def review(root, prompt):
- """Returns (is_accepted, reason). A reviewer that could not run never accepts."""
+
+def review(root, prompt, client):
try:
- result = run_reviewer(root, prompt)
+ result = parse_review_result(run_reviewer(root, prompt, client, QUICK_REVIEWER))
except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as error:
- message = str(error).strip()[-1200:] or "unknown reviewer error"
- return False, f"The automatic reviewer could not run: {message}"
+ return False, describe_reviewer_error(error)
if result["ok"]:
return True, ""
return False, result["reason"].strip() or "The reviewer rejected the result without a reason."
-def read_plan(tool_input):
- plan = str(tool_input.get("plan") or "").strip()
- if plan:
- return plan
- try:
- return Path(str(tool_input.get("planFilePath") or "")).read_text().strip()
- except OSError:
- return ""
-
-
-def gate_plan(payload, root, state_path):
- state = load_state(state_path)
- plan = read_plan(payload.get("tool_input") or {})
+def gate_plan_tool(session, gate, client):
+ gate_path = session.gate_path(gate)
+ state = load_state(gate_path)
+ plan = read_plan(get_field(session.payload, "tool_input", "toolInput") or {})
if plan:
- prompt = build_review_prompt(root, state, "plan", plan, get_changed_paths(root))
- is_accepted, reason = review(root, prompt)
+ prompt = build_review_prompt(session, gate, "plan", plan, get_changed_paths(session.root))
+ is_accepted, reason = review(session.root, prompt, client)
else:
is_accepted, reason = False, "ExitPlanMode carried no plan text, so the plan could not be reviewed."
if is_accepted:
- state["plan_blocks"] = 0
- save_state(state_path, state)
+ save_state(gate_path, {"blocks": 0})
emit({})
return
- plan_blocks = int(state.get("plan_blocks") or 0) + 1
- state["plan_blocks"] = plan_blocks
- save_state(state_path, state)
- if plan_blocks > MAX_REVISIONS:
+ blocks = int(state.get("blocks") or 0) + 1
+ save_state(gate_path, {"blocks": blocks})
+ if blocks > MAX_REVISIONS:
emit(
{
"continue": False,
- "stopReason": f"Automatic plan review still fails after {MAX_REVISIONS} revisions: {reason}",
- "systemMessage": "Automatic plan review reached its revision limit. The plan was not accepted.",
+ "stopReason": f"Automatic plan review ({gate}) still fails after {MAX_REVISIONS} revisions: {reason}",
}
)
return
+
+ denial = f"{AUTOMATIC_REVIEW_PREFIX} {gate}\n{reason}\nRevise the plan and show it again."
emit(
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
- "permissionDecisionReason": f"{AUTOMATIC_REVIEW_PREFIX}\n{reason}\nRevise the plan and call ExitPlanMode again.",
+ "permissionDecisionReason": denial,
}
}
)
-def is_stop_review_needed(payload, state, fingerprint):
- if int(state.get("blocks") or 0) > 0:
- return True
-
- is_workspace_changed = state.get("baseline") != fingerprint
- # Another Stop hook can resume the turn; an accepted result it did not change needs no second review.
- if state.get("is_accepted") and not is_workspace_changed:
- return False
- # In plan mode the plan reaches the user through ExitPlanMode, which the plan gate reviews.
- if payload.get("permission_mode") == "plan":
- return is_workspace_changed
- return is_workspace_changed or is_planning_request(str(state.get("prompt") or ""))
+def get_stop_subject(
+ gate, client, is_plan_turn, is_openspec_turn, is_workspace_changed, blocks, is_code_changed=False
+):
+ # Claude shows a plan through ExitPlanMode, which has its own check. Codex has no such
+ # tool, and its plan reaches the user in the final message.
+ is_plan_in_message = is_plan_turn and client != "claude"
+
+ if gate == "naming":
+ return "finished change" if is_code_changed or blocks > 0 else None
+
+ if gate == "necessity":
+ if is_openspec_turn and is_workspace_changed:
+ return "OpenSpec proposal"
+ return "plan" if is_plan_in_message else None
+ if gate == "plan":
+ return "plan" if is_plan_in_message else None
+ if gate == "architecture" and is_plan_in_message:
+ return "plan"
+ if is_workspace_changed or blocks > 0:
+ return "finished change"
+ return None
+
+
+def gate_stop(session, gate, client):
+ request = session.load_request()
+ if gate in GATES_YIELDING_TO_PROPOSAL_REVIEW and is_proposal_review_turn(session.root, request):
+ emit({})
+ return
+ gate_path = session.gate_path(gate)
+ state = load_state(gate_path)
+ fingerprint = get_workspace_fingerprint(session.root)
+ blocks = int(state.get("blocks") or 0)
+ subject = get_stop_subject(
+ gate,
+ client,
+ is_planning(session.payload, request),
+ is_openspec_planning(request, session.root),
+ request.get("baseline") != fingerprint,
+ blocks,
+ gate == "naming" and is_code_changed_since_request(session.root, request),
+ )
-def gate_stop(client, payload, root, state_path):
- state = load_state(state_path)
- fingerprint = get_workspace_fingerprint(root)
- if not is_stop_review_needed(payload, state, fingerprint):
+ if subject is None or (state.get("accepted") == fingerprint and blocks == 0):
emit({})
return
- paths = get_changed_paths(root)
- mode = get_stop_review_mode(payload, state, paths)
- candidate = str(payload.get("last_assistant_message") or "(not available)")
- prompt = build_review_prompt(root, state, mode, candidate, paths)
- is_accepted, reason = review(root, prompt)
+ candidate = str(get_field(session.payload, "last_assistant_message", "lastAssistantMessage") or "(not available)")
+ prompt = build_review_prompt(session, gate, subject, candidate, get_changed_paths(session.root))
+ is_accepted, reason = review(session.root, prompt, client)
if is_accepted:
- state.update({"baseline": fingerprint, "blocks": 0, "is_accepted": True})
- save_state(state_path, state)
+ save_state(gate_path, {"blocks": 0, "accepted": fingerprint})
emit({})
return
- blocks = int(state.get("blocks") or 0) + 1
- state["blocks"] = blocks
- save_state(state_path, state)
+ blocks += 1
+ save_state(gate_path, {"blocks": blocks})
if blocks > MAX_REVISIONS:
emit(
{
"continue": False,
- "stopReason": f"Automatic {client} review still fails after {MAX_REVISIONS} revisions: {reason}",
- "systemMessage": "Automatic review reached its revision limit. The result was not accepted.",
+ "stopReason": f"Automatic review ({gate}) still fails after {MAX_REVISIONS} revisions: {reason}",
+ "systemMessage": f"Automatic review ({gate}) reached its revision limit. The result was not accepted.",
}
)
return
- emit(
- {
- "decision": "block",
- "reason": f"{AUTOMATIC_REVIEW_PREFIX}\n{reason}\nFix the result, update OpenSpec when requested, and finish with another review.",
- }
+
+ feedback = f"{AUTOMATIC_REVIEW_PREFIX} {gate}\n{reason}\nFix the result and finish the turn again; the review will repeat."
+ emit({"decision": "block", "reason": feedback})
+
+
+def get_task_marks(change_dir):
+ try:
+ return TASK_PATTERN.findall((change_dir / "tasks.md").read_text())
+ except OSError:
+ return []
+
+
+def is_implemented(change_dir):
+ marks = get_task_marks(change_dir)
+ return bool(marks) and " " not in marks
+
+
+def is_unstarted(change_dir):
+ marks = get_task_marks(change_dir)
+ return bool(marks) and all(mark == " " for mark in marks)
+
+
+# The CLI decides whether the artifacts are complete: it knows the change's schema, an optional
+# design.md and skip_specs. Without the CLI the proposal review does not run, and the quick checks do.
+def is_planning_complete(root, change_name):
+ try:
+ process = subprocess.run(
+ ["openspec", "status", "--change", change_name, "--json"],
+ cwd=root,
+ text=True,
+ errors="replace",
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=OPENSPEC_TIMEOUT_SECONDS,
+ )
+ status = json.loads(process.stdout)
+ except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError):
+ return False
+ return process.returncode == 0 and isinstance(status, dict) and status.get("isPlanningComplete") is True
+
+
+def get_file_hashes(root, relative_paths):
+ hashes = {}
+ for relative_path in relative_paths:
+ try:
+ hashes[relative_path] = hashlib.sha256((root / relative_path).read_bytes()).hexdigest()
+ except OSError:
+ hashes[relative_path] = "missing"
+ return hashes
+
+
+def get_paths_changed_since(reviewed_files, current_files):
+ paths = set(reviewed_files) | set(current_files)
+ return sorted(path for path in paths if reviewed_files.get(path) != current_files.get(path))
+
+
+def get_change_file_hashes(root, change_dir):
+ paths = sorted(path for path in change_dir.rglob("*") if path.is_file())
+ return get_file_hashes(root, [str(path.relative_to(root)) for path in paths])
+
+
+def get_openspec_file_hashes(root):
+ hashes = {}
+ for change_dir in get_active_changes(root):
+ hashes.update(get_change_file_hashes(root, change_dir))
+ return hashes
+
+
+def is_code_path(path):
+ return path.startswith(CODE_DIRS) and path.endswith(CODE_SUFFIXES)
+
+
+# Changed code is found by file hashes, as in is_proposal_review_turn: someone else's changed
+# file that was already in the tree before the request does not start the naming reviewer.
+def is_code_changed_since_request(root, request):
+ current_files = get_file_hashes(root, get_changed_paths(root))
+ changed_paths = get_paths_changed_since(request.get("baseline_files") or {}, current_files)
+ return any(is_code_path(path) for path in changed_paths)
+
+
+# The conditions go from cheap to expensive: openspec status runs last.
+def is_proposal_review_turn(root, request):
+ current_files = get_file_hashes(root, get_changed_paths(root))
+ change_names = set()
+ for path in get_paths_changed_since(request.get("baseline_files") or {}, current_files):
+ parts = Path(path).parts
+ if len(parts) < 4 or parts[:2] != ("openspec", "changes") or parts[2] == "archive":
+ return False
+ change_names.add(parts[2])
+
+ changes_dir = root / "openspec" / "changes"
+ return bool(change_names) and all(
+ is_unstarted(changes_dir / name) and is_planning_complete(root, name) for name in sorted(change_names)
)
+def get_output_tail(output):
+ if isinstance(output, bytes):
+ output = output.decode(errors="replace")
+ return "\n".join((output or "").rstrip().splitlines()[-CHECK_OUTPUT_LINES:]) or "(no output)"
+
+
+def run_checks(root, checks):
+ for check in checks:
+ command = f"`{' '.join(check.arguments)}` in `{check.directory}`"
+ try:
+ process = subprocess.run(
+ list(check.arguments),
+ cwd=root / check.directory,
+ text=True,
+ errors="replace",
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ timeout=CHECK_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as error:
+ return f"{command} did not finish in {CHECK_TIMEOUT_SECONDS} seconds.\n\nEnd of output:\n{get_output_tail(error.output)}"
+ except OSError as error:
+ return f"{command} could not start: {error}"
+
+ if process.returncode != 0:
+ return f"{command} exited with code {process.returncode}.\n\nEnd of output:\n{get_output_tail(process.stdout)}"
+ return None
+
+
+def get_module_checks(root):
+ changed_paths = get_changed_paths(root)
+ return [
+ check
+ for prefix, checks in MODULE_CHECKS
+ if any(path.startswith(prefix) for path in changed_paths)
+ for check in checks
+ ]
+
+
+@dataclass(frozen=True)
+class ReviewTarget:
+ change_dir: Path
+ state: dict
+ accepted: str
+ files: dict
+
+
+@dataclass(frozen=True)
+class FullReview:
+ gate: str
+ title: str
+ subject: str
+ reviewer: Reviewer
+ categories: tuple
+ non_blocking_categories: tuple
+ summary_categories: tuple
+ category_notes: dict
+ first_roles: tuple
+ files_title: str
+ select_targets: Callable
+ get_checks: Callable
+ block_instruction: str
+ optional_findings_title: str
+ summary_instruction: str
+
+
+@dataclass(frozen=True)
+class ReviewJob:
+ change_name: str
+ prompt: str
+
+
+def format_paths(paths):
+ return "\n".join(f"- {path}" for path in paths) or "- none"
+
+
+def format_findings(full_review, findings):
+ order = {category: index for index, category in enumerate(full_review.categories)}
+ lines = []
+ for finding in sorted(findings, key=lambda finding: order[finding["category"]]):
+ note = full_review.category_notes.get(finding["category"], "")
+ lines.append(f"- [{finding['category']}]{note} {finding['file']}: {finding['summary']}")
+ return "\n".join(lines)
+
+
+def build_full_review_prompt(session, full_review, change_dir, role, details):
+ request = session.load_request()
+ instructions = "\n\n".join(
+ [
+ (HOOKS_DIR / "common-prompt.md").read_text(),
+ (HOOKS_DIR / f"{full_review.gate}-prompt.md").read_text(),
+ ]
+ )
+ candidate = str(get_field(session.payload, "last_assistant_message", "lastAssistantMessage") or "(not available)")
+ return f"""{instructions}
+
+OpenSpec change: {change_dir.relative_to(session.root)}
+Role: {role}
+Repository root: {session.root}
+
+Latest user request:
+<user_request>
+{request.get("prompt") or "(not captured)"}
+</user_request>
+
+Agent response:
+<candidate>
+{candidate}
+</candidate>
+
+{details}
+"""
+
+
+def build_review_jobs(session, full_review, target):
+ change_dir = target.change_dir
+ findings = target.state.get("findings")
+ if findings:
+ changed_since_review = get_paths_changed_since(target.state.get("reviewed_files") or {}, target.files)
+ details = (
+ f"Previous review findings:\n{format_findings(full_review, findings)}\n\n"
+ f"Paths changed after the previous review:\n{format_paths(changed_since_review)}"
+ )
+ prompt = build_full_review_prompt(session, full_review, change_dir, "repeat review", details)
+ return [ReviewJob(change_dir.name, prompt)]
+
+ details = f"{full_review.files_title}:\n{format_paths(sorted(target.files))}"
+ spec_paths = sorted(change_dir.glob("specs/**/spec.md"))
+ roles = [f"delta spec `{path.relative_to(session.root)}`" for path in spec_paths]
+ roles.extend(full_review.first_roles)
+ return [ReviewJob(change_dir.name, build_full_review_prompt(session, full_review, change_dir, role, details)) for role in roles]
+
+
+def parse_findings(full_review, value):
+ findings = value.get("findings")
+ if not isinstance(findings, list):
+ raise ValueError("the reviewer result does not match the schema")
+
+ for finding in findings:
+ if (
+ not isinstance(finding, dict)
+ or finding.get("category") not in full_review.categories
+ or not isinstance(finding.get("file"), str)
+ or not isinstance(finding.get("summary"), str)
+ ):
+ raise ValueError("the reviewer result does not match the schema")
+ return [{"category": finding["category"], "file": finding["file"], "summary": finding["summary"]} for finding in findings]
+
+
+def run_review_job(root, client, full_review, job):
+ try:
+ return parse_findings(full_review, run_reviewer(root, job.prompt, client, full_review.reviewer)), None
+ except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as error:
+ return [], describe_reviewer_error(error)
+
+
+def block_full_review(session, full_review, report, instruction):
+ gate_path = session.gate_path(full_review.gate)
+ blocks = int(load_state(gate_path).get("blocks") or 0) + 1
+ save_state(gate_path, {"blocks": blocks})
+ if blocks > MAX_FULL_REVIEW_REVISIONS:
+ emit(
+ {
+ "continue": False,
+ "stopReason": f"{full_review.title} still fails after {MAX_FULL_REVIEW_REVISIONS} repeats.\n\n{report}",
+ "systemMessage": f"{full_review.title} reached its repeat limit. The result was not accepted.",
+ }
+ )
+ return
+
+ emit({"decision": "block", "reason": f"{AUTOMATIC_REVIEW_PREFIX} {full_review.gate}\n{report}\n\n{instruction}"})
+
+
+def gate_full_review(session, client, full_review):
+ root = session.root
+ targets = full_review.select_targets(session)
+ if not targets:
+ emit({})
+ return
+
+ check_failure = run_checks(root, full_review.get_checks(root, targets))
+ if check_failure:
+ block_full_review(
+ session,
+ full_review,
+ f"{check_failure}\n\nNo reviewer ran.",
+ "Fix the failure and finish the turn again; the full review will repeat.",
+ )
+ return
+
+ jobs = [job for target in targets for job in build_review_jobs(session, full_review, target)]
+ with ThreadPoolExecutor(max_workers=MAX_PARALLEL_REVIEWERS) as executor:
+ results = list(executor.map(lambda job: run_review_job(root, client, full_review, job), jobs))
+
+ reports = []
+ has_blocking = False
+ has_summary_findings = False
+ for target in targets:
+ change_name = target.change_dir.name
+ change_results = [result for job, result in zip(jobs, results) if job.change_name == change_name]
+ findings = [finding for change_findings, _ in change_results for finding in change_findings]
+ errors = [error for _, error in change_results if error]
+ is_blocking = bool(errors) or any(
+ finding["category"] not in full_review.non_blocking_categories for finding in findings
+ )
+
+ state_path = get_change_state_path(root, full_review.gate, change_name)
+ if is_blocking and not errors:
+ save_state(state_path, {"findings": findings, "reviewed_files": target.files})
+ elif not is_blocking:
+ save_state(state_path, {"accepted": target.accepted, "findings": [], "reviewed_files": {}})
+
+ has_blocking = has_blocking or is_blocking
+ has_summary_findings = has_summary_findings or any(
+ finding["category"] in full_review.summary_categories for finding in findings
+ )
+ lines = [format_findings(full_review, findings), *errors]
+ if any(lines):
+ reports.append(f"Change `{change_name}`:\n" + "\n".join(line for line in lines if line))
+
+ report = "\n\n".join(reports)
+ if has_blocking:
+ block_full_review(session, full_review, f"{full_review.title} did not accept the {full_review.subject}.\n\n{report}", full_review.block_instruction)
+ return
+
+ gate_path = session.gate_path(full_review.gate)
+ previous_blocks = int(load_state(gate_path).get("blocks") or 0)
+ save_state(gate_path, {"blocks": 0})
+ # After fix rounds the agent's last response covers only the fixes,
+ # so it writes the summary of the whole work in a separate turn.
+ if previous_blocks or has_summary_findings:
+ optional_findings = f"\n\n{full_review.optional_findings_title}:\n\n{report}" if report else ""
+ emit(
+ {
+ "decision": "block",
+ "reason": f"{AUTOMATIC_REVIEW_PREFIX} {full_review.gate}\n"
+ f"{full_review.title} accepted the {full_review.subject}.{optional_findings}\n\n{full_review.summary_instruction}",
+ }
+ )
+ return
+
+ if report:
+ emit({"systemMessage": f"{full_review.title} accepted the {full_review.subject}. {full_review.optional_findings_title}:\n\n{report}"})
+ return
+ emit({})
+
+
+def select_implementation_targets(session):
+ root = session.root
+ request = session.load_request()
+ fingerprint = get_workspace_fingerprint(root)
+ if "baseline" not in request or request["baseline"] == fingerprint or has_command(request, OPENSPEC_PLANNING_COMMANDS):
+ return []
+
+ change_dirs = [change_dir for change_dir in get_active_changes(root) if is_implemented(change_dir)]
+ states = {change_dir: load_state(get_change_state_path(root, "implementation", change_dir.name)) for change_dir in change_dirs}
+ change_dirs = [change_dir for change_dir in change_dirs if states[change_dir].get("accepted") != fingerprint]
+ if not change_dirs:
+ return []
+
+ files = get_file_hashes(root, get_changed_paths(root))
+ return [ReviewTarget(change_dir, states[change_dir], fingerprint, files) for change_dir in change_dirs]
+
+
+def select_proposal_targets(session):
+ root = session.root
+ baseline = session.load_request().get("openspec_files")
+ if not isinstance(baseline, dict):
+ return []
+
+ targets = []
+ for change_dir in get_active_changes(root):
+ files = get_change_file_hashes(root, change_dir)
+ prefix = f"{change_dir.relative_to(root)}/"
+ baseline_files = {path: digest for path, digest in baseline.items() if path.startswith(prefix)}
+ if files == baseline_files or not is_unstarted(change_dir):
+ continue
+
+ accepted = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest()
+ state = load_state(get_change_state_path(root, "proposal", change_dir.name))
+ if state.get("accepted") == accepted or not is_planning_complete(root, change_dir.name):
+ continue
+ targets.append(ReviewTarget(change_dir, state, accepted, files))
+ return targets
+
+
+IMPLEMENTATION_REVIEW = FullReview(
+ gate="implementation",
+ title="Full implementation review",
+ subject="change",
+ reviewer=IMPLEMENTATION_REVIEWER,
+ categories=("bug", "spec_mismatch", "missing_test", "docs", "minor"),
+ non_blocking_categories=("minor",),
+ summary_categories=(),
+ category_notes={"minor": " (optional)"},
+ first_roles=("documentation and tasks",),
+ files_title="Paths changed relative to HEAD",
+ select_targets=select_implementation_targets,
+ get_checks=lambda root, targets: get_module_checks(root),
+ block_instruction="Resolve every finding yourself, without asking the user. Fix a bug in the code. "
+ "On a spec mismatch, pick the right side and fix the other one, including the change's delta spec. "
+ "Reject a false finding and explain why in your final response. Minor findings are optional. "
+ "If a reviewer could not run, find the cause of the failure. "
+ "Then finish the turn again: the repeat review checks the previous findings and the new edits.",
+ optional_findings_title="Optional findings",
+ summary_instruction="Do not change files any more. Write the user a summary of the whole implementation, not only the last round: "
+ "what was done for the change's tasks; what the full review found in each round and how you resolved it, "
+ "which findings you rejected and why, which minor ones you left; which checks passed; the next step.",
+)
+PROPOSAL_REVIEW = FullReview(
+ gate="proposal",
+ title="Full proposal review",
+ subject="proposal",
+ reviewer=PROPOSAL_REVIEWER,
+ categories=("gap", "mismatch", "tasks", "simplify", "scope", "minor"),
+ non_blocking_categories=("scope", "minor"),
+ summary_categories=("scope",),
+ category_notes={"scope": " (the user decides)", "minor": " (optional)"},
+ first_roles=("proposal and design", "tasks"),
+ files_title="Change files",
+ select_targets=select_proposal_targets,
+ get_checks=lambda root, targets: [
+ Check(".", ("openspec", "validate", target.change_dir.name, "--strict")) for target in targets
+ ],
+ block_instruction="Resolve every gap, mismatch, tasks and simplify finding yourself, without asking the user: "
+ "fix the change's artifacts, and reject a false finding with the reason in your final response. "
+ "Do not apply scope findings: cutting the feature needs the user's consent, and the user sees them in the summary. "
+ "Minor findings are optional. If a reviewer could not run, find the cause of the failure. "
+ "Then finish the turn again: the repeat review checks the previous findings and the new edits.",
+ optional_findings_title="Findings that do not block the turn",
+ summary_instruction="Do not change files any more. Write the user a summary of the whole proposal, not only the last round: "
+ "what is proposed; what the full review found in each round and how you resolved it, "
+ "which findings you rejected and why, which minor ones you left. "
+ "List every scope finding separately: what the user loses and what they save, the decision is theirs. "
+ "End with the next step.",
+)
+FULL_REVIEWS = {full_review.gate: full_review for full_review in (IMPLEMENTATION_REVIEW, PROPOSAL_REVIEW)}
+
+
def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=("session-start", "snapshot", *GATES))
+ parser.add_argument("--client", choices=("claude", "codex"), required=True)
+ arguments = parser.parse_args()
+
payload = read_payload()
if os.environ.get(REVIEWER_ACTIVE_ENV) == "1":
emit({})
return
+ if arguments.action == "session-start":
+ start_session()
+ return
- root = find_root(payload)
- state_path = get_state_path(root, payload)
- action = sys.argv[1] if len(sys.argv) > 1 else ""
- if action == "snapshot":
- snapshot(payload, root, state_path)
+ session = Session(find_root(payload), payload)
+ if arguments.action == "snapshot":
+ snapshot(session)
return
- if action == "plan-gate":
- gate_plan(payload, root, state_path)
+
+ if arguments.action in FULL_REVIEWS:
+ gate_full_review(session, arguments.client, FULL_REVIEWS[arguments.action])
return
- if action in {"claude", "codex"}:
- gate_stop(action, payload, root, state_path)
+
+ event = get_field(payload, "hook_event_name", "hookEventName")
+ if event == "PreToolUse":
+ gate_plan_tool(session, arguments.action, arguments.client)
return
- emit({"continue": False, "stopReason": f"Unknown review hook action: {action}"})
+ gate_stop(session, arguments.action, arguments.client)
if __name__ == "__main__":
diff --git a/.agent-hooks/review_gate_test.py b/.agent-hooks/review_gate_test.py
new file mode 100644
index 00000000..2fd30ad8
--- /dev/null
+++ b/.agent-hooks/review_gate_test.py
@@ -0,0 +1,1190 @@
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import textwrap
+import unittest
+
+
+HOOK_PATH = Path(__file__).resolve().parent / "review_gate.py"
+CHANGE_NAME = "add-widgets"
+PROPOSAL_NAME = "add-gadgets"
+STUB_NAMES = ("claude", "codex", "openspec", "golangci-lint", "pnpm", "npm", "make")
+
+# The stub stands in for every external command: it takes its answer from <stubs>/<name>.json
+# and records each call in <stubs>/calls, so a test sees the arguments, the working directory
+# and the prompt. openspec answers by its first argument (openspec.json["status"]),
+# npm by its script name (npm.json["build"]).
+STUB_SOURCE = textwrap.dedent(
+ """
+ import json
+ import os
+ from pathlib import Path
+ import sys
+ import uuid
+
+ stubs_dir = Path(os.environ["REVIEW_GATE_STUBS"])
+ name = Path(sys.argv[0]).name
+ arguments = sys.argv[1:]
+ prompt = sys.stdin.read() if name in ("claude", "codex") else ""
+ calls_dir = stubs_dir / "calls"
+ calls_dir.mkdir(exist_ok=True)
+ (calls_dir / f"{name}-{uuid.uuid4().hex}.json").write_text(
+ json.dumps(
+ {
+ "name": name,
+ "arguments": arguments,
+ "cwd": os.getcwd(),
+ "prompt": prompt,
+ "effort_env": os.environ.get("CLAUDE_CODE_EFFORT_LEVEL"),
+ }
+ )
+ )
+
+ config_path = stubs_dir / f"{name}.json"
+ config = json.loads(config_path.read_text()) if config_path.exists() else {}
+ if name == "openspec":
+ config = config.get(arguments[0], {})
+ elif name == "npm":
+ config = config.get(arguments[-1], {})
+
+ if config.get("exit_code"):
+ sys.stdout.write(config.get("output", ""))
+ sys.exit(config["exit_code"])
+
+ result = config.get("result", {"ok": True, "reason": "", "findings": []})
+ if name == "claude":
+ sys.stdout.write(json.dumps({"structured_output": result}))
+ elif name == "codex":
+ output_path = arguments[arguments.index("--output-last-message") + 1]
+ Path(output_path).write_text(json.dumps(result))
+ elif name == "openspec" and arguments[0] == "status":
+ sys.stdout.write(config.get("output", json.dumps({"isPlanningComplete": True})))
+ else:
+ sys.stdout.write(config.get("output", ""))
+ """
+)
+PASSING_HOOK_TEST = textwrap.dedent(
+ """
+ import unittest
+
+
+ class SampleTest(unittest.TestCase):
+ def test_passes(self):
+ self.assertTrue(True)
+ """
+)
+FAILING_HOOK_TEST = textwrap.dedent(
+ """
+ import unittest
+
+
+ class SampleTest(unittest.TestCase):
+ def test_reports_broken_gate(self):
+ self.fail("gate returned block for an accepted turn")
+ """
+)
+
+
+class HookRepository:
+ def __init__(self, test_case):
+ temporary_dir = tempfile.TemporaryDirectory(prefix="review-gate-test-")
+ test_case.addCleanup(temporary_dir.cleanup)
+ base = Path(temporary_dir.name)
+
+ self.root = base / "repo"
+ self.stubs_dir = base / "stubs"
+ bin_dir = base / "bin"
+ for directory in (self.root, self.stubs_dir, bin_dir):
+ directory.mkdir()
+
+ for name in STUB_NAMES:
+ stub = bin_dir / name
+ stub.write_text(f"#!{sys.executable}\n{STUB_SOURCE}")
+ stub.chmod(0o755)
+
+ self.environment = {
+ name: value
+ for name, value in os.environ.items()
+ if not name.startswith("GIT_") and name != "AGENT_REVIEW_HOOK_ACTIVE"
+ }
+ self.environment["PATH"] = f"{bin_dir}{os.pathsep}{os.environ['PATH']}"
+ self.environment["REVIEW_GATE_STUBS"] = str(self.stubs_dir)
+ self.environment["PYTHONDONTWRITEBYTECODE"] = "1"
+
+ self.git("init", "--quiet")
+ self.git("config", "user.email", "[email protected]")
+ self.git("config", "user.name", "test")
+ self.write("README.md", "test repository\n")
+ self.write_change(spec_names=("widgets",), tasks="- [x] 1.1 Build\n- [ ] 1.2 Verify\n")
+ self.git("add", ".")
+ self.git("commit", "--quiet", "-m", "init")
+
+ def git(self, *arguments):
+ subprocess.run(["git", *arguments], cwd=self.root, env=self.environment, check=True, capture_output=True)
+
+ def write(self, relative_path, content):
+ path = self.root / relative_path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+
+ def write_change(self, spec_names, tasks, name=CHANGE_NAME):
+ change_dir = f"openspec/changes/{name}"
+ self.write(f"{change_dir}/proposal.md", "# Proposal\n")
+ self.write(f"{change_dir}/design.md", "# Design\n")
+ self.write(f"{change_dir}/tasks.md", f"# Tasks\n\n{tasks}")
+ for spec_name in spec_names:
+ self.write(f"{change_dir}/specs/{spec_name}/spec.md", f"# {spec_name}\n")
+
+ def write_proposal(self, spec_names=("gadgets",), tasks="- [ ] 1.1 Build\n- [ ] 1.2 Verify\n"):
+ self.write_change(spec_names=spec_names, tasks=tasks, name=PROPOSAL_NAME)
+
+ def complete_tasks(self, name=CHANGE_NAME):
+ self.write(f"openspec/changes/{name}/tasks.md", "# Tasks\n\n- [x] 1.1 Build\n- [x] 1.2 Verify\n")
+
+ def set_reviewer_result(self, result):
+ for name in ("claude", "codex"):
+ (self.stubs_dir / f"{name}.json").write_text(json.dumps({"result": result}))
+
+ def set_reviewer_failure(self, output):
+ for name in ("claude", "codex"):
+ (self.stubs_dir / f"{name}.json").write_text(json.dumps({"exit_code": 1, "output": output}))
+
+ def set_stub(self, name, config):
+ (self.stubs_dir / f"{name}.json").write_text(json.dumps(config))
+
+ def calls(self, name=None):
+ calls_dir = self.stubs_dir / "calls"
+ if not calls_dir.is_dir():
+ return []
+ calls = [json.loads(path.read_text()) for path in calls_dir.iterdir()]
+ return [call for call in calls if name is None or call["name"] == name]
+
+ def check_calls(self):
+ return [call for call in self.calls() if call["name"] in ("golangci-lint", "pnpm", "npm", "make")]
+
+ def reviewer_calls(self):
+ return [call for call in self.calls() if call["name"] in ("claude", "codex")]
+
+ def clear_calls(self):
+ for path in (self.stubs_dir / "calls").glob("*.json"):
+ path.unlink()
+
+ def run_hook(self, action, payload, client="claude"):
+ process = subprocess.run(
+ [sys.executable, str(HOOK_PATH), action, "--client", client],
+ cwd=self.root,
+ env=self.environment,
+ input=json.dumps({"cwd": str(self.root), **payload}),
+ text=True,
+ capture_output=True,
+ check=True,
+ )
+ return json.loads(process.stdout) if process.stdout.strip() else None
+
+ def submit_prompt(self, prompt, session_id="session-1", client="claude"):
+ self.run_hook("snapshot", {"hook_event_name": "UserPromptSubmit", "session_id": session_id, "prompt": prompt}, client)
+
+ def stop(self, action, session_id="session-1", client="claude", message="Done."):
+ payload = {"hook_event_name": "Stop", "session_id": session_id, "last_assistant_message": message}
+ return self.run_hook(action, payload, client)
+
+
+def finding(category, summary, file="src/widgets.py:10"):
+ return {"category": category, "file": file, "summary": summary}
+
+
+class SessionStartTest(unittest.TestCase):
+ def test_tells_agent_to_load_communication_skill(self):
+ repository = HookRepository(self)
+
+ response = repository.run_hook("session-start", {"hook_event_name": "SessionStart", "session_id": "session-1"})
+
+ context = response["hookSpecificOutput"]["additionalContext"]
+ self.assertIn(".agents/skills/humanizer/SKILL.md", context)
+
+
+class PlanGateTest(unittest.TestCase):
+ def exit_plan_mode(self, repository, gate, plan):
+ payload = {
+ "hook_event_name": "PreToolUse",
+ "session_id": "session-1",
+ "tool_name": "ExitPlanMode",
+ "tool_input": {"plan": plan},
+ }
+ return repository.run_hook(gate, payload)
+
+ def test_allows_plan_when_reviewer_approves(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Plan the widgets")
+
+ response = self.exit_plan_mode(repository, "plan", "# Plan\n\nAdd widgets.\n")
+
+ self.assertEqual(response, {})
+ [call] = repository.reviewer_calls()
+ self.assertIn("## Plan review", call["prompt"])
+ self.assertIn("Add widgets.", call["prompt"])
+
+ def test_denies_plan_with_reviewer_reason_when_reviewer_rejects(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"ok": False, "reason": "The plan keeps a compatibility alias."})
+ repository.submit_prompt("Plan the widgets")
+
+ response = self.exit_plan_mode(repository, "necessity", "# Plan\n")
+
+ output = response["hookSpecificOutput"]
+ self.assertEqual(output["permissionDecision"], "deny")
+ self.assertIn("The plan keeps a compatibility alias.", output["permissionDecisionReason"])
+
+ def test_denies_exit_plan_mode_without_plan_text(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Plan the widgets")
+
+ response = self.exit_plan_mode(repository, "architecture", "")
+
+ self.assertEqual(response["hookSpecificOutput"]["permissionDecision"], "deny")
+ self.assertEqual(repository.reviewer_calls(), [])
+
+
+class DiffGateTest(unittest.TestCase):
+ def test_accepts_turn_when_reviewer_approves(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ response = repository.stop("diff")
+
+ self.assertEqual(response, {})
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+
+ def test_blocks_turn_with_reviewer_reason_when_reviewer_rejects(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"ok": False, "reason": "No test for an empty list."})
+ repository.submit_prompt("Add a widget")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ response = repository.stop("diff")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("No test for an empty list.", response["reason"])
+
+ def test_diff_reviewer_prompt_checks_agent_instructions(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Fix the docs")
+ repository.write("AGENTS.md", "# AGENTS.md\n")
+
+ repository.stop("diff")
+
+ [call] = repository.reviewer_calls()
+ self.assertIn("Check edits to agent instructions per the same section.", call["prompt"])
+
+ def test_reviewer_prompt_maps_paths_to_module_docs(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ repository.stop("diff")
+
+ [call] = repository.reviewer_calls()
+ self.assertIn("| `agent/**` | `agent/verification/AGENTS.md` |", call["prompt"])
+
+ def test_runs_claude_reviewer_on_opus_with_low_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ repository.stop("diff")
+
+ [call] = repository.calls("claude")
+ self.assertIn("--model opus --effort low", " ".join(call["arguments"]))
+ self.assertEqual(call["effort_env"], "low")
+
+ def test_runs_codex_reviewer_on_gpt_with_low_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget", client="codex")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ repository.stop("diff", client="codex")
+
+ [call] = repository.calls("codex")
+ self.assertIn("--model gpt-6.1-sol --config model_reasoning_effort=\"low\"", " ".join(call["arguments"]))
+
+ def test_stops_agent_after_fourth_rejection(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"ok": False, "reason": "No test for an empty list."})
+ repository.submit_prompt("Add a widget")
+
+ responses = []
+ for attempt in range(4):
+ repository.write("src/widgets.py", f"WIDGETS = [{attempt}]\n")
+ responses.append(repository.stop("diff"))
+
+ self.assertEqual([response.get("decision") for response in responses[:3]], ["block", "block", "block"])
+ self.assertIs(responses[3]["continue"], False)
+
+
+class NamingGateTest(unittest.TestCase):
+ def test_runs_reviewer_when_turn_changes_backend_go_file(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+
+ response = repository.stop("naming")
+
+ self.assertEqual(response, {})
+ [call] = repository.reviewer_calls()
+ self.assertIn("## Naming review", call["prompt"])
+
+ def test_runs_reviewer_when_turn_changes_agent_go_file(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a heartbeat field")
+ repository.write("agent/verification/internal/heartbeat/heartbeat.go", "package heartbeat\n")
+
+ repository.stop("naming")
+
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+
+ def test_runs_reviewer_when_turn_changes_frontend_tsx_file(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("frontend/src/pages/widgets/ui/WidgetsPage.tsx", "export {};\n")
+
+ repository.stop("naming")
+
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+
+ def test_runs_reviewer_when_turn_changes_website_tsx_file(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a page")
+ repository.write("website/app/[lang]/pricing/page.tsx", "export {};\n")
+
+ repository.stop("naming")
+
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+
+ def test_blocks_turn_with_reviewer_reason_when_reviewer_rejects(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"ok": False, "reason": "Active() is a getter, name it GetRunningVerificationIDs()."})
+ repository.submit_prompt("Add a widget")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+
+ response = repository.stop("naming")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("GetRunningVerificationIDs", response["reason"])
+
+ def test_skips_turn_that_changes_only_markdown(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Fix the docs")
+ repository.write("backend/AGENTS.md", "# AGENTS.md\n")
+
+ response = repository.stop("naming")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_turn_that_changes_only_frontend_config(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Bump Vite")
+ repository.write("frontend/vite.config.ts", "export default {};\n")
+
+ repository.stop("naming")
+
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_markdown_turn_when_go_file_was_changed_before_request(self):
+ repository = HookRepository(self)
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+ repository.submit_prompt("Fix the docs")
+ repository.write("backend/AGENTS.md", "# AGENTS.md\n")
+
+ repository.stop("naming")
+
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_turn_that_changes_only_ready_proposal(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("naming")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_runs_claude_reviewer_on_opus_with_low_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+
+ repository.stop("naming")
+
+ [call] = repository.calls("claude")
+ self.assertIn("--model opus --effort low", " ".join(call["arguments"]))
+
+ def test_runs_codex_reviewer_on_gpt_with_low_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Add a widget", client="codex")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+
+ repository.stop("naming", client="codex")
+
+ [call] = repository.calls("codex")
+ self.assertIn("--model gpt-6.1-sol --config model_reasoning_effort=\"low\"", " ".join(call["arguments"]))
+
+
+class ImplementationGateStartTest(unittest.TestCase):
+ def test_runs_full_review_when_agent_completes_last_task(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_skips_review_when_tasks_remain_unchecked(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_when_workspace_is_unchanged_during_turn(self):
+ repository = HookRepository(self)
+ repository.complete_tasks()
+ repository.submit_prompt("What is left?")
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_in_new_session_when_workspace_matches_accepted_state(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue", session_id="first")
+ repository.submit_prompt("Look at the tasks", session_id="second")
+ repository.complete_tasks()
+ repository.stop("implementation", session_id="first")
+ repository.clear_calls()
+
+ response = repository.stop("implementation", session_id="second")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_runs_review_again_when_files_change_after_accepted_review(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+ repository.stop("implementation")
+ repository.clear_calls()
+ repository.submit_prompt("Rename it")
+ repository.write("src/widgets.py", "WIDGETS = ()\n")
+
+ repository.stop("implementation")
+
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_skips_review_when_prompt_has_openspec_planning_command(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("/opsx:propose add widgets")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_archived_changes(self):
+ repository = HookRepository(self)
+ repository.git("rm", "-r", "--quiet", f"openspec/changes/{CHANGE_NAME}")
+ repository.git("commit", "--quiet", "-m", "archive")
+ repository.submit_prompt("Archive it")
+ repository.write_change(spec_names=("widgets",), tasks="- [x] 1.1 Build\n", name=f"archive/2026-10-01-{CHANGE_NAME}")
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_returns_empty_response_without_payload(self):
+ repository = HookRepository(self)
+
+ process = subprocess.run(
+ [sys.executable, str(HOOK_PATH), "implementation", "--client", "claude"],
+ cwd=repository.root,
+ env=repository.environment,
+ input="",
+ text=True,
+ capture_output=True,
+ )
+
+ self.assertEqual(process.returncode, 0)
+ self.assertEqual(json.loads(process.stdout), {})
+
+
+class ImplementationGateChecksTest(unittest.TestCase):
+ def test_runs_only_backend_linter_when_change_touches_backend(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ [call] = repository.check_calls()
+ self.assertEqual(call["name"], "golangci-lint")
+ self.assertEqual(call["arguments"], ["run", "./cmd/...", "./internal/..."])
+ self.assertEqual(Path(call["cwd"]), repository.root / "backend")
+
+ def test_runs_agent_linter_in_verification_agent_directory(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("agent/verification/internal/heartbeat/heartbeat.go", "package heartbeat\n")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ [call] = repository.check_calls()
+ self.assertEqual(call["arguments"], ["run", "./cmd/...", "./internal/...", "./e2e/..."])
+ self.assertEqual(Path(call["cwd"]), repository.root / "agent" / "verification")
+
+ def test_runs_only_frontend_linter_when_change_touches_frontend(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("frontend/src/pages/widgets/ui/WidgetsPage.tsx", "export {};\n")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ self.assertEqual([call["arguments"] for call in repository.check_calls()], [["--dir", "frontend", "lint"]])
+
+ def test_runs_website_lint_and_build_when_change_touches_website(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("website/app/[lang]/pricing/page.tsx", "export {};\n")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ self.assertEqual(
+ sorted(call["arguments"] for call in repository.calls("npm")),
+ [["--prefix", "website", "run", "build"], ["--prefix", "website", "run", "lint"]],
+ )
+
+ def test_runs_no_checks_when_change_touches_no_module(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("docs/widgets.md", "# Widgets\n")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ self.assertEqual(repository.check_calls(), [])
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_blocks_turn_with_output_tail_when_linter_fails(self):
+ repository = HookRepository(self)
+ repository.set_stub("golangci-lint", {"exit_code": 1, "output": "service.go:12:2: ineffectual assignment to err\n"})
+ repository.submit_prompt("Continue")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("`golangci-lint run ./cmd/... ./internal/...` in `backend`", response["reason"])
+ self.assertIn("service.go:12:2: ineffectual assignment to err", response["reason"])
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_never_runs_formatters_or_make(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write("backend/internal/features/widgets/service.go", "package widgets\n")
+ repository.write("frontend/src/pages/widgets/ui/WidgetsPage.tsx", "export {};\n")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls("make"), [])
+ arguments = [" ".join(call["arguments"]) for call in repository.check_calls()]
+ self.assertEqual(len(arguments), 2)
+ self.assertFalse(any("fmt" in argument or "format" in argument for argument in arguments))
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_runs_hook_tests_when_change_touches_hooks(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write(".agent-hooks/sample_test.py", PASSING_HOOK_TEST)
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response, {})
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_blocks_turn_when_hook_tests_fail(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.write(".agent-hooks/sample_test.py", FAILING_HOOK_TEST)
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("gate returned block for an accepted turn", response["reason"])
+ self.assertEqual(repository.reviewer_calls(), [])
+
+
+class ImplementationGateReviewTest(unittest.TestCase):
+ def test_runs_reviewer_per_spec_and_one_for_docs_on_claude_with_medium_effort(self):
+ repository = HookRepository(self)
+ repository.write_change(spec_names=("widgets", "gadgets"), tasks="- [x] 1.1 Build\n")
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ calls = repository.calls("claude")
+ self.assertEqual(len(calls), 3)
+ for call in calls:
+ self.assertIn("--model opus --effort medium", " ".join(call["arguments"]))
+ self.assertEqual(call["effort_env"], "medium")
+ roles = sorted(line for call in calls for line in call["prompt"].splitlines() if line.startswith("Role:"))
+ self.assertEqual(
+ roles,
+ [
+ f"Role: delta spec `openspec/changes/{CHANGE_NAME}/specs/gadgets/spec.md`",
+ f"Role: delta spec `openspec/changes/{CHANGE_NAME}/specs/widgets/spec.md`",
+ "Role: documentation and tasks",
+ ],
+ )
+
+ def test_runs_codex_reviewers_on_gpt_with_high_effort(self):
+ repository = HookRepository(self)
+ repository.write_change(spec_names=("widgets", "gadgets"), tasks="- [x] 1.1 Build\n")
+ repository.submit_prompt("Continue", client="codex")
+ repository.complete_tasks()
+
+ repository.stop("implementation", client="codex")
+
+ calls = repository.calls("codex")
+ self.assertEqual(len(calls), 3)
+ for call in calls:
+ self.assertIn("--model gpt-6.1-sol --config model_reasoning_effort=\"high\"", " ".join(call["arguments"]))
+
+ def test_implementation_docs_reviewer_prompt_checks_agent_instructions(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ repository.stop("implementation")
+
+ [call] = [call for call in repository.reviewer_calls() if "\nRole: documentation and tasks\n" in call["prompt"]]
+ prompt = call["prompt"]
+ docs_role = prompt[prompt.index("### Role: documentation and tasks") : prompt.index("### Role: repeat review")]
+ self.assertIn("Check the edits to agent instructions the change made", docs_role)
+
+ def test_blocks_turn_and_requires_agent_to_resolve_findings_when_reviewer_finds_bug(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("bug", "Race between the check and the write.")]})
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("[bug] src/widgets.py:10: Race between the check and the write.", response["reason"])
+ self.assertIn("without asking the user", response["reason"])
+
+ def test_marks_minor_findings_optional_when_turn_is_blocked(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result(
+ {"findings": [finding("docs", "The README does not mention the command."), finding("minor", "Long function.")]}
+ )
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertIn("[minor] (optional) src/widgets.py:10: Long function.", response["reason"])
+
+ def test_accepts_change_and_shows_minor_findings_to_user(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("minor", "Long function.")]})
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+ repository.clear_calls()
+ repeated_response = repository.stop("implementation")
+
+ self.assertNotIn("decision", response)
+ self.assertIn("Long function.", response["systemMessage"])
+ self.assertEqual(repeated_response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_blocks_turn_when_reviewer_answer_does_not_match_schema(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [{"category": "typo", "file": "a", "summary": "b"}]})
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("does not match the schema", response["reason"])
+
+ def test_blocks_turn_with_failure_reason_when_reviewer_crashes(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_failure("rate limit exceeded")
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+
+ response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("rate limit exceeded", response["reason"])
+
+
+class ImplementationGateRepeatTest(unittest.TestCase):
+ def block_with_bug(self, repository):
+ repository.set_reviewer_result({"findings": [finding("bug", "Race between the check and the write.")]})
+ repository.submit_prompt("Continue")
+ repository.write("src/widgets.py", "WIDGETS = []\n")
+ repository.write("src/gadgets.py", "GADGETS = []\n")
+ repository.complete_tasks()
+ repository.stop("implementation")
+ repository.clear_calls()
+
+ def test_repeat_runs_one_reviewer_with_previous_findings_and_paths_changed_after_review(self):
+ repository = HookRepository(self)
+ self.block_with_bug(repository)
+ repository.write("src/widgets.py", "WIDGETS = ()\n")
+
+ repository.stop("implementation")
+
+ [call] = repository.reviewer_calls()
+ self.assertIn("Role: repeat review", call["prompt"])
+ self.assertIn("Race between the check and the write.", call["prompt"])
+ changed_paths = call["prompt"].split("Paths changed after the previous review:")[1]
+ self.assertIn("- src/widgets.py", changed_paths)
+ self.assertNotIn("src/gadgets.py", changed_paths)
+
+ def test_accepted_repeat_clears_findings(self):
+ repository = HookRepository(self)
+ self.block_with_bug(repository)
+ repository.set_reviewer_result({"findings": []})
+ repository.write("src/widgets.py", "WIDGETS = ()\n")
+
+ repository.stop("implementation")
+ repository.write("src/widgets.py", "WIDGETS = (1,)\n")
+ repository.clear_calls()
+ repository.stop("implementation")
+
+ self.assertEqual(len(repository.reviewer_calls()), 2)
+
+ def test_asks_for_summary_of_whole_implementation_once_after_repeat_accepts_change(self):
+ repository = HookRepository(self)
+ self.block_with_bug(repository)
+ repository.set_reviewer_result({"findings": [finding("minor", "Long function.")]})
+ repository.write("src/widgets.py", "WIDGETS = ()\n")
+
+ response = repository.stop("implementation")
+ repository.clear_calls()
+ summary_response = repository.stop("implementation")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("accepted the change", response["reason"])
+ self.assertIn("summary of the whole implementation", response["reason"])
+ self.assertIn("Long function.", response["reason"])
+ self.assertEqual(summary_response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_stops_agent_with_remaining_findings_after_third_block(self):
+ repository = HookRepository(self)
+ self.block_with_bug(repository)
+ repository.write("src/widgets.py", "WIDGETS = ()\n")
+ second_response = repository.stop("implementation")
+ repository.write("src/widgets.py", "WIDGETS = (1,)\n")
+
+ third_response = repository.stop("implementation")
+
+ self.assertEqual(second_response["decision"], "block")
+ self.assertIs(third_response["continue"], False)
+ self.assertIn("Race between the check and the write.", third_response["stopReason"])
+
+
+class NecessityDuringImplementationReviewTest(unittest.TestCase):
+ def block_with_spec_mismatch(self, repository):
+ repository.set_reviewer_result({"findings": [finding("spec_mismatch", "The spec requires 409, the code answers 400.")]})
+ repository.submit_prompt("Continue")
+ repository.complete_tasks()
+ repository.stop("implementation")
+ repository.clear_calls()
+
+ def test_skips_necessity_when_agent_fixes_delta_spec_after_finding(self):
+ repository = HookRepository(self)
+ self.block_with_spec_mismatch(repository)
+ repository.write(f"openspec/changes/{CHANGE_NAME}/specs/widgets/spec.md", "# widgets\n\nAnswers 400.\n")
+
+ response = repository.stop("necessity")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_runs_necessity_when_prompt_has_openspec_planning_command(self):
+ repository = HookRepository(self)
+ self.block_with_spec_mismatch(repository)
+ repository.submit_prompt("/opsx:propose a new change")
+ repository.write(f"openspec/changes/{CHANGE_NAME}/specs/widgets/spec.md", "# widgets\n\nAnswers 400.\n")
+
+ repository.stop("necessity")
+
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+
+
+class ProposalGateStartTest(unittest.TestCase):
+ def test_runs_full_review_when_agent_writes_all_artifacts_without_command(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec for gadgets")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(len(repository.reviewer_calls()), 3)
+
+ def test_skips_review_without_calling_openspec_when_tasks_are_missing(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec for gadgets")
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/proposal.md", "# Proposal\n")
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_without_calling_openspec_when_tasks_file_has_no_tasks(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec for gadgets")
+ repository.write_proposal(tasks="")
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_when_openspec_reports_incomplete_artifacts(self):
+ repository = HookRepository(self)
+ repository.set_stub("openspec", {"status": {"output": json.dumps({"isPlanningComplete": False})}})
+ repository.submit_prompt("Write a spec for gadgets")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_review_when_openspec_status_fails(self):
+ repository = HookRepository(self)
+ repository.set_stub("openspec", {"status": {"exit_code": 1, "output": "openspec: unknown change"}})
+ repository.submit_prompt("Write a spec for gadgets")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_review_without_calling_openspec_when_task_is_checked(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Fix the widgets spec")
+ repository.write(f"openspec/changes/{CHANGE_NAME}/specs/widgets/spec.md", "# widgets\n\nAnswers 409.\n")
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_when_change_files_are_unchanged_during_turn(self):
+ repository = HookRepository(self)
+ repository.write_proposal()
+ repository.submit_prompt("What is in the proposal?")
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_skips_review_in_new_session_when_files_match_accepted_state(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec", session_id="first")
+ repository.submit_prompt("Look at the spec", session_id="second")
+ repository.write_proposal()
+ repository.stop("proposal", session_id="first")
+ repository.clear_calls()
+
+ response = repository.stop("proposal", session_id="second")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_runs_review_again_when_design_changes_after_accepted_review(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+ repository.stop("proposal")
+ repository.clear_calls()
+ repository.submit_prompt("Fix the design")
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/design.md", "# Design\n\nIn-memory cache.\n")
+
+ repository.stop("proposal")
+
+ self.assertEqual(len(repository.reviewer_calls()), 3)
+
+ def test_skips_archived_changes(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Archive it")
+ repository.write_change(spec_names=("gadgets",), tasks="- [ ] 1.1 Build\n", name=f"archive/2026-10-01-{PROPOSAL_NAME}")
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response, {})
+ self.assertEqual(repository.calls(), [])
+
+
+class ProposalGateValidationTest(unittest.TestCase):
+ def test_blocks_turn_with_validation_output_when_requirement_has_no_scenario(self):
+ repository = HookRepository(self)
+ repository.set_stub(
+ "openspec",
+ {"validate": {"exit_code": 1, "output": '✗ [ERROR] gadgets/spec.md: ADDED "Gadgets" must include at least one scenario\n'}},
+ )
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn(f"`openspec validate {PROPOSAL_NAME} --strict`", response["reason"])
+ self.assertIn("must include at least one scenario", response["reason"])
+ self.assertEqual(repository.reviewer_calls(), [])
+
+
+class ProposalGateReviewTest(unittest.TestCase):
+ def test_runs_reviewer_per_spec_and_for_proposal_and_tasks_on_claude_with_medium_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal(spec_names=("gadgets", "gizmos"))
+
+ repository.stop("proposal")
+
+ calls = repository.calls("claude")
+ self.assertEqual(len(calls), 4)
+ for call in calls:
+ self.assertIn("--model opus --effort medium", " ".join(call["arguments"]))
+ self.assertEqual(call["effort_env"], "medium")
+ roles = sorted(line for call in calls for line in call["prompt"].splitlines() if line.startswith("Role:"))
+ self.assertEqual(
+ roles,
+ [
+ f"Role: delta spec `openspec/changes/{PROPOSAL_NAME}/specs/gadgets/spec.md`",
+ f"Role: delta spec `openspec/changes/{PROPOSAL_NAME}/specs/gizmos/spec.md`",
+ "Role: proposal and design",
+ "Role: tasks",
+ ],
+ )
+
+ def test_runs_codex_reviewers_on_gpt_with_high_effort(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec", client="codex")
+ repository.write_proposal(spec_names=("gadgets", "gizmos"))
+
+ repository.stop("proposal", client="codex")
+
+ calls = repository.calls("codex")
+ self.assertEqual(len(calls), 4)
+ for call in calls:
+ self.assertIn("--model gpt-6.1-sol --config model_reasoning_effort=\"high\"", " ".join(call["arguments"]))
+
+ def test_tasks_reviewer_prompt_requires_every_scenario_covered_by_task_with_test(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ repository.stop("proposal")
+
+ [call] = [call for call in repository.reviewer_calls() if "\nRole: tasks\n" in call["prompt"]]
+ self.assertIn("every scenario of the delta specs is covered by a task with a test", call["prompt"])
+ self.assertIn("the task order can be followed", call["prompt"])
+
+ def test_blocks_turn_and_requires_agent_to_resolve_simplify_finding_without_asking_user(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result(
+ {"findings": [finding("simplify", "A field in an existing table replaces the new table.", file="design.md:12")]}
+ )
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("[simplify] design.md:12: A field in an existing table replaces the new table.", response["reason"])
+ self.assertIn("without asking the user", response["reason"])
+
+ def test_asks_for_summary_with_scope_finding_without_requiring_fix(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("scope", "The settings screen can be dropped.", file="proposal.md:5")]})
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+ repository.clear_calls()
+ summary_response = repository.stop("proposal")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("Full proposal review accepted the proposal.", response["reason"])
+ self.assertIn("[scope] (the user decides) proposal.md:5: The settings screen can be dropped.", response["reason"])
+ self.assertIn("summary of the whole proposal", response["reason"])
+ self.assertIn("what the user loses and what they save", response["reason"])
+ self.assertEqual(summary_response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_accepts_proposal_and_shows_minor_findings_to_user(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("minor", "Long paragraph.", file="design.md:3")]})
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+ repository.clear_calls()
+ repeated_response = repository.stop("proposal")
+
+ self.assertNotIn("decision", response)
+ self.assertIn("Long paragraph.", response["systemMessage"])
+ self.assertEqual(repeated_response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_blocks_turn_when_reviewer_uses_implementation_category(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("bug", "Race.")]})
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ response = repository.stop("proposal")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("does not match the schema", response["reason"])
+
+
+class ProposalGateRepeatTest(unittest.TestCase):
+ def block_with_gap(self, repository):
+ repository.set_reviewer_result({"findings": [finding("gap", "The answer for an empty list is missing.", file="specs/gadgets/spec.md:8")]})
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+ repository.stop("proposal")
+ repository.clear_calls()
+
+ def test_repeat_runs_one_reviewer_with_previous_findings_and_files_changed_after_review(self):
+ repository = HookRepository(self)
+ self.block_with_gap(repository)
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/specs/gadgets/spec.md", "# gadgets\n\nEmpty list.\n")
+
+ repository.stop("proposal")
+
+ [call] = repository.reviewer_calls()
+ self.assertIn("Role: repeat review", call["prompt"])
+ self.assertIn("The answer for an empty list is missing.", call["prompt"])
+ changed_paths = call["prompt"].split("Paths changed after the previous review:")[1]
+ self.assertIn(f"- openspec/changes/{PROPOSAL_NAME}/specs/gadgets/spec.md", changed_paths)
+ self.assertNotIn("design.md", changed_paths)
+
+ def test_asks_for_summary_of_whole_proposal_once_after_repeat_accepts_it(self):
+ repository = HookRepository(self)
+ self.block_with_gap(repository)
+ repository.set_reviewer_result({"findings": []})
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/specs/gadgets/spec.md", "# gadgets\n\nEmpty list.\n")
+
+ response = repository.stop("proposal")
+ repository.clear_calls()
+ summary_response = repository.stop("proposal")
+
+ self.assertEqual(response["decision"], "block")
+ self.assertIn("accepted the proposal", response["reason"])
+ self.assertIn("summary of the whole proposal", response["reason"])
+ self.assertEqual(summary_response, {})
+ self.assertEqual(repository.calls(), [])
+
+ def test_stops_agent_with_remaining_findings_after_third_block(self):
+ repository = HookRepository(self)
+ self.block_with_gap(repository)
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/design.md", "# Design\n\nSecond attempt.\n")
+ second_response = repository.stop("proposal")
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/design.md", "# Design\n\nThird attempt.\n")
+
+ third_response = repository.stop("proposal")
+
+ self.assertEqual(second_response["decision"], "block")
+ self.assertIs(third_response["continue"], False)
+ self.assertIn("Full proposal review", third_response["stopReason"])
+ self.assertIn("The answer for an empty list is missing.", third_response["stopReason"])
+
+
+class QuickGatesDuringProposalReviewTest(unittest.TestCase):
+ def test_skips_quick_checks_when_turn_changes_only_ready_proposal(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+
+ responses = [repository.stop(gate) for gate in ("necessity", "architecture", "diff")]
+
+ self.assertEqual(responses, [{}, {}, {}])
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_skips_quick_checks_in_summary_turn_after_accepted_review(self):
+ repository = HookRepository(self)
+ repository.set_reviewer_result({"findings": [finding("scope", "The settings screen can be dropped.")]})
+ repository.submit_prompt("Write a spec")
+ repository.write_proposal()
+ repository.stop("proposal")
+ repository.clear_calls()
+
+ responses = [repository.stop(gate, message="Proposal summary.") for gate in ("necessity", "architecture", "diff")]
+
+ self.assertEqual(responses, [{}, {}, {}])
+ self.assertEqual(repository.reviewer_calls(), [])
+
+ def test_runs_necessity_when_agent_wrote_only_proposal(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec")
+ repository.write(f"openspec/changes/{PROPOSAL_NAME}/proposal.md", "# Proposal\n")
+
+ repository.stop("necessity", message="Is the settings screen needed?")
+
+ [call] = repository.reviewer_calls()
+ self.assertIn("Under review: OpenSpec proposal", call["prompt"])
+
+ def test_runs_quick_checks_without_calling_openspec_when_code_changes_too(self):
+ repository = HookRepository(self)
+ repository.submit_prompt("Write a spec and start")
+ repository.write_proposal()
+ repository.write("src/gadgets.py", "GADGETS = []\n")
+
+ response = repository.stop("diff")
+
+ self.assertEqual(response, {})
+ self.assertEqual(len(repository.reviewer_calls()), 1)
+ self.assertEqual(repository.calls("openspec"), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.md
deleted file mode 100644
index d1e32721..00000000
--- a/.claude/agents/reviewer.md
+++ /dev/null
@@ -1,117 +0,0 @@
----
-name: reviewer
-description: Audits a plan or a working-tree diff against the repo's AGENTS.md standards. The review hooks run the same audit automatically; invoke this only when hooks are disabled or when the user asks for a manual review.
-tools: Read, Grep, Glob, Bash
----
-
-You audit work against the Databasus `AGENTS.md` standards. You report violations; you never fix them. You have no `Write` or `Edit` tool — the calling agent applies every fix.
-
-Your caller tells you the mode: **plan** or **implementation**. If the mode is absent, infer it: a plan file path means plan mode, otherwise implementation mode.
-
-Before reviewing, read `.agents/skills/humanizer/SKILL.md` completely. Apply it in embedded mode to your report.
-
-## Step 1 — Resolve scope
-
-**Implementation mode.** Run `git status --porcelain` and `git diff HEAD` to get the changed files and their contents. Untracked files do not appear in `git diff` — read them with `Read`.
-
-**Plan mode.** Read the plan file the caller names. Extract the files it proposes to touch, the names it proposes to introduce, and any behavior it proposes to preserve.
-
-## Step 2 — Read the governing docs
-
-Every file is governed by **two** documents at once, and you audit it against both. Neither replaces the other: the root doc carries the project-wide philosophy, and the module doc carries the stack-specific rules on top of it.
-
-1. **Always** read `AGENTS.md` at the repo root. It governs every file in every module, with no exceptions.
-2. **Also** read the module doc for each area the change touches:
-
- | Touched path | Module doc |
- | --- | --- |
- | `backend/**` | `backend/AGENTS.md` |
- | `agent/**` | `agent/verification/AGENTS.md` |
- | `frontend/**` | `frontend/AGENTS.md` |
- | `website/**` | `website/AGENTS.md` |
- | `assets/readme/**` | `assets/readme/AGENTS.md` |
-
-A change spanning several modules is audited against the root doc plus *every* module doc it touches. A change under `backend/` is audited against the root doc **and** `backend/AGENTS.md` — never the module doc alone, and never the root doc alone.
-
-Skip only the module docs that govern nothing in scope. Never skip the root doc.
-
-## Step 3 — Audit
-
-Audit against the root doc and the module doc together. Run the root-level pass over *every* changed file, including files governed by a module doc — a module doc's silence on naming or comments does not exempt that module from the root rules.
-
-These are the rules that get violated most. They are not the whole of the docs — the docs you read in step 2 are authoritative, and this list is a prompt for where to look first.
-
-### From the root `AGENTS.md` — applies to every changed file
-
-**Naming.** Names state intent, not mechanism. No `data`, `handle`, `process`, `tmp`, `helper`, `manager`. No type-suffix noise (`nameStr`, `agentList`, `tokenObj`). Booleans and predicate methods take `is` / `can` / `has` / `should` — `IsAborted(id)`, not `AbortedContains(id)`. State that holds the entity being acted on names the entity — `deletingAgentId`, not `deletingId`. Getters take a `Get` prefix and name the entity — `GetRunningVerificationIDs()`, not `Active()`; this is house style and deliberately departs from vanilla Go. A getter returning a bool stays a predicate (`Is...`/`Has...`). A name that hides a second effect is a lie — a function that records *and* cancels is `recordAndCancelAborts`, or it is two functions. Tests use domain nouns, never `got` / `want` / `expected`.
-
-**Comments.** The default is no comment. A comment that restates what the code does is a naming bug: if `// Foo does X` sits above `func Foo`, the fix is to rename `Foo` until the comment is redundant. Only a *why* justifies a comment — a business rule, a cross-system constraint, a non-obvious optimisation. No "how it was" comments (`used to be X`, `renamed from Y`, `kept for legacy callers`); history lives in git.
-
-**Prose.** Audit every agent-authored response, plan, document, OpenSpec artifact, review finding, commit or pull request text, and code comment available in scope against `.agents/skills/humanizer/SKILL.md`. Before humanizing a code comment, verify that clearer naming or a smaller function cannot remove it. Flag removable comments instead of rewriting them. Humanization must preserve facts, behavior, scope, and technical meaning.
-
-**Backward compatibility.** Never preserved unless the user asked for it. Flag every deprecation shim, alias, and fallback for the old shape.
-
-**Language.** English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages — including user-facing fallback copy. The one exception under `frontend/src/` is the interface dictionaries (`frontend/src/shared/i18n/locales/<locale>.ts`), whose values are in the target language; their keys, identifiers and comments stay English.
-
-**Types and signatures.** No generic type names (`Manager`, `Provisioner`, `Handler`). No package stutter (`container.ContainerManager`) — `revive` fails CI on it; put the noun on the variable instead. Roughly four or more positional parameters, or two adjacent same-typed parameters, become a named struct.
-
-**Security.** No disabled or weakened security checks to make a build pass. Every GitHub Action pinned to a full commit SHA with a `# vX.Y.Z` comment — no floating `@v4` or `@main`. Workflows default to top-level `permissions: contents: read`.
-
-### From the module docs — applies on top of the root pass
-
-**`backend/AGENTS.md`.** Dependency injection through `SetupDependencies()`; never inject another feature's repository. Controller tests preferred over unit tests; `features/tests/` is reserved for backup→restore cycle tests; clean up test data. Logging: values in the message, IDs and errors as key-value pairs, scope IDs via `logger.With(...)`; never log secrets, tokens, or credentials — redact at the logger layer, not at call sites. File organization, spacing between logical statements, time handling, and modern Go (`slices`, `context` helpers, `omitzero` over `omitempty`, `new(val)`).
-
-**`agent/verification/AGENTS.md`.** The same spacing, file organization, background-service, testing, time-handling, logging and modern-Go rules as the backend doc, in their agent-specific form. Read it rather than assuming it matches the backend doc.
-
-**`frontend/AGENTS.md`.** Feature-Sliced Design: import direction, correct slice placement, no cross-imports between same-layer slices. React component structure order, vertical spacing, UI kit and icons, forms and progressive disclosure, user-facing copy.
-
-**`website/AGENTS.md`.** Keep translated pages structurally synchronized with English, preserve localized link and metadata rules, and apply the locale-specific translation standards. Run `npm run lint` and `npm run build` when website files change.
-
-**`assets/readme/AGENTS.md`.** Keep all five translations synchronized with the root README, preserve byte-identical technical content and locale-specific paths, and apply the website translation-quality rules.
-
-## Step 4 — Lint (implementation mode only)
-
-Run the linter for each directory the diff actually touches, and no others:
-
-- `backend/**` → `make lint` in `backend/`
-- `agent/**` → `make lint` in `agent/verification/`
-- `frontend/**` → `pnpm lint` in `frontend/`
-- `website/**` → `npm run lint` and `npm run build` in `website/`
-
-Changes limited to `assets/readme/**` have no dedicated linter. Verify their structure and byte-identical technical content against the root `README.md`.
-
-Report each failure as a finding. Skip this step entirely in plan mode.
-
-## Step 5 — Report
-
-Open with a verdict line, alone, exactly one of:
-
-```
-PASS
-CHANGES REQUIRED
-```
-
-On the line below the verdict, name the docs you audited against, so the caller can see the root doc was not skipped:
-
-```
-Audited against: AGENTS.md, backend/AGENTS.md
-```
-
-On `CHANGES REQUIRED`, list findings beneath that, most severe first, one per line. Every finding names the doc the rule comes from:
-
-```
-<file>:<line> — [<doc>] <the rule violated> — <the concrete fix>
-```
-
-For example:
-
-```
-backend/internal/features/system/agent/service.go:42 — [AGENTS.md] getters take a Get prefix and name the entity — rename Active() to GetRunningVerificationIDs()
-backend/internal/features/system/agent/di.go:17 — [backend/AGENTS.md] never inject another feature's repository — depend on the audit log service, not AuditLogRepository
-```
-
-In plan mode a finding cites the plan's section instead of a line number.
-
-On `PASS`, list nothing below the `Audited against:` line.
-
-Report only violations of a rule written in one of the docs you read. Do not invent style preferences the docs do not state. Do not restate what the code does. Do not praise. If a rule is ambiguous as applied to this code, say so in the finding and name the reading you took, rather than silently choosing one.
diff --git a/.claude/settings.json b/.claude/settings.json
index b3ea19d9..81bfd97b 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -1,25 +1,48 @@
{
"hooks": {
- "UserPromptSubmit": [
+ "SessionStart": [
{
"hooks": [
{
"type": "command",
- "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" session-start --client claude",
"timeout": 10
}
]
}
],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot --client claude",
+ "timeout": 30
+ }
+ ]
+ }
+ ],
"PreToolUse": [
{
"matcher": "ExitPlanMode",
"hooks": [
{
"type": "command",
- "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" plan-gate",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" plan --client claude",
"timeout": 600,
"statusMessage": "Reviewing the plan"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" necessity --client claude",
+ "timeout": 600,
+ "statusMessage": "Checking whether the task is needed"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" architecture --client claude",
+ "timeout": 600,
+ "statusMessage": "Checking architecture"
}
]
}
@@ -29,9 +52,39 @@
"hooks": [
{
"type": "command",
- "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" claude",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" diff --client claude",
+ "timeout": 600,
+ "statusMessage": "Reviewing the diff"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" necessity --client claude",
+ "timeout": 600,
+ "statusMessage": "Checking whether the task is needed"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" architecture --client claude",
"timeout": 600,
- "statusMessage": "Reviewing the plan and changes"
+ "statusMessage": "Checking architecture"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" naming --client claude",
+ "timeout": 600,
+ "statusMessage": "Checking names"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" implementation --client claude",
+ "timeout": 3600,
+ "statusMessage": "Full implementation review"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" proposal --client claude",
+ "timeout": 3600,
+ "statusMessage": "Full proposal review"
}
]
}
diff --git a/.codex/hooks.json b/.codex/hooks.json
index 8bccfc8b..c17a2adc 100644
--- a/.codex/hooks.json
+++ b/.codex/hooks.json
@@ -1,25 +1,72 @@
{
- "description": "Review plans and completed changes before Codex stops.",
+ "description": "Review the plan, the task's necessity, the diff, architecture and names, plus the full review of a finished OpenSpec proposal and a finished implementation, before Codex finishes a turn.",
"hooks": {
- "UserPromptSubmit": [
+ "SessionStart": [
{
"hooks": [
{
"type": "command",
- "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" session-start --client codex",
"timeout": 10
}
]
}
],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot --client codex",
+ "timeout": 30
+ }
+ ]
+ }
+ ],
"Stop": [
{
"hooks": [
{
"type": "command",
- "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" codex",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" plan --client codex",
+ "timeout": 600,
+ "statusMessage": "Reviewing the plan"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" necessity --client codex",
"timeout": 600,
- "statusMessage": "Reviewing the plan and changes"
+ "statusMessage": "Checking whether the task is needed"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" diff --client codex",
+ "timeout": 600,
+ "statusMessage": "Reviewing the diff"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" architecture --client codex",
+ "timeout": 600,
+ "statusMessage": "Checking architecture"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" naming --client codex",
+ "timeout": 600,
+ "statusMessage": "Checking names"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" implementation --client codex",
+ "timeout": 3600,
+ "statusMessage": "Full implementation review"
+ },
+ {
+ "type": "command",
+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" proposal --client codex",
+ "timeout": 3600,
+ "statusMessage": "Full proposal review"
}
]
}
diff --git a/.gitignore b/.gitignore
index 9a180f66..24926154 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,3 +25,4 @@ backend/cleanup_test_db.exe
plans/
.pnpm-store
+__pycache__/
diff --git a/AGENTS.md b/AGENTS.md
index 6997fee3..4afde86c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,11 +5,12 @@ This is NOT a strict set of rules — it is a set of recommendations to help wri
Per-folder rules live next to the code they govern:
-- [`backend/AGENTS.md`](backend/AGENTS.md) — Go + Gin + GORM + PostgreSQL backend (controllers, migrations, CRUD, DI, testing, logging)
-- [`agent/verification/AGENTS.md`](agent/verification/AGENTS.md) — Go verification agent CLI (self-update + capacity heartbeat; restore logic deferred)
-- [`frontend/AGENTS.md`](frontend/AGENTS.md) — React 19 + TypeScript + Vite + Ant Design + Tailwind
-- [`website/AGENTS.md`](website/AGENTS.md) — Next.js marketing site and its 6-language translation rules
+- [`backend/AGENTS.md`](backend/AGENTS.md) — backend code rules, Go + Gin + GORM + PostgreSQL
+- [`agent/verification/AGENTS.md`](agent/verification/AGENTS.md) — verification agent code rules, Go CLI
+- [`frontend/AGENTS.md`](frontend/AGENTS.md) — frontend code rules, React + TypeScript + Vite + Ant Design + Tailwind
+- [`website/AGENTS.md`](website/AGENTS.md) — marketing site rules and its translations, Next.js
- [`assets/readme/AGENTS.md`](assets/readme/AGENTS.md) — translated copies of the root `README.md`
+- [`adr/AGENTS.md`](adr/AGENTS.md) — how to write architecture decision records
This root file holds the engineering philosophy that applies everywhere.
@@ -27,16 +28,16 @@ Reply to the user in the language they write in, and keep everything committed t
## Development environment
-Work happens inside the repo's [Dev Container](.devcontainer/devcontainer.json). The container ships Go, Node.js + pnpm, Docker-in-Docker, linters and matching VS Code extensions, so the toolchain is identical for every contributor. Ports `4005` (backend) and `5173` (Vite) are forwarded automatically. Don't install or rely on host-level SDKs — run `make`, `pnpm` and `docker` commands from inside the container.
+Work happens inside the repo's [Dev Container](.devcontainer/devcontainer.json), so the toolchain is identical for every contributor. Don't install or rely on host-level SDKs — run `make`, `pnpm` and `docker` commands from inside the container.
-Running the backend suite host-native is supported on Fedora via `make test-fedora`, which shims the Debian soname the bundled `assets/tools` clients expect. Any other host distro is on its own — the container stays the reference environment. Also project sometimes is run in different worktrees, in this case it is needed to copy .env.example -> .env, `make swagger` and `pnpm install` to run tests
+On a Fedora host the backend suite may run host-native through `make test-fedora`. Any other host distro is on its own — the container stays the reference environment. In a fresh worktree, copy `.env.example` to `.env` and run `make swagger` and `pnpm install` before running tests.
### Several agents, one set of containers
Several agents may work on this repo at once, in different worktrees, sharing one Docker daemon, one set of test containers and one pool of test metadata databases. Don't let that stop you from running tests — simultaneous runs are rare and usually harmless. Two habits keep them that way:
-- Lint and format whenever you want. `make lint`, `pnpm lint`, `pnpm format`, `npm run lint` and the frontend's `pnpm test` touch nothing shared.
-- Test the package you touched: `go test ./internal/features/<feature>/... -count=1` loads the repo-root `.env` itself and claims a free database slot through an advisory lock (`backend/internal/config/config.go`). Leave `make test` and `make test-fedora` for the end of a change — they start by removing every `org.testcontainers` container and recreating every slot database, which those slots also come from, so a fresh environment needs one full run first.
+- Lint and format whenever you want: the linters, the formatters and the frontend's `pnpm test` touch nothing shared.
+- Test the package you touched with `go test ./internal/features/<feature>/... -count=1`; the database slot it claims is described in [`backend/internal/config/config.go`](backend/internal/config/config.go). Leave `make test` and `make test-fedora` for the end of a change, because they reset the test containers and slot databases every other agent uses. A fresh environment needs one full run first.
When a failure makes no sense — a container that vanished, a database that emptied itself — a parallel run is worth suspecting in maybe one case in twenty. Re-run before hunting the bug.
@@ -76,18 +77,35 @@ The dictionaries are the only target-language text anywhere under `frontend/`, `
Reread the diff with fresh eyes and **list** (don't silently apply) refactor suggestions: unclear names, duplication, dead code, deep nesting, misplaced responsibilities, leaky abstractions. Keep suggestions concrete (file + lines), behavior-preserving, and scoped to the current change. If the diff is already clean, say so in one line.
-### Mandatory compliance review
+### Review hooks
-Every non-trivial change is audited twice against this document **and** the module doc for each area it touches (`backend/AGENTS.md`, `agent/verification/AGENTS.md`, `frontend/AGENTS.md`, `website/AGENTS.md`, `assets/readme/AGENTS.md`). The module docs add stack-specific rules on top of this one; they never replace it, so a change under `backend/` answers to both. The rules the audit applies live in [`.claude/agents/reviewer.md`](.claude/agents/reviewer.md).
+Every change answers to this document **and** the module doc for each area it touches. The module docs add stack-specific rules on top of this one; they never replace it, so a change under `backend/` answers to both.
-1. **After planning, before the user sees the plan** — it checks the approach, the proposed names, file placement, and any planned backward-compat shims while they're still cheap to change.
-2. **After implementing, before finishing the turn** — it checks the working-tree diff, the OpenSpec artifacts, and the final response.
+Which review hooks exist, when they run and which model reviews are described in the docstring and comments of [`.agent-hooks/review_gate.py`](.agent-hooks/review_gate.py), the reviewer prompts in `.agent-hooks/*-prompt.md`, and the specs `openspec/specs/proposal-review` and `openspec/specs/implementation-review`.
-Hooks in [`.claude/settings.json`](.claude/settings.json) and [`.codex/hooks.json`](.codex/hooks.json) run both checkpoints through [`.agent-hooks/review_gate.py`](.agent-hooks/review_gate.py). It starts a separate read-only Claude Opus 5 process at low effort. That process reviews a plan before `ExitPlanMode` shows it to the user, and reviews the finished turn before the agent stops. A rejection comes back as feedback that starts with `AUTOMATIC REVIEW:`. Fix what it names. After three rejected revisions, or when the reviewer cannot run, the hook stops the agent and does not accept the result. Do not also invoke the `reviewer` subagent yourself while the hooks are active. The gate does not run linters, so run the linter for each directory the diff touches before finishing.
+What the agent does with findings:
-If hooks are disabled, invoke the `reviewer` subagent yourself at both checkpoints. It is read-only: it reports findings, you apply the fixes. Resolve every `CHANGES REQUIRED` finding before moving on.
+- A blocking finding is resolved by the agent itself, without asking the user, and then the agent finishes the turn again. It fixes the code, the documentation or the change's artifacts; when the implementation is right, it fixes the delta spec. A false finding is rejected with the reason in the response.
+- A `minor` finding is optional.
+- A `scope` finding proposes cutting the feature. The agent does not apply it; the summary shows the user what they lose and what they save, and the user decides.
+- Run the linter and formatter for each directory the diff touches before finishing.
-> At both checkpoints, the reviewer also applies [the how-to-communicate skill](.agents/skills/humanizer/SKILL.md) to every agent-authored response, plan, document, OpenSpec artifact, review finding, commit or pull request text, and code comment available in scope. Before editing a code comment, it first checks whether clearer naming or a smaller function can remove the comment. It flags removable comments instead of rewriting them. Editing must preserve facts, behavior, scope and technical meaning.
+### The best code is unwritten
+
+Before doing a task, check whether it is needed in this form. If the feature can be skipped or done much more simply, offer that to the user before implementing: what they lose and what they save.
+
+- Product: an existing feature, a manual process or an external service already covers the need; a narrower option covers the same need; a setting, screen or scenario is rarely needed and costs more than it gives.
+- Code: what is needed already exists in the repository or its dependencies; a small refactoring lets existing code be reused instead of writing new code; the standard library or a ready tool is enough.
+
+The user decides; the task is never cut without their consent. Simplify code within the task yourself, and agree a large rework first per [Refactoring within a feature](#refactoring-within-a-feature).
+
+### Refactoring within a feature
+
+The system improves gradually, along with ordinary tasks. If code the task touches stands in the way of the task or breaks the rules of the module docs or an accepted ADR, the refactoring is part of the same task; no separate task for later. The refactoring is limited to the code the task works with and does not touch other agents' changes in the working tree. Agree a large rework that goes beyond the task with the user first.
+
+### Other agents' changes in the working tree
+
+Several agents sometimes work in one branch at once. A file or change the agent did not create within the current request belongs to someone else. Never delete, revert, format, stage or commit someone else's changes. If they must be moved aside with `git stash` before a commit, ask the user first.
### Naming
@@ -173,7 +191,7 @@ Don't preserve backward compatibility unless the user asks for it. No deprecatio
### Security
-Databasus handles sensitive data, so security is a layered defence. CodeQL, CodeRabbit, Codex Security, Trivy, Dependabot, gitleaks and semgrep all run on every PR. When working in the repo:
+Databasus handles sensitive data, so security is a layered defence. When working in the repo:
- Don't disable or weaken security checks to make a build pass. For genuine false positives, suppress explicitly with a documented reason (e.g. `.trivyignore`) and explain why in the PR.
- Pin every new GitHub Action to a full commit SHA with a `# vX.Y.Z` tag comment. No floating tags like `@v4` or `@main`.
@@ -183,6 +201,52 @@ Databasus handles sensitive data, so security is a layered defence. CodeQL, Code
The README's `🛡️ Security & reliability engineering` section is the public-facing version of these practices — keep both consistent if substance changes. That section, like the rest of `README.md`, exists in 6 languages: a substantive edit lands in the English file and in all five `assets/readme/README.<locale>.md` copies.
+---
+
+## Documentation consistency
+
+All project documentation agrees with itself and with the code: every `AGENTS.md`, `adr/`, `docs/`, the repository's own skills, the READMEs and code comments. OpenSpec specs and changes are outside this rule; the OpenSpec process keeps them consistent.
+
+When an edit in one place affects others, update every affected place in the same task: a renamed command, a changed rule, a new path, a different order of steps. Before handing the work over, search the repository for every mention of what changed and bring them in line.
+
+Agent instructions are the git-tracked `AGENTS.md` files and the repository's own skills under `.agents/skills`, that is every skill except the generated `openspec-*`. They hold principles and conventions that change how the agent behaves and outlive the next feature, not the implementation. An instruction changes when a rule changes, not when the code it points to changes. It may hold a table of documents with the topic of each, a table of commands with the purpose of each, the stack of a part, a link to a file as an example or a source of values, and one sentence saying that a linter enforces a rule.
+
+Everything else lives next to what it describes:
+
+| What | Where |
+|---|---|
+| Inventories of what exists: features, endpoints, checks, tools | the code, the generated API description, the program's README |
+| The state of the code, "currently" and "for now" statements about it | the code and its comments, `docs/` |
+| How a process, module, command or deployment works; helper signatures and options | the code and its comments, `docs/`, `README.md` |
+| Why an architectural choice was made | `adr/` |
+| How the review hooks work | the docstring and comments of `.agent-hooks/review_gate.py`, the prompts `.agent-hooks/*-prompt.md`, the specs `openspec/specs/implementation-review` and `openspec/specs/proposal-review` |
+| The sections of a document | the document itself |
+
+An ordinary feature does not change agent instructions. If a feature needs to, first check that what you add does not belong in the table above.
+
+One rule is written in one place. Other documents link to it instead of retelling it. If you find a contradiction between documents that is unrelated to the task, do not fix it silently: report it in the response.
+
+---
+
+## OpenSpec
+
+A request to write a spec, write up a change or write its artifacts goes through the `openspec-propose` skill, and an edit to a finished change through `openspec-update-change`. This way the change gets every artifact in OpenSpec format at once.
+
+### Discussing a task in explore
+
+When the agent works through a task with the user in `/opsx:explore` or the `openspec-explore` skill, it builds the answer from the essence to the mechanics:
+
+1. What needs to be done, without technical details: what problem exists now, what changes for the Databasus user or for the team, what is out of scope.
+2. How it works now. The agent explains the parts of the system the task touches in plain words. It introduces a feature, a service, a migration and other terms before their first use, following the [how-to-communicate skill](.agents/skills/humanizer/SKILL.md). It quotes no code without explaining it.
+3. How it will work: an ASCII diagram and a short step-by-step story.
+4. Decisions: each as a separate point with its reason and with what breaks under the other choice.
+5. How to tell the task is done: tests and observable signs.
+6. Which documents will change.
+
+The agent settles technical questions that have an optimal answer itself and explains the choice in point 4. It asks the user only about what the user decides: the size of the feature, product rules, cutting the task per [The best code is unwritten](#the-best-code-is-unwritten). The question goes at the end of the answer, one at a time.
+
+---
+
## Committing
Follow the [Git commits skill](.agents/skills/git-commits/SKILL.md) for commit messages and branch names.
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/.openspec.yaml b/openspec/changes/archive/2026-10-10-port-review-gates/.openspec.yaml
new file mode 100644
index 00000000..53f62d70
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-10-10
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/design.md b/openspec/changes/archive/2026-10-10-port-review-gates/design.md
new file mode 100644
index 00000000..1e525c94
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/design.md
@@ -0,0 +1,66 @@
+## Context
+
+See proposal.md for the motivation and the three delta specs for the behavior contract.
+
+Today the hook script has four actions: `snapshot`, `plan-gate`, `claude` and `codex` (`.agent-hooks/review_gate.py:373-391`). Every review runs `claude-opus-5` at low effort with one prompt, `.agent-hooks/review-prompt.md`, which delegates the path-to-doc mapping and the most-violated rules to `.claude/agents/reviewer.md`. Codex turns are reviewed by Claude too (`review_gate.py:210-256`). The state lives under the git directory in `agent-review-hooks/<session>.json` (`review_gate.py:112-118`), so worktrees keep separate state.
+
+The sibling project's gate script is the source of this change. Its structure carries over unchanged: a request snapshot with workspace fingerprint and per-file hashes, one state file per gate, per-change state for the full reviews, and quick gates that skip a turn which only wrote a finished proposal.
+
+Constraints from the root [`AGENTS.md`](../../../AGENTS.md): English in every committed file, no backward compatibility the user did not ask for, and several agents sharing one working tree and one set of test containers.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Each gate reviews one concern with a prompt that names its standard.
+- A finished proposal and a finished implementation are each reviewed once as a whole, in parallel by role, with a repeat pass that checks only the previous findings.
+- The hook never modifies the working tree.
+
+**Non-Goals:**
+
+- Faster reviews. The full reviews add minutes to the turn that finishes a change, by design.
+- A hook-level test run.
+
+## Decisions
+
+### Port the sibling script whole and adapt only project facts
+
+The script is taken as is and translated. The adapted parts are the communication skill path, the code directories that trigger the naming gate, and the check commands of the implementation review.
+
+Rejected: extending the current script gate by gate. The sibling script already has tests for the interactions between gates, such as quick gates yielding to the proposal review and the necessity gate ignoring fixes to a change under review. Re-deriving those would repeat the work and its bugs.
+
+### Models and reasoning effort match the sibling project exactly
+
+Quick gates run `opus` at `low` effort on Claude and `gpt-6.1-sol` at `low` on Codex. Both full reviews run `opus` at `medium` on Claude and `gpt-6.1-sol` at `high` on Codex. The current pinned `claude-opus-5` and `--max-turns 30` go away.
+
+Rejected: keeping Claude as the reviewer for Codex turns. The user chose the sibling project's setup, where each client reviews its own turns.
+
+### The implementation review runs read-only checks of the touched modules
+
+The check list is built from the paths changed relative to `HEAD`: `golangci-lint run` in `backend/` and in `agent/verification/`, `pnpm --dir frontend lint`, `npm --prefix website run lint` and `npm --prefix website run build`, and the hook unit tests through the hook's own Python interpreter when `.agent-hooks/` changed.
+
+Rejected: `make lint`, because it starts with `golangci-lint fmt` and would rewrite files while a parallel agent works in the same tree. Rejected: `make test`, because it removes every test container and recreates the slot databases that other agents use. Rejected: one fixed command list as in the sibling project, because this repository has no root command that lints every module.
+
+The hook tests run through `sys.executable` rather than `python3` from `PATH`. Under test, `PATH` holds stubs, and a stubbed `python3` would not be the interpreter the test expects.
+
+### The architecture gate reads the module docs and ADRs
+
+This repository has no single architecture document. The architecture prompt names the architectural sections of the module docs: file organization, controllers, dependency injection, background services, stored files and migrations for the backend, FSD for the frontend, file organization and background services for the verification agent. It adds the accepted ADRs in `adr/`.
+
+Rejected: writing a new architecture document first. That is a separate piece of documentation work with its own review, and the module docs already state the rules.
+
+### The reviewer subagent is deleted
+
+The hooks run the same audit on every turn. The subagent duplicated the rules in a third place, and its path-to-doc table moves into `common-prompt.md`.
+
+Rejected: keeping it for sessions with hooks disabled. The user chose to delete it.
+
+### The root `AGENTS.md` is cleaned in the same change
+
+The new `agent-instructions` requirement forbids inventories, statements about the current state of code and descriptions of tooling internals in agent instructions. The root `AGENTS.md` breaks it in a few places, starting with the hook paragraph this change rewrites anyway. Leaving them would make the diff gate reject this change.
+
+## Risks / Trade-offs
+
+- [Full reviews take minutes on the turn that finishes a change] → They run once per proposal and once per implementation, and an accepted state is remembered per change, so a new session does not repeat them.
+- [The Codex reviewer depends on the `codex` CLI and its model name] → A reviewer that cannot run never accepts the turn, so a broken setup is visible at once.
+- [Linters for the touched modules are slow on a large diff] → They run once per full review, not on every turn.
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/proposal.md b/openspec/changes/archive/2026-10-10-port-review-gates/proposal.md
new file mode 100644
index 00000000..a266a4f1
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/proposal.md
@@ -0,0 +1,46 @@
+## Why
+
+The review hooks run one reviewer that judges a plan or a finished turn against every rule at once (`.agent-hooks/review_gate.py:158-168`, `.agent-hooks/review-prompt.md`). A single low-effort pass over all rules misses whole classes of problems: nobody asks whether the task is needed in this form, architecture and naming get a line each among twenty other checks, and a finished OpenSpec proposal or implementation is never reviewed as a whole against its own specs. Those gaps surface later, when the user reviews the work in a new session.
+
+The sibling project the same team works in already splits this review into narrow gates with their own prompts, plus two full reviews of an OpenSpec change. It also has a rule for how an agent presents a task in explore mode, so that the user understands the problem before the details. This change brings both here.
+
+## Governing docs
+
+This change answers to the root [`AGENTS.md`](../../../AGENTS.md). It touches no code under `backend/`, `agent/`, `frontend/` or `website/`, so the module docs do not govern it. The hook prompts name every module doc, because the reviewers apply them to future changes.
+
+## What Changes
+
+- Replace the single reviewer with separate gates, each with its own prompt: `plan` (the plan solves the request at the right layer), `necessity` (whether the task is needed in this form, or something much smaller covers the same need), `architecture` (module architecture rules and accepted ADRs), `diff` (correctness, tests, documentation consistency), and `naming` (names the diff added or changed, run only when code changed).
+- Add the full proposal review. When every artifact of an active change is written and no task is checked, the hook runs `openspec validate --strict`, then parallel reviewers: one per delta spec, one for proposal and design, one for tasks.
+- Add the full implementation review. When every task of an active change is checked, the hook runs the read-only linters of the touched modules and the hook tests, then parallel reviewers: one per delta spec, one for documentation and tasks.
+- Add a session start hook that tells the agent to load the communication skill first.
+- Run the Codex reviewer on Codex itself instead of Claude.
+- Add sections to the root `AGENTS.md`: what the agent does with review findings, how it presents a task in explore mode, "The best code is unwritten", documentation consistency, refactoring within a feature, and other agents' changes in the working tree. Remove the parts of the root `AGENTS.md` that the new `agent-instructions` rule forbids: hook internals, inventories, port numbers and command internals.
+- **BREAKING** for anyone invoking the `reviewer` subagent: it is deleted. The hooks are the review now. Its path-to-doc table moves into the shared hook prompt and its website build check into the implementation review checks.
+
+### Out of scope
+
+- Upgrading the OpenSpec CLI or regenerating the OpenSpec skills.
+- Cleaning the module `AGENTS.md` files against the new `agent-instructions` rule. They are not edited here.
+- Running the hook tests in CI.
+- Running the Go test suites from the hook. `make test` resets the shared test containers and slows every turn, so tests stay with the agent, and the reviewers check its claims about them.
+
+## Capabilities
+
+### New Capabilities
+
+- `proposal-review`: the full review of a finished OpenSpec proposal before implementation.
+- `implementation-review`: the full review of a change whose tasks are all checked.
+- `agent-instructions`: what belongs in `AGENTS.md` and the repository's own skills, and how the diff reviewer enforces it.
+
+### Modified Capabilities
+
+None.
+
+## Impact
+
+- `.agent-hooks/`: the gate script, prompts, result schemas and new tests.
+- `.gitignore`: Python bytecode caches that running the hook tests leaves behind.
+- `.claude/settings.json`, `.codex/hooks.json`: new hook wiring.
+- `.claude/agents/reviewer.md`: deleted.
+- `AGENTS.md`, `openspec/config.yaml`: references to the reviewer subagent replaced, new sections.
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/specs/agent-instructions/spec.md b/openspec/changes/archive/2026-10-10-port-review-gates/specs/agent-instructions/spec.md
new file mode 100644
index 00000000..b43bb75c
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/specs/agent-instructions/spec.md
@@ -0,0 +1,47 @@
+## ADDED Requirements
+
+### Requirement: What belongs in agent instructions
+Agent instructions are the git-tracked `AGENTS.md` files at the repository root and in subdirectories, and the repository's own skills, that is every skill except the generated `openspec-*` skills. Agent instructions SHALL hold only rules that change how the agent behaves and do not depend on which features already exist. Agent instructions MUST NOT hold:
+
+- inventories of what already exists in the system: features, endpoints, checks, installed tools;
+- statements about the current state of code with words like "currently" and "for now", except the rule about how to write about the current state;
+- descriptions of how code, hooks and tools work: the internal steps of commands, hook trigger conditions, constant values, limits, models;
+- retellings of another document's sections.
+
+The root `AGENTS.md` SHALL name the place for each of these kinds of information: code and its comments, the API contract, `docs/`, the ADRs, a program's README, the hook docstring and prompts, the OpenSpec specs. An instruction MAY link to a file as an example or a source of values, when the link itself does not change with the file's contents. An instruction MAY hold:
+
+- a table of documents with the topic of each;
+- a table of commands the agent runs with the purpose of each, without its internal steps;
+- the stack of a part: language and main frameworks;
+- one sentence saying that a linter enforces a rule, without the list of its checks.
+
+#### Scenario: A feature adds an endpoint
+- **WHEN** a feature adds a backend endpoint
+- **THEN** neither `AGENTS.md` nor any module doc changes, and the endpoint is visible in the code and the generated API description
+
+#### Scenario: A module doc gets a new section
+- **WHEN** a change adds a section to `website/AGENTS.md`
+- **THEN** the `website/AGENTS.md` line in the root `AGENTS.md` does not change, because it names the doc's topic rather than its sections
+
+#### Scenario: A review hook changes
+- **WHEN** a review hook changes its trigger, model, effort or reviewer prompt
+- **THEN** the hook script, its prompt or its spec changes, and the root `AGENTS.md` does not
+
+#### Scenario: What the agent does with a finding category changes
+- **WHEN** what the agent does with a full review finding category changes, for example it stops blocking the turn
+- **THEN** the "Review hooks" section of the root `AGENTS.md` changes, because that is a rule of agent behavior
+
+#### Scenario: A new rule of agent behavior appears
+- **WHEN** the team introduces a rule that changes how the agent writes code or answers
+- **THEN** the rule is written in one place in the agent instructions, and other documents link to it
+
+### Requirement: The diff reviewer checks edits to agent instructions
+The diff reviewer SHALL check every edit to agent instructions against the requirement "What belongs in agent instructions". When an edit adds an inventory of what exists, a statement about the current state of code, a description of how something works or a retelling of another document, the reviewer SHALL reject the turn and name the place to move that information to. An edit that adds or changes a rule of agent behavior MUST NOT be rejected under this criterion.
+
+#### Scenario: An edit adds an inventory
+- **WHEN** the agent adds "the backend currently has features X and Y" to a module doc
+- **THEN** the diff reviewer rejects the turn and says that the state of the code is visible in the code
+
+#### Scenario: An edit adds a rule
+- **WHEN** the agent adds a rule that changes agent behavior to `AGENTS.md`
+- **THEN** the diff reviewer does not reject the turn under the instruction content criterion
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/specs/implementation-review/spec.md b/openspec/changes/archive/2026-10-10-port-review-gates/specs/implementation-review/spec.md
new file mode 100644
index 00000000..c9cdf0e5
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/specs/implementation-review/spec.md
@@ -0,0 +1,106 @@
+## ADDED Requirements
+
+### Requirement: The full implementation review starts after a change is implemented
+The hook that runs when the agent finishes a turn, in Claude Code and in Codex, SHALL start the full implementation review when all of these hold: every task of an active change is checked, the working tree changed during this turn, and its state differs from the last state the full implementation review accepted for this change. The accepted state SHALL be stored per change, not per session. The full implementation review MUST NOT start while a task is unchecked, in a turn that left the working tree unchanged, or in a turn whose request carries an OpenSpec planning command. Archived changes are not reviewed.
+
+#### Scenario: The agent checks the last task
+- **WHEN** the agent checks the last task of a change and finishes the turn
+- **THEN** the hook starts the full implementation review of that change
+
+#### Scenario: Tasks remain
+- **WHEN** a task of the change is unchecked and the agent finishes the turn
+- **THEN** the full implementation review does not start and only the quick checks run
+
+#### Scenario: A turn without changes
+- **WHEN** every task of the change is checked but the working tree did not change during the turn
+- **THEN** the full implementation review does not start
+
+#### Scenario: New session after acceptance
+- **WHEN** the full implementation review accepted a change in one session, and in a new session the agent finishes a turn with the working tree still in the accepted state
+- **THEN** the full implementation review does not start again
+
+#### Scenario: Edit after acceptance
+- **WHEN** after an accepted review the agent changes files and finishes the turn
+- **THEN** the full implementation review starts again
+
+### Requirement: Read-only checks of the touched modules run first
+Before starting reviewers the hook SHALL run the checks of every module the working tree changes relative to the last commit: the Go linter for the backend and for the verification agent, the linter for the frontend, the linter and the build for the website, and the hook tests when the hooks changed. The checks MUST NOT modify files, so formatters do not run. The hook MUST NOT run the backend test suites. When a check fails, the hook SHALL block the turn and pass the agent the command and the end of its output. Reviewers MUST NOT start in that case.
+
+#### Scenario: The backend linter fails
+- **WHEN** the change touches the backend and its linter fails
+- **THEN** the turn is blocked, the agent gets the end of the linter output, and no reviewer starts
+
+#### Scenario: Only the frontend changed
+- **WHEN** the change touches only the frontend
+- **THEN** the hook runs the frontend linter and no backend, agent or website check
+
+#### Scenario: The website changed
+- **WHEN** the change touches the website
+- **THEN** the hook runs both the website linter and the website build
+
+### Requirement: What the full implementation review checks
+The full implementation review SHALL run several read-only reviewers in parallel: one per delta spec of the change and one for documentation and the task list. The delta spec reviewer SHALL find the code and the test for every requirement and scenario, check that the test actually proves the scenario, check the design decisions against the code, and look for bugs. The documentation reviewer SHALL check that everything each task states was done, including its verification, and that documentation agrees with itself and with the code. The documentation reviewer SHALL also check edits to agent instructions made by the change against the requirement "What belongs in agent instructions" of the `agent-instructions` capability.
+
+#### Scenario: A scenario without a test
+- **WHEN** a delta spec scenario has no test, or its test passes without the described behavior
+- **THEN** the reviewer returns a `missing_test` finding with the path to the test or code
+
+#### Scenario: Documentation lags behind
+- **WHEN** the change adds an environment variable and the configuration documentation does not mention it
+- **THEN** the documentation reviewer returns a `docs` finding
+
+#### Scenario: The change retells a document in AGENTS.md
+- **WHEN** the change adds a list of a module doc's sections to the root `AGENTS.md`
+- **THEN** the documentation reviewer returns a `docs` finding that suggests naming the doc's topic instead
+
+#### Scenario: The change adds a rule to AGENTS.md
+- **WHEN** the change adds a rule to `AGENTS.md` that changes agent behavior and is written nowhere else
+- **THEN** the documentation reviewer returns no finding under the instruction content criterion
+
+### Requirement: Full review models
+The full review reviewers SHALL run on Opus with `medium` effort in Claude Code and on `gpt-6.1-sol` with `high` effort in Codex. The quick checks SHALL run on Opus with `low` effort in Claude Code and on `gpt-6.1-sol` with `low` effort in Codex.
+
+#### Scenario: Review in Codex
+- **WHEN** the full review starts from Codex
+- **THEN** the reviewers run on `gpt-6.1-sol` with `high` effort
+
+#### Scenario: Quick check in Claude Code
+- **WHEN** the diff check starts from Claude Code
+- **THEN** the reviewer runs on Opus with `low` effort
+
+### Requirement: Which findings block the turn
+A reviewer SHALL return findings, each with a category (`bug`, `spec_mismatch`, `missing_test`, `docs`, `minor`), a path and a description. The hook SHALL block the turn when at least one finding is not `minor`, and pass the agent every finding with `minor` marked optional. When the turn is not blocked, the user SHALL see the `minor` findings. The block text SHALL require the agent to resolve every finding without asking the user: fix the code or, when the implementation is right, the change's delta spec. With no findings or only `minor` ones, the review SHALL count as accepted. When the review accepts the change after at least one block within this user request, the hook SHALL block the turn once and ask the agent to write the user a summary of the whole implementation, including each review round, and pass the `minor` findings in that request.
+
+#### Scenario: Only minor findings
+- **WHEN** every finding is `minor`, and no earlier review in this request blocked the turn
+- **THEN** the state is stored as accepted and the user sees the findings
+
+#### Scenario: Accepted after fixes
+- **WHEN** a repeat review accepts a change the previous review blocked
+- **THEN** the hook blocks the turn once and asks the agent for a summary of the whole implementation, and the next turn without edits is not blocked
+
+#### Scenario: A bug is found
+- **WHEN** a reviewer returns a `bug` finding
+- **THEN** the turn is blocked, and the agent gets every finding with the instruction to resolve them itself
+
+#### Scenario: The reviewer cannot run
+- **WHEN** the reviewer process crashes or times out
+- **THEN** the review is not accepted and the agent gets the failure reason
+
+### Requirement: Repeat review after fixes
+After a blocked full review the next run SHALL check the previous findings and the files changed after that review, not the whole change again. The repeat SHALL run on the same models. There SHALL be at most two repeats per user request, after which the hook SHALL stop the agent and show the remaining findings.
+
+#### Scenario: Findings are fixed
+- **WHEN** the agent fixed every finding of the previous review and finishes the turn
+- **THEN** the repeat review checks the previous findings and the new edits and accepts the change
+
+#### Scenario: Repeat limit
+- **WHEN** the third review in a row within one user request blocks the turn again
+- **THEN** the hook stops the agent and shows the remaining findings
+
+### Requirement: The necessity check does not interfere with fixes
+While a change has an unaccepted full implementation review, the necessity check MUST NOT start because of edits to that change's artifacts.
+
+#### Scenario: The agent fixes a delta spec after a finding
+- **WHEN** after a `spec_mismatch` finding the agent edits the change's delta spec and finishes the turn
+- **THEN** the necessity check does not start, and the full review checks the edit
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/specs/proposal-review/spec.md b/openspec/changes/archive/2026-10-10-port-review-gates/specs/proposal-review/spec.md
new file mode 100644
index 00000000..068e44c5
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/specs/proposal-review/spec.md
@@ -0,0 +1,81 @@
+## ADDED Requirements
+
+### Requirement: The full proposal review starts once the proposal is written
+The hook that runs when the agent finishes a turn, in Claude Code and in Codex, SHALL start the full proposal review of an active change when all of these hold: the change has every artifact its schema requires, its task list has tasks and none is checked, the change's files changed during this turn, and their state differs from the last state the full proposal review accepted for this change. The turn SHALL be recognized by the change's files, not by the request text: whether the agent started through a command, a skill or a plain request MUST NOT matter. The accepted state SHALL be stored per change, not per session. Archived changes are not reviewed.
+
+#### Scenario: The agent writes every artifact after a plain request
+- **WHEN** the user writes "write a spec for this", and the agent creates the proposal, design, delta specs and tasks and finishes the turn
+- **THEN** the hook starts the full proposal review of that change
+
+#### Scenario: Artifacts are not finished
+- **WHEN** a change has a proposal but no tasks, and the agent finishes the turn
+- **THEN** the full proposal review does not start and the quick checks run
+
+#### Scenario: Implementation has started
+- **WHEN** at least one task of the change is checked, and the agent edits a delta spec
+- **THEN** the full proposal review does not start
+
+#### Scenario: New session without edits
+- **WHEN** the full proposal review accepted a proposal in one session, and in a new session the agent finishes a turn without touching the change's files
+- **THEN** the full proposal review does not start
+
+#### Scenario: Edit after acceptance
+- **WHEN** after an accepted review the agent edits the design of a change whose tasks are not started
+- **THEN** the full proposal review starts again
+
+### Requirement: OpenSpec validation runs first
+Before starting reviewers the hook SHALL run strict OpenSpec validation of the change. When validation fails, the hook SHALL block the turn and pass the agent the end of its output. Reviewers MUST NOT start in that case.
+
+#### Scenario: A requirement without a scenario
+- **WHEN** a delta spec has a requirement without a scenario and validation fails
+- **THEN** the turn is blocked, the agent gets the validation output, and no reviewer starts
+
+### Requirement: What the full proposal review checks
+The full proposal review SHALL run several read-only reviewers in parallel, on the same models as the full implementation review: one per delta spec of the change, one for the proposal and design, and one for the task list.
+
+The delta spec reviewer SHALL check that requirements are complete and testable, do not contradict the main specs, the proposal or the design, and that claims about existing code are true. The proposal and design reviewer SHALL look for a noticeably simpler way to reach the same result, following the repository rule that the best code is unwritten, check the design decisions against the module architecture rules and accepted ADRs, and check that decisions agree with each other. The task reviewer SHALL check that a task with a test covers every scenario, that every task has a verification, and that the task order is feasible.
+
+#### Scenario: A change with two delta specs
+- **WHEN** the full proposal review starts for a change with two delta specs
+- **THEN** the hook starts four reviewers in parallel: one per delta spec, one for proposal and design, and one for tasks
+
+#### Scenario: The task reviewer's role
+- **WHEN** the hook starts the task reviewer
+- **THEN** its prompt names the role and requires checking that a task with a test covers every scenario, every task has a verification, and the task order is feasible
+
+### Requirement: The agent resolves findings itself, except cutting the feature
+A reviewer SHALL return findings, each with a category, a path and a description. The categories are `gap` (a requirement is incomplete or a case is missing), `mismatch` (artifacts contradict each other, the main specs, the code or the architecture rules), `tasks` (a scenario without a task with a test, a task without verification, an infeasible order), `simplify` (the same result for the user, noticeably simpler), `scope` (an option that cuts the feature) and `minor`. The hook SHALL block the turn when there is a `gap`, `mismatch`, `tasks` or `simplify` finding, and require the agent to resolve each one without asking the user. `scope` and `minor` findings MUST NOT block the turn. The agent MUST NOT apply a `scope` finding itself: cutting the task is the user's decision.
+
+#### Scenario: A simplification without loss
+- **WHEN** a reviewer finds that a field in an existing table replaces a new table, and the user loses nothing
+- **THEN** the turn is blocked, and the agent gets the finding with the instruction to resolve it without asking the user
+
+#### Scenario: A proposal to cut the feature
+- **WHEN** a reviewer returns only a `scope` finding saying the settings screen can be dropped
+- **THEN** the hook does not require a fix and once asks the agent for a summary that shows this option to the user
+
+### Requirement: Repeat and summary of the full proposal review
+After a blocked review the next run SHALL check the previous findings and the change's files that changed after that review, not the whole proposal again. There SHALL be at most two repeats per user request, after which the hook SHALL stop the agent and show the remaining findings. When the review accepts the proposal after at least one block in this request, or returns `scope` findings, the hook SHALL block the turn once and ask the agent to write the user a summary of the whole proposal: what is proposed, what each review round found and how it was resolved, and separately each option to cut the feature with what the user loses and saves. The next turn without edits to the change's files MUST NOT be blocked.
+
+#### Scenario: Accepted after fixes
+- **WHEN** a repeat review accepts a proposal the previous review blocked
+- **THEN** the hook once asks the agent for a summary of the whole proposal, and the next turn without edits is not blocked
+
+#### Scenario: Accepted at once without cuts
+- **WHEN** the first review returns only `minor` findings
+- **THEN** the turn is not blocked and the user sees the findings
+
+#### Scenario: Repeat limit
+- **WHEN** the third proposal review in a row within one user request blocks the turn again
+- **THEN** the hook stops the agent and shows the remaining findings
+
+### Requirement: Quick checks yield to the full proposal review
+When only files of changes that have every artifact and no checked task changed during the turn, the `necessity`, `architecture`, `diff` and `naming` checks SHALL skip the turn. This way the quick checks duplicate neither the review turn nor the summary turn after acceptance. When other files changed too, the quick checks SHALL run as usual.
+
+#### Scenario: A turn with only artifacts
+- **WHEN** the agent finished every artifact of a change and changed nothing else
+- **THEN** the quick checks skip the turn and only the full proposal review runs
+
+#### Scenario: An unfinished proposal
+- **WHEN** the agent wrote only the proposal and finishes the turn with a question to the user
+- **THEN** the full proposal review does not start, and the quick necessity check reviews the proposal
diff --git a/openspec/changes/archive/2026-10-10-port-review-gates/tasks.md b/openspec/changes/archive/2026-10-10-port-review-gates/tasks.md
new file mode 100644
index 00000000..473e513b
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-port-review-gates/tasks.md
@@ -0,0 +1,17 @@
+Hook tests run from the repository root with `python3 -m unittest discover -s .agent-hooks -p '*_test.py'`.
+
+## 1. Gate script and prompts
+
+- [x] 1.1 Replace `.agent-hooks/review_gate.py` with the sibling project's gate script, translated to English, with the communication skill path, the code directories `backend/`, `agent/`, `frontend/src/`, `website/` for the naming gate, the models and effort from design.md, and the implementation review checks built from the changed paths. Verify with `python3 -m py_compile .agent-hooks/review_gate.py`.
+- [x] 1.2 Add `common-prompt.md` with the path-to-doc table from `.claude/agents/reviewer.md`, and `plan-prompt.md`, `necessity-prompt.md`, `architecture-prompt.md`, `diff-prompt.md`, `naming-prompt.md`, `proposal-prompt.md`, `implementation-prompt.md`, each citing this repository's docs. Add `proposal-result.schema.json` and `implementation-result.schema.json`. Delete `review-prompt.md`. Verify with `grep -rn "docs/architecture.md\|glossary\|just \|review-prompt" .agent-hooks` returning nothing.
+- [x] 1.3 Port `review_gate_test.py`, with `make`, `pnpm`, `npm` and `golangci-lint` stubs instead of `just`, plus tests that a backend change runs only the backend linter, a website change runs lint and build, a failing linter blocks the turn with the end of its output, an `.agent-hooks` change runs the hook tests, and an `agent/` code change starts the naming gate. Verify with the hook test command.
+
+## 2. Hook wiring
+
+- [x] 2.1 Rewrite `.claude/settings.json` and `.codex/hooks.json` with every gate, the sibling project's hook timeouts and the worktree-safe script path. Verify with `python3 -m json.tool` on both files and with `echo '{"hook_event_name":"Stop","session_id":"manual-check","cwd":"'$PWD'"}' | python3 .agent-hooks/review_gate.py naming --client claude` printing `{}`.
+
+## 3. Agent instructions
+
+- [x] 3.1 Delete `.claude/agents/reviewer.md`.
+- [x] 3.2 In the root `AGENTS.md`, replace "Mandatory compliance review" with "Review hooks", add the sections "OpenSpec", "Discussing a task in explore", "The best code is unwritten", "Documentation consistency", "Refactoring within a feature" and "Other agents' changes in the working tree", and remove the inventories, port numbers, command internals and the list of security scanners. Verify with `grep -n "reviewer subagent\|reviewer.md\|Opus\|4005\|CodeQL" AGENTS.md` returning nothing.
+- [x] 3.3 Replace the reviewer subagent references in `openspec/config.yaml` with the review hooks and add the architecture grounding rule for design. Verify with `grep -n "reviewer" openspec/config.yaml` returning nothing and `openspec validate port-review-gates --strict` passing.
diff --git a/openspec/config.yaml b/openspec/config.yaml
index 587b3a64..fa69560c 100644
--- a/openspec/config.yaml
+++ b/openspec/config.yaml
@@ -29,8 +29,9 @@ context: |
booleans take is/can/has/should.
- Work happens inside the repo Dev Container. Commands are make (backend,
agent) and pnpm (frontend).
- - Every non-trivial change is audited by the reviewer subagent
- twice: after planning and after implementation.
+ - Review hooks gate plans, finished turns, full proposals and full
+ implementations. Resolve their findings as the "Review hooks" section
+ of AGENTS.md says.
rules:
proposal:
@@ -46,6 +47,7 @@ rules:
- Humanize all prose in embedded mode before writing the artifact.
- For each decision, name the alternatives rejected and why. A decision with no alternatives listed is a description, not a decision.
- Ground claims about current state in file:line references.
+ - Ground architecture decisions in the module AGENTS.md architecture rules and the accepted ADRs in adr/.
- Say which module AGENTS.md rules the approach is constrained by.
tasks:
- Humanize all prose in embedded mode before writing the artifact.
@@ -58,7 +60,7 @@ operations:
apply:
guidance:
- Run the linter for every directory the diff touches before finishing.
- - Run reviewer after planning and again before finishing the turn; resolve every CHANGES REQUIRED finding.
+ - Resolve every blocking review hook finding before finishing; never apply a scope finding without the user's consent.
- Never commit or push without explicit approval. No AI attribution trailers in commit messages.
archive:
guidance:
diff --git a/openspec/specs/agent-instructions/spec.md b/openspec/specs/agent-instructions/spec.md
new file mode 100644
index 00000000..c81795c0
--- /dev/null
+++ b/openspec/specs/agent-instructions/spec.md
@@ -0,0 +1,52 @@
+# agent-instructions Specification
+
+## Purpose
+Keeps `AGENTS.md` and the repository's own skills stable: they hold rules of agent behavior, while descriptions of the system, inventories of what exists and the internals of tools live next to what they describe. This way an ordinary feature does not edit these files, and parallel branches do not conflict in them.
+
+## Requirements
+
+### Requirement: What belongs in agent instructions
+Agent instructions are the git-tracked `AGENTS.md` files at the repository root and in subdirectories, and the repository's own skills, that is every skill except the generated `openspec-*` skills. Agent instructions SHALL hold only rules that change how the agent behaves and do not depend on which features already exist. Agent instructions MUST NOT hold:
+
+- inventories of what already exists in the system: features, endpoints, checks, installed tools;
+- statements about the current state of code with words like "currently" and "for now", except the rule about how to write about the current state;
+- descriptions of how code, hooks and tools work: the internal steps of commands, hook trigger conditions, constant values, limits, models;
+- retellings of another document's sections.
+
+The root `AGENTS.md` SHALL name the place for each of these kinds of information: code and its comments, the API contract, `docs/`, the ADRs, a program's README, the hook docstring and prompts, the OpenSpec specs. An instruction MAY link to a file as an example or a source of values, when the link itself does not change with the file's contents. An instruction MAY hold:
+
+- a table of documents with the topic of each;
+- a table of commands the agent runs with the purpose of each, without its internal steps;
+- the stack of a part: language and main frameworks;
+- one sentence saying that a linter enforces a rule, without the list of its checks.
+
+#### Scenario: A feature adds an endpoint
+- **WHEN** a feature adds a backend endpoint
+- **THEN** neither `AGENTS.md` nor any module doc changes, and the endpoint is visible in the code and the generated API description
+
+#### Scenario: A module doc gets a new section
+- **WHEN** a change adds a section to `website/AGENTS.md`
+- **THEN** the `website/AGENTS.md` line in the root `AGENTS.md` does not change, because it names the doc's topic rather than its sections
+
+#### Scenario: A review hook changes
+- **WHEN** a review hook changes its trigger, model, effort or reviewer prompt
+- **THEN** the hook script, its prompt or its spec changes, and the root `AGENTS.md` does not
+
+#### Scenario: What the agent does with a finding category changes
+- **WHEN** what the agent does with a full review finding category changes, for example it stops blocking the turn
+- **THEN** the "Review hooks" section of the root `AGENTS.md` changes, because that is a rule of agent behavior
+
+#### Scenario: A new rule of agent behavior appears
+- **WHEN** the team introduces a rule that changes how the agent writes code or answers
+- **THEN** the rule is written in one place in the agent instructions, and other documents link to it
+
+### Requirement: The diff reviewer checks edits to agent instructions
+The diff reviewer SHALL check every edit to agent instructions against the requirement "What belongs in agent instructions". When an edit adds an inventory of what exists, a statement about the current state of code, a description of how something works or a retelling of another document, the reviewer SHALL reject the turn and name the place to move that information to. An edit that adds or changes a rule of agent behavior MUST NOT be rejected under this criterion.
+
+#### Scenario: An edit adds an inventory
+- **WHEN** the agent adds "the backend currently has features X and Y" to a module doc
+- **THEN** the diff reviewer rejects the turn and says that the state of the code is visible in the code
+
+#### Scenario: An edit adds a rule
+- **WHEN** the agent adds a rule that changes agent behavior to `AGENTS.md`
+- **THEN** the diff reviewer does not reject the turn under the instruction content criterion
diff --git a/openspec/specs/implementation-review/spec.md b/openspec/specs/implementation-review/spec.md
new file mode 100644
index 00000000..0864d6de
--- /dev/null
+++ b/openspec/specs/implementation-review/spec.md
@@ -0,0 +1,111 @@
+# implementation-review Specification
+
+## Purpose
+Reviews the finished implementation of an OpenSpec change as a whole, so that bugs, mismatches with the spec and scenarios without tests are found by the hook rather than by the user in a separate review session.
+
+## Requirements
+
+### Requirement: The full implementation review starts after a change is implemented
+The hook that runs when the agent finishes a turn, in Claude Code and in Codex, SHALL start the full implementation review when all of these hold: every task of an active change is checked, the working tree changed during this turn, and its state differs from the last state the full implementation review accepted for this change. The accepted state SHALL be stored per change, not per session. The full implementation review MUST NOT start while a task is unchecked, in a turn that left the working tree unchanged, or in a turn whose request carries an OpenSpec planning command. Archived changes are not reviewed.
+
+#### Scenario: The agent checks the last task
+- **WHEN** the agent checks the last task of a change and finishes the turn
+- **THEN** the hook starts the full implementation review of that change
+
+#### Scenario: Tasks remain
+- **WHEN** a task of the change is unchecked and the agent finishes the turn
+- **THEN** the full implementation review does not start and only the quick checks run
+
+#### Scenario: A turn without changes
+- **WHEN** every task of the change is checked but the working tree did not change during the turn
+- **THEN** the full implementation review does not start
+
+#### Scenario: New session after acceptance
+- **WHEN** the full implementation review accepted a change in one session, and in a new session the agent finishes a turn with the working tree still in the accepted state
+- **THEN** the full implementation review does not start again
+
+#### Scenario: Edit after acceptance
+- **WHEN** after an accepted review the agent changes files and finishes the turn
+- **THEN** the full implementation review starts again
+
+### Requirement: Read-only checks of the touched modules run first
+Before starting reviewers the hook SHALL run the checks of every module the working tree changes relative to the last commit: the Go linter for the backend and for the verification agent, the linter for the frontend, the linter and the build for the website, and the hook tests when the hooks changed. The checks MUST NOT modify files, so formatters do not run. The hook MUST NOT run the backend test suites. When a check fails, the hook SHALL block the turn and pass the agent the command and the end of its output. Reviewers MUST NOT start in that case.
+
+#### Scenario: The backend linter fails
+- **WHEN** the change touches the backend and its linter fails
+- **THEN** the turn is blocked, the agent gets the end of the linter output, and no reviewer starts
+
+#### Scenario: Only the frontend changed
+- **WHEN** the change touches only the frontend
+- **THEN** the hook runs the frontend linter and no backend, agent or website check
+
+#### Scenario: The website changed
+- **WHEN** the change touches the website
+- **THEN** the hook runs both the website linter and the website build
+
+### Requirement: What the full implementation review checks
+The full implementation review SHALL run several read-only reviewers in parallel: one per delta spec of the change and one for documentation and the task list. The delta spec reviewer SHALL find the code and the test for every requirement and scenario, check that the test actually proves the scenario, check the design decisions against the code, and look for bugs. The documentation reviewer SHALL check that everything each task states was done, including its verification, and that documentation agrees with itself and with the code. The documentation reviewer SHALL also check edits to agent instructions made by the change against the requirement "What belongs in agent instructions" of the `agent-instructions` capability.
+
+#### Scenario: A scenario without a test
+- **WHEN** a delta spec scenario has no test, or its test passes without the described behavior
+- **THEN** the reviewer returns a `missing_test` finding with the path to the test or code
+
+#### Scenario: Documentation lags behind
+- **WHEN** the change adds an environment variable and the configuration documentation does not mention it
+- **THEN** the documentation reviewer returns a `docs` finding
+
+#### Scenario: The change retells a document in AGENTS.md
+- **WHEN** the change adds a list of a module doc's sections to the root `AGENTS.md`
+- **THEN** the documentation reviewer returns a `docs` finding that suggests naming the doc's topic instead
+
+#### Scenario: The change adds a rule to AGENTS.md
+- **WHEN** the change adds a rule to `AGENTS.md` that changes agent behavior and is written nowhere else
+- **THEN** the documentation reviewer returns no finding under the instruction content criterion
+
+### Requirement: Full review models
+The full review reviewers SHALL run on Opus with `medium` effort in Claude Code and on `gpt-6.1-sol` with `high` effort in Codex. The quick checks SHALL run on Opus with `low` effort in Claude Code and on `gpt-6.1-sol` with `low` effort in Codex.
+
+#### Scenario: Review in Codex
+- **WHEN** the full review starts from Codex
+- **THEN** the reviewers run on `gpt-6.1-sol` with `high` effort
+
+#### Scenario: Quick check in Claude Code
+- **WHEN** the diff check starts from Claude Code
+- **THEN** the reviewer runs on Opus with `low` effort
+
+### Requirement: Which findings block the turn
+A reviewer SHALL return findings, each with a category (`bug`, `spec_mismatch`, `missing_test`, `docs`, `minor`), a path and a description. The hook SHALL block the turn when at least one finding is not `minor`, and pass the agent every finding with `minor` marked optional. When the turn is not blocked, the user SHALL see the `minor` findings. The block text SHALL require the agent to resolve every finding without asking the user: fix the code or, when the implementation is right, the change's delta spec. With no findings or only `minor` ones, the review SHALL count as accepted. When the review accepts the change after at least one block within this user request, the hook SHALL block the turn once and ask the agent to write the user a summary of the whole implementation, including each review round, and pass the `minor` findings in that request.
+
+#### Scenario: Only minor findings
+- **WHEN** every finding is `minor`, and no earlier review in this request blocked the turn
+- **THEN** the state is stored as accepted and the user sees the findings
+
+#### Scenario: Accepted after fixes
+- **WHEN** a repeat review accepts a change the previous review blocked
+- **THEN** the hook blocks the turn once and asks the agent for a summary of the whole implementation, and the next turn without edits is not blocked
+
+#### Scenario: A bug is found
+- **WHEN** a reviewer returns a `bug` finding
+- **THEN** the turn is blocked, and the agent gets every finding with the instruction to resolve them itself
+
+#### Scenario: The reviewer cannot run
+- **WHEN** the reviewer process crashes or times out
+- **THEN** the review is not accepted and the agent gets the failure reason
+
+### Requirement: Repeat review after fixes
+After a blocked full review the next run SHALL check the previous findings and the files changed after that review, not the whole change again. The repeat SHALL run on the same models. There SHALL be at most two repeats per user request, after which the hook SHALL stop the agent and show the remaining findings.
+
+#### Scenario: Findings are fixed
+- **WHEN** the agent fixed every finding of the previous review and finishes the turn
+- **THEN** the repeat review checks the previous findings and the new edits and accepts the change
+
+#### Scenario: Repeat limit
+- **WHEN** the third review in a row within one user request blocks the turn again
+- **THEN** the hook stops the agent and shows the remaining findings
+
+### Requirement: The necessity check does not interfere with fixes
+While a change has an unaccepted full implementation review, the necessity check MUST NOT start because of edits to that change's artifacts.
+
+#### Scenario: The agent fixes a delta spec after a finding
+- **WHEN** after a `spec_mismatch` finding the agent edits the change's delta spec and finishes the turn
+- **THEN** the necessity check does not start, and the full review checks the edit
diff --git a/openspec/specs/proposal-review/spec.md b/openspec/specs/proposal-review/spec.md
new file mode 100644
index 00000000..f7af1e33
--- /dev/null
+++ b/openspec/specs/proposal-review/spec.md
@@ -0,0 +1,86 @@
+# proposal-review Specification
+
+## Purpose
+Reviews a finished OpenSpec proposal as a whole before implementation, so that gaps in requirements, contradictions between artifacts and needless complexity are found before code is written against them.
+
+## Requirements
+
+### Requirement: The full proposal review starts once the proposal is written
+The hook that runs when the agent finishes a turn, in Claude Code and in Codex, SHALL start the full proposal review of an active change when all of these hold: the change has every artifact its schema requires, its task list has tasks and none is checked, the change's files changed during this turn, and their state differs from the last state the full proposal review accepted for this change. The turn SHALL be recognized by the change's files, not by the request text: whether the agent started through a command, a skill or a plain request MUST NOT matter. The accepted state SHALL be stored per change, not per session. Archived changes are not reviewed.
+
+#### Scenario: The agent writes every artifact after a plain request
+- **WHEN** the user writes "write a spec for this", and the agent creates the proposal, design, delta specs and tasks and finishes the turn
+- **THEN** the hook starts the full proposal review of that change
+
+#### Scenario: Artifacts are not finished
+- **WHEN** a change has a proposal but no tasks, and the agent finishes the turn
+- **THEN** the full proposal review does not start and the quick checks run
+
+#### Scenario: Implementation has started
+- **WHEN** at least one task of the change is checked, and the agent edits a delta spec
+- **THEN** the full proposal review does not start
+
+#### Scenario: New session without edits
+- **WHEN** the full proposal review accepted a proposal in one session, and in a new session the agent finishes a turn without touching the change's files
+- **THEN** the full proposal review does not start
+
+#### Scenario: Edit after acceptance
+- **WHEN** after an accepted review the agent edits the design of a change whose tasks are not started
+- **THEN** the full proposal review starts again
+
+### Requirement: OpenSpec validation runs first
+Before starting reviewers the hook SHALL run strict OpenSpec validation of the change. When validation fails, the hook SHALL block the turn and pass the agent the end of its output. Reviewers MUST NOT start in that case.
+
+#### Scenario: A requirement without a scenario
+- **WHEN** a delta spec has a requirement without a scenario and validation fails
+- **THEN** the turn is blocked, the agent gets the validation output, and no reviewer starts
+
+### Requirement: What the full proposal review checks
+The full proposal review SHALL run several read-only reviewers in parallel, on the same models as the full implementation review: one per delta spec of the change, one for the proposal and design, and one for the task list.
+
+The delta spec reviewer SHALL check that requirements are complete and testable, do not contradict the main specs, the proposal or the design, and that claims about existing code are true. The proposal and design reviewer SHALL look for a noticeably simpler way to reach the same result, following the repository rule that the best code is unwritten, check the design decisions against the module architecture rules and accepted ADRs, and check that decisions agree with each other. The task reviewer SHALL check that a task with a test covers every scenario, that every task has a verification, and that the task order is feasible.
+
+#### Scenario: A change with two delta specs
+- **WHEN** the full proposal review starts for a change with two delta specs
+- **THEN** the hook starts four reviewers in parallel: one per delta spec, one for proposal and design, and one for tasks
+
+#### Scenario: The task reviewer's role
+- **WHEN** the hook starts the task reviewer
+- **THEN** its prompt names the role and requires checking that a task with a test covers every scenario, every task has a verification, and the task order is feasible
+
+### Requirement: The agent resolves findings itself, except cutting the feature
+A reviewer SHALL return findings, each with a category, a path and a description. The categories are `gap` (a requirement is incomplete or a case is missing), `mismatch` (artifacts contradict each other, the main specs, the code or the architecture rules), `tasks` (a scenario without a task with a test, a task without verification, an infeasible order), `simplify` (the same result for the user, noticeably simpler), `scope` (an option that cuts the feature) and `minor`. The hook SHALL block the turn when there is a `gap`, `mismatch`, `tasks` or `simplify` finding, and require the agent to resolve each one without asking the user. `scope` and `minor` findings MUST NOT block the turn. The agent MUST NOT apply a `scope` finding itself: cutting the task is the user's decision.
+
+#### Scenario: A simplification without loss
+- **WHEN** a reviewer finds that a field in an existing table replaces a new table, and the user loses nothing
+- **THEN** the turn is blocked, and the agent gets the finding with the instruction to resolve it without asking the user
+
+#### Scenario: A proposal to cut the feature
+- **WHEN** a reviewer returns only a `scope` finding saying the settings screen can be dropped
+- **THEN** the hook does not require a fix and once asks the agent for a summary that shows this option to the user
+
+### Requirement: Repeat and summary of the full proposal review
+After a blocked review the next run SHALL check the previous findings and the change's files that changed after that review, not the whole proposal again. There SHALL be at most two repeats per user request, after which the hook SHALL stop the agent and show the remaining findings. When the review accepts the proposal after at least one block in this request, or returns `scope` findings, the hook SHALL block the turn once and ask the agent to write the user a summary of the whole proposal: what is proposed, what each review round found and how it was resolved, and separately each option to cut the feature with what the user loses and saves. The next turn without edits to the change's files MUST NOT be blocked.
+
+#### Scenario: Accepted after fixes
+- **WHEN** a repeat review accepts a proposal the previous review blocked
+- **THEN** the hook once asks the agent for a summary of the whole proposal, and the next turn without edits is not blocked
+
+#### Scenario: Accepted at once without cuts
+- **WHEN** the first review returns only `minor` findings
+- **THEN** the turn is not blocked and the user sees the findings
+
+#### Scenario: Repeat limit
+- **WHEN** the third proposal review in a row within one user request blocks the turn again
+- **THEN** the hook stops the agent and shows the remaining findings
+
+### Requirement: Quick checks yield to the full proposal review
+When only files of changes that have every artifact and no checked task changed during the turn, the `necessity`, `architecture`, `diff` and `naming` checks SHALL skip the turn. This way the quick checks duplicate neither the review turn nor the summary turn after acceptance. When other files changed too, the quick checks SHALL run as usual.
+
+#### Scenario: A turn with only artifacts
+- **WHEN** the agent finished every artifact of a change and changed nothing else
+- **THEN** the quick checks skip the turn and only the full proposal review runs
+
+#### Scenario: An unfinished proposal
+- **WHEN** the agent wrote only the proposal and finishes the turn with a question to the user
+- **THEN** the full proposal review does not start, and the quick necessity check reviews the proposal