PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
REFACTOR (agents): Gate plans and changes with an independent Opus review
Rostislav Dugin691bb95d0c2c
diff --git a/.agent-hooks/review-prompt.md b/.agent-hooks/review-prompt.mdnew file mode 100644index 00000000..ec163b33--- /dev/null+++ b/.agent-hooks/review-prompt.md@@ -0,0 +1,28 @@+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-result.schema.json b/.agent-hooks/review-result.schema.jsonnew file mode 100644index 00000000..bdf6e3f6--- /dev/null+++ b/.agent-hooks/review-result.schema.json@@ -0,0 +1,13 @@+{+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ },+ "reason": {+ "type": "string"+ }+ },+ "required": ["ok", "reason"],+ "additionalProperties": false+}diff --git a/.agent-hooks/review_gate.py b/.agent-hooks/review_gate.pynew file mode 100755index 00000000..7674ea90--- /dev/null+++ b/.agent-hooks/review_gate.py@@ -0,0 +1,395 @@+#!/usr/bin/env python3+"""Review gate shared by the Claude Code and Codex hooks.++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.++Every review runs a separate read-only Claude process. A failed review is never accepted.+"""++import hashlib+import json+import os+from pathlib import Path+import re+import subprocess+import sys+++AUTOMATIC_REVIEW_PREFIX = "AUTOMATIC REVIEW:"+MAX_REVISIONS = 3+REVIEW_TIMEOUT_SECONDS = 540+REVIEWER_MODEL = "claude-opus-5"+REVIEWER_EFFORT = "low"+REVIEWER_ACTIVE_ENV = "AGENT_REVIEW_HOOK_ACTIVE"+EXPLICIT_PLANNING_COMMANDS = (+ "/opsx:propose",+ "/opsx:update",+ "$openspec-propose",+ "$openspec-update-change",+)+++def read_payload():+ try:+ value = json.load(sys.stdin)+ except (json.JSONDecodeError, OSError):+ return {}+ return value if isinstance(value, dict) else {}+++def emit(value):+ json.dump(value, sys.stdout, ensure_ascii=False)+ sys.stdout.write("\n")+++def run_git(root, *args):+ return subprocess.run(+ ["git", *args],+ cwd=root,+ check=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ ).stdout+++def find_root(payload):+ cwd = Path(payload.get("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+++def get_untracked_paths(root):+ try:+ output = run_git(root, "ls-files", "--others", "--exclude-standard", "-z")+ except (OSError, subprocess.CalledProcessError):+ return []+ return [path for path in output.decode(errors="replace").split("\0") if path]+++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+ return sorted(paths)+++def get_workspace_fingerprint(root):+ digest = hashlib.sha256()+ try:+ digest.update(run_git(root, "rev-parse", "HEAD"))+ digest.update(run_git(root, "diff", "--binary", "HEAD", "--"))+ except (OSError, subprocess.CalledProcessError):+ digest.update(run_git(root, "diff", "--binary", "--cached", "--"))+ digest.update(run_git(root, "diff", "--binary", "--"))++ for relative_path in get_untracked_paths(root):+ path = root / relative_path+ 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):+ 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"))+ 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"+++def load_state(path):+ try:+ value = json.loads(path.read_text())+ except (OSError, json.JSONDecodeError):+ return {}+ return value if isinstance(value, dict) else {}+++def save_state(path, state):+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_suffix(".tmp")+ temporary.write_text(json.dumps(state, ensure_ascii=False))+ 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):+ return+ save_state(+ state_path,+ {+ "baseline": get_workspace_fingerprint(root),+ "baseline_paths": get_changed_paths(root),+ "blocks": 0,+ "plan_blocks": 0,+ "is_accepted": False,+ "prompt": prompt,+ },+ )+++def is_planning_request(prompt):+ lowered = prompt.lower()+ return any(command in lowered for command in EXPLICIT_PLANNING_COMMANDS)+++def get_stop_review_mode(payload, state, paths):+ if payload.get("permission_mode") == "plan":+ return "planning"++ if is_planning_request(str(state.get("prompt") or "")):+ return "planning"++ 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 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"+ return f"""{instructions}++Review mode: {mode}+Repository root: {root}++Latest user request:+<user_request>+{original_prompt}+</user_request>++Candidate:+<candidate>+{candidate}+</candidate>++Paths that already had changes before this request:+{baseline_path_list}++Currently changed paths:+{path_list}+"""+++def parse_review_result(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")+ if not isinstance(value.get("ok"), bool) or not isinstance(value.get("reason"), str):+ raise ValueError("reviewer result does not match the required schema")+ return value+++def run_reviewer(root, prompt):+ schema = (Path(__file__).parent / "review-result.schema.json").read_text()+ command = [+ "claude",+ "--print",+ "--model",+ REVIEWER_MODEL,+ "--effort",+ REVIEWER_EFFORT,+ "--permission-mode",+ "plan",+ # The reviewer loads this repository's hooks too; its own stop 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",+ "--no-session-persistence",+ "--prompt-suggestions",+ "false",+ "--output-format",+ "json",+ "--json-schema",+ schema,+ ]+ 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)+ process = subprocess.run(+ command,+ cwd=root,+ input=prompt,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ env=environment,+ timeout=REVIEW_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)+++def review(root, prompt):+ """Returns (is_accepted, reason). A reviewer that could not run never accepts."""+ try:+ result = run_reviewer(root, prompt)+ 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}"++ 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 {})+ if plan:+ prompt = build_review_prompt(root, state, "plan", plan, get_changed_paths(root))+ is_accepted, reason = review(root, prompt)+ 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)+ 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:+ 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.",+ }+ )+ return+ emit(+ {+ "hookSpecificOutput": {+ "hookEventName": "PreToolUse",+ "permissionDecision": "deny",+ "permissionDecisionReason": f"{AUTOMATIC_REVIEW_PREFIX}\n{reason}\nRevise the plan and call ExitPlanMode again.",+ }+ }+ )+++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 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):+ 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)++ if is_accepted:+ state.update({"baseline": fingerprint, "blocks": 0, "is_accepted": True})+ save_state(state_path, state)+ emit({})+ return++ blocks = int(state.get("blocks") or 0) + 1+ state["blocks"] = blocks+ save_state(state_path, state)+ 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.",+ }+ )+ return+ emit(+ {+ "decision": "block",+ "reason": f"{AUTOMATIC_REVIEW_PREFIX}\n{reason}\nFix the result, update OpenSpec when requested, and finish with another review.",+ }+ )+++def main():+ payload = read_payload()+ if os.environ.get(REVIEWER_ACTIVE_ENV) == "1":+ emit({})+ 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)+ return+ if action == "plan-gate":+ gate_plan(payload, root, state_path)+ return+ if action in {"claude", "codex"}:+ gate_stop(action, payload, root, state_path)+ return+ emit({"continue": False, "stopReason": f"Unknown review hook action: {action}"})+++if __name__ == "__main__":+ main()diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.mdindex 52a0b59b..d1e32721 100644--- a/.claude/agents/reviewer.md+++ b/.claude/agents/reviewer.md@@ -1,6 +1,6 @@---name: reviewer-description: Audits a plan or a working-tree diff against the repo's AGENTS.md standards. Invoke after producing an implementation plan and again after finishing an implementation.+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---diff --git a/.claude/hooks/require-stop-review.sh b/.claude/hooks/require-stop-review.shdeleted file mode 100755index ecd80686..00000000--- a/.claude/hooks/require-stop-review.sh+++ /dev/null@@ -1,55 +0,0 @@-#!/usr/bin/env bash-# Stop hook: blocks once per distinct working-tree state until the review round named by $1 has run.-#-# usage: require-stop-review.sh <marker-prefix> <reason>-#-# Blocking is guarded by a marker file keyed on marker prefix + session id + a hash of the diff.-# Claude Code does not document a `stop_hook_active` field, so the marker is the only thing standing-# between this hook and an infinite stop loop. Any git failure exits 0 — never block on a broken repo.-#-# Several rounds can share this script: each gets its own marker prefix, so they block together on-# the same tree state and clear together, costing one stop round rather than one per round.--set -uo pipefail--REVIEWED_PATHS=(.)--marker_prefix=${1:-}-reason=${2:-}-[ -n "$marker_prefix" ] || exit 0-[ -n "$reason" ] || exit 0--hook_input=$(cat)--project_dir=${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null)} || exit 0-[ -n "$project_dir" ] || exit 0-cd "$project_dir" 2>/dev/null || exit 0--git rev-parse --verify HEAD >/dev/null 2>&1 || exit 0--changed_paths=$(git status --porcelain -- "${REVIEWED_PATHS[@]}" 2>/dev/null) || exit 0-[ -n "$changed_paths" ] || exit 0--# `git diff` omits untracked files, so hash their contents separately. Without this an edit to a-# newly created file would not change the hash, and its review round would be silently skipped.-tree_hash=$(- {- git diff HEAD -- "${REVIEWED_PATHS[@]}" 2>/dev/null- git ls-files --others --exclude-standard -z -- "${REVIEWED_PATHS[@]}" 2>/dev/null |- xargs -0 -r sha256sum 2>/dev/null- } | sha256sum | cut -d' ' -f1-) || exit 0-[ -n "$tree_hash" ] || exit 0--session_id=$(printf '%s' "$hook_input" | jq -r '.session_id // "unknown"' 2>/dev/null)-session_id=${session_id//[^a-zA-Z0-9_-]/}-[ -n "$session_id" ] || session_id=unknown--marker_dir="${TMPDIR:-/tmp}/databasus-claude-review"-mkdir -p "$marker_dir" 2>/dev/null || exit 0-marker="$marker_dir/$marker_prefix-$session_id-$tree_hash"--[ -e "$marker" ] && exit 0-: >"$marker" 2>/dev/null || exit 0--jq -n --arg reason "$reason" '{decision: "block", reason: $reason}'diff --git a/.claude/settings.json b/.claude/settings.jsonindex 428816a7..b3ea19d9 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -1,26 +1,37 @@{"hooks": {- "PostToolUse": [+ "UserPromptSubmit": [{- "matcher": "ExitPlanMode","hooks": [{"type": "command",- "command": "jq -n '{hookSpecificOutput:{hookEventName:\"PostToolUse\",additionalContext:\"Before writing any code, invoke the reviewer subagent in plan mode on the approved plan file. Resolve every CHANGES REQUIRED finding before implementing. As part of the review, apply the repository how-to-communicate skill at .agents/skills/humanizer/SKILL.md to all agent-authored prose in scope. Check whether each code comment can be removed through clearer naming or a smaller function before editing it.\"}}'"+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot",+ "timeout": 10}]}],- "Stop": [+ "PreToolUse": [{+ "matcher": "ExitPlanMode","hooks": [{"type": "command",- "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-stop-review.sh\" compliance \"The working tree has unreviewed changes. Invoke the reviewer subagent in implementation mode, then resolve every CHANGES REQUIRED finding before stopping. As part of the review, apply the repository how-to-communicate skill at .agents/skills/humanizer/SKILL.md to all agent-authored prose in scope. Check whether each code comment can be removed through clearer naming or a smaller function before editing it. If it returns PASS, stop as normal.\""- },+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" plan-gate",+ "timeout": 600,+ "statusMessage": "Reviewing the plan"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [{"type": "command",- "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-stop-review.sh\" solution \"Re-audit the finished change end to end before stopping, with fresh eyes and no attachment to what you already built. Does it remove the root cause the user actually asked about, or only the symptom they happened to see? Would a reviewer who never saw the plan choose this approach, or a simpler or more complete one? Did the plan itself get something wrong — wrong layer, wrong scope, a case it never considered, a break it did not flag? Confirm every test and lint command you claimed actually ran and passed, and that new tests fail when the fix is reverted. If any of that does not hold, say so plainly and fix it, reworking the approach or replanning if that is what it takes — do not defend the implemented solution or narrow the scope to fit it. If the change holds up, stop as normal.\""+ "command": "python3 \"$(git -C \"${CLAUDE_PROJECT_DIR}\" rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" claude",+ "timeout": 600,+ "statusMessage": "Reviewing the plan and changes"}]}diff --git a/.codex/hooks.json b/.codex/hooks.jsonnew file mode 100644index 00000000..8bccfc8b--- /dev/null+++ b/.codex/hooks.json@@ -0,0 +1,28 @@+{+ "description": "Review plans and completed changes before Codex stops.",+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" snapshot",+ "timeout": 10+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "python3 \"$(git rev-parse --show-toplevel)/.agent-hooks/review_gate.py\" codex",+ "timeout": 600,+ "statusMessage": "Reviewing the plan and changes"+ }+ ]+ }+ ]+ }+}diff --git a/.gitignore b/.gitignoreindex c2b0f66b..55c9da65 100644--- a/.gitignore+++ b/.gitignore@@ -17,7 +17,6 @@ node_modules/.vscode/settings.json.claude/*!.claude/agents/-!.claude/hooks/!.claude/settings.jsonbackend/cleanup_test_db.exeplans/diff --git a/AGENTS.md b/AGENTS.mdindex f60ed655..4c57bde2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -67,12 +67,14 @@ Reread the diff with fresh eyes and **list** (don't silently apply) refactor sug### Mandatory compliance review-Every non-trivial change is audited twice by the [`reviewer`](.claude/agents/reviewer.md) subagent — 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.+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).-1. **After planning, before writing code** — it checks 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 and runs the linter for each directory the diff touches.+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.-The reviewer is read-only: it reports findings, you apply the fixes. Resolve every `CHANGES REQUIRED` finding before moving on. Hooks in [`.claude/settings.json`](.claude/settings.json) prompt for both checkpoints, but the obligation is this rule, not the hook — honour it if hooks are disabled.+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.++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.> 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.