Skip to main content
Glama
README.md
# review-gate

**Deterministic boundary & review gate for multi-model AI coding agents.**

`CLI` · `MCP Server` · `Pi Native Extension` · `3 Intent-Driven Skills` · `Zero-Build TypeScript (Node ≥ 24)` · `Windows / WSL / macOS / Linux`

> Stop unbounded plan/code review ping-pong, weak-implementer scope drift, and silent prompt-cache tax.  
> `review-gate` moves loop caps, Git-tree diff slicing, scope enforcement, and regression circuit breakers out of fragile prompts and into deterministic code — shared seamlessly across **Claude Code**, **Codex CLI**, **T3 Code**, and **Pi**.

---

## Why `review-gate`?

LLM-driven review loops fail predictably without hard code boundaries:
- **Diminishing returns & over-refinement**: quality gains peak in rounds 1–2; unbounded rounds introduce regressions and goalpost shifting.
- **Weak-refiner ping-pong**: letting a weaker model repeatedly guess at a stronger critic's complex feedback degrades code instead of fixing it.
- **Silent drift & tampering**: implementers weaken test assertions, tweak `package.json`, or ignore soft prompt limits.
- **Prompt-cache invalidation & client timeouts**: dynamic timestamps in prompt prefixes bust KV caches, and 2–4 minute deep reviews trip 60s MCP client timeouts.

`review-gate` solves all four with **one lightweight TypeScript core** storing tamper-resistant state inside `<git-dir>/agent-gate/` (no `.gitignore` edits, naturally isolated per `git worktree`).

---

## Two Governed Workflows

```mermaid
flowchart LR
  subgraph M1["Mode 1 · advisor_impl (Strong Plan/Advisor -> Weak Implementer)"]
    direction LR
    P1["Strong Init Contract"] --> W1["Weak Implements"]
    W1 --> S1["Git-Tree Scope Check"]
    S1 -->|"Repeated Fail / Conflict / Final Check"| A1["Strong Advisor (max 2 calls)"]
    A1 -->|"coach"| W1
    A1 -->|"amend_contract"| M1A["Orchestrator Amends"]
    A1 -->|"takeover_now / Same Fingerprint / Cap"| T1["TAKEOVER_REQUIRED"]
  end

  subgraph M2["Mode 2 · final_review (Single Model Impl -> Strong Final Review)"]
    direction LR
    P2["Init Spec + Verify Cmd"] --> I2["Implement + Pass verify_cmd"]
    I2 --> R1["Round 1 Full Diff Review"]
    R1 -->|"0 P0 + approve"| OK["APPROVED"]
    R1 -->|"ambiguity"| H1["ESCALATE_HUMAN"]
    R1 -->|"P0 > 0"| F2["Fix P0s Only"]
    F2 --> R2["Round 2 Verify-Only (r1..r2 Diff)"]
    R2 -->|"All R1 P0 Resolved + 0 Regressions"| OK
    R2 -->|"Regression or P0 Increased"| RB["ROLLBACK_ESCALATE"]
    R2 -->|"Unresolved Non-Regressing P0"| T2["TAKEOVER_REQUIRED (No R3)"]
  end
```

| Dimension | Mode 1: `advisor_impl` | Mode 2: `final_review` |
| :--- | :--- | :--- |
| **Role Split** | Strong model writes contracted plan & advises; weaker model implements | One model plans & implements; independent stronger model reviews diff |
| **Hard Caps** | `max_advisor_calls = 2` (max `3`) + normalized `blocker_fingerprint` stagnation stop | `max_review_rounds = 2` (Round 3 hard-rejected in code) |
| **Pre-Checks** | Authoritative `git diff --name-status` scope & protected manifest/test checks | Mandatory `verify_cmd` (`CI=1`, process-tree kill) + non-CRLF empty-diff guard |
| **Review Scope** | Structural triggers only (`repeated_verify_failure`, `scope_or_api_conflict`, `final_spec_check`) | R1: full `base_tree..r1_tree` · R2: strictly `r1_tree..r2_tree` + R1 P0 partition check |
| **Escalation** | `takeover_required` (or instant `takeover_now` on Call 1) → `takeover` unlocks strong model | `approved`, `escalate_human` (`ambiguity`), non-destructive `rollback_escalate`, or `takeover_required` |

---

## Architecture: One Core, Four Clients

```mermaid
flowchart TD
  CC["Claude Code"] --> MCP["review-gate-mcp (stdio + progress heartbeat)"]
  CX["Codex CLI"] --> MCP
  T3["T3 Code"] --> MCP
  T3 -.->|"gate_only + native async delegate_task"| CORE
  PI["Pi Coding Agent"] --> EXT["extensions/pi/review-gate.ts (tool_call guard + native tools)"]

  SK["~/.agents/skills/ (3 Intent-Driven SKILL.md)"] -.-> CC
  SK -.-> CX
  SK -.-> T3
  SK -.-> PI
  MCP --> CORE["src/core/ · Single TypeScript Engine"]
  EXT --> CORE

  CORE --> STATE["{git-dir}/agent-gate/ (tasks, active.json, metrics.jsonl)"]
  CORE --> REFS["refs/agent-gate/{task_id}/* (immutable write-tree snapshots)"]
  CORE --> RUN["Hardened Backends: codex exec | claude -p | gate_only"]
```

---

## Quick Start

Requires **Node ≥ 24** (runs `.ts` natively with `erasableSyntaxOnly: true` — zero build step).

### 1. Clone, Test & Link Globally
```bash
git clone https://github.com/hua0512/review-gate.git review-gate
cd review-gate
pnpm install
pnpm run typecheck
pnpm test
pnpm add -g link:.   # exposes `review-gate` and `review-gate-mcp` on PATH (or: npm link)
```
> On Windows, `pnpm` global bins generate `.cmd` wrappers; when registering MCP servers in clients that spawn with `shell: false`, use `command: "node"` with `args: ["<path/to/review-gate>/src/mcp.ts", "--role", "orchestrator"]`.

### 2. Install Shared Skills (+ Native Pi Extension)
```bash
# Installs 3 skills to ~/.agents/skills/ and links ~/.claude/skills/ & ~/.pi/agent/skills/
# (unprivileged NTFS junctions on Windows; POSIX symlinks on macOS/Linux/WSL)
review-gate install-skills --force

# Include the native Pi extension shim (~/.pi/agent/extensions/review-gate.ts):
review-gate install-skills --force --with-pi-extension
```
> Using both Windows native and WSL on the same machine? Run `install-skills` once in Windows and once inside WSL so each `$HOME` keeps native links.

### 3. Connect Your Clients

| Client | Setup | Recommended Mode |
| :--- | :--- | :--- |
| **Claude Code** | `claude mcp add -s user review-gate -- node <path/to/review-gate>/src/mcp.ts --role orchestrator` | Unified backend (`--backend codex`) + `MCP_TOOL_TIMEOUT=360000` |
| **Codex CLI** | `codex mcp add review-gate -- node <path/to/review-gate>/src/mcp.ts --role orchestrator` | Unified backend (`--backend claude`) + `tool_timeout_sec = 360` in `~/.codex/config.toml` |
| **T3 Code** | Add MCP server `review-gate` (`command: "node"`, `args: ["<path/to/review-gate>/src/mcp.ts", "--role", "orchestrator"]`) | Mode 1: Strong main thread + `delegate_task` · Mode 2: `--backend gate_only` + native async `delegate_task` (full thread visibility, zero timeout risk) |
| **Pi** | Run `review-gate install-pi` then `/reload` (or configure `mcp.json` below) | Native `tool_call` scope guard (`ctx.ui.select()` override) + native `gate_*` tools |

<details>
<summary><strong>Pi MCP config (alternative to native Pi Extension) & implementer-only MCP role</strong></summary>

In `~/.pi/agent/mcp.json` (or `.pi/mcp.json`), then `/reload`:
```json
{
  "mcpServers": {
    "review-gate": {
      "command": "review-gate-mcp",
      "args": ["--role", "orchestrator"],
      "exposure": "direct"
    }
  }
}
```

When mounting MCP for an **isolated weak-implementer session**, pass `--role implementer`. This hides privileged lifecycle and approval tools (`gate_init`, `gate_amend`, `gate_takeover`, `gate_approve`, `gate_close`, `gate_prepare_review`, `gate_record_review`, `gate_metrics`, `gate_prune`) so implementers can never self-approve or rewrite contracts.

</details>

---

## Everyday Usage

Once Skills and MCP/Extension are installed, just express your **intent** naturally — no CLI syntax to memorize:

- **Mode 1 (Strong Plan/Advisor → Weak Implementer)**  
  *“Design a contracted plan to refactor `src/auth/**`, protect `tests/auth/**`, verify with `pnpm test`, initialize `review-gate` in advisor mode, and delegate implementation.”*
- **Mode 2 (Implement → Strong Final Review)**  
  *“Initialize `review-gate` in final-review mode with `codex` (`gpt-5.4`, high effort) and `pnpm test`, implement the feature, and pass final review.”*
- **Metrics & Model Comparison**  
  *“Show recent review effectiveness across models”* or *“Export and open the review dashboard”*
  - **T3 Code**: `gate_metrics(format="html")` → `html_preview` → `html_render` renders the interactive SVG dashboard inline in your thread.
  - **Claude Code / Codex / Pi**: renders a Markdown table in terminal, or runs `gate_metrics(format="html", open=true)` to write a standalone dark/light-adaptive HTML dashboard to the OS temp dir and open your default browser automatically.
- **Maintenance**  
  *“Clean up stale review-gate tasks older than 7 days”* → previews with `dry_run=true`, then prunes old task files & orphan refs while preserving `metrics.jsonl`, the active task, and sibling worktrees' live refs.

---

## Optional: `PreToolUse` Fast-Fail Scope Hooks

> **Authoritative vs. Fast-Fail**: The engine's Git-tree scope check (`git diff --name-status <base_tree> <current_tree>`) is always the single authoritative guard across all 4 clients. Adding a `PreToolUse` hook is optional — it catches out-of-scope file edits *before* they happen during Mode 1 (`advisor_impl` + `in_progress`), and stays completely silent otherwise.

<details>
<summary><strong>Claude Code (<code>settings.json</code>) &amp; Codex CLI (<code>hooks.json</code>) — zero <code>jq</code> required</strong></summary>

**Claude Code** (`~/.claude/settings.json` or `.claude/settings.json`):
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "review-gate hook-pre-tool-use --client claude"
          }
        ]
      }
    ]
  }
}
```

**Codex CLI** (`~/.codex/hooks.json` or `.codex/hooks.json`):
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "review-gate hook-pre-tool-use --client codex"
          }
        ]
      }
    ]
  }
}
```

> **Note**: Codex CLI does not currently fire `PreToolUse` on `apply_patch`, and T3 Code `delegate_task` does not run local `PreToolUse` hooks; in both cases the engine's Git-tree scope check still enforces the contract at every gate transition. Pi gets interactive `tool_call` interception natively via `extensions/pi/review-gate.ts`.

</details>

---

## Systems Engineering & Hardening

| Area | What `review-gate` Does |
| :--- | :--- |
| **Tamper Resistance** | State lives under `<git-dir>/agent-gate/` (protected by `.git/` sandbox guards). Gate-Only binds `prepare` ↔ `record` via single-use `{ round, tree_sha, nonce }` and verifies the working tree has not mutated since `prepare`. |
| **Zero-Commit Snapshots** | Snapshots uncommitted edits, deletions, and untracked files using a temporary `GIT_INDEX_FILE` + `git write-tree`, pinned under `refs/agent-gate/<task_id>/*`. Never touches `HEAD`, branches, or `.git/index`. |
| **Implicit Manifest Protection** | Blocks edits to `package.json`, `tsconfig*.json`, `Cargo.toml`, `pyproject.toml`, test configs, and `.github/workflows/**` unless explicitly opted into `allowed_files` (catch-all `**` does not waive protection). |
| **Windows + WSL Hardening** | Resolves `.exe` vs `.ps1` (`pwsh.exe -File`) via `where.exe` with `shell: false`, pipes all prompts/diffs over `stdin` (no 8–32 KB argv overflow), runs `verify_cmd` via `pwsh` / `bash` with `CI=1` and full process-tree kill, uses NTFS `nocase: true` + `--ignore-cr-at-eol`, and installs skills via unprivileged NTFS junctions. |
| **Anti-Recursion & Real CLI Auth** | Sets `REVIEW_GATE_CHILD=1` on all child processes; disables every Codex MCP individually via `codex mcp list --json` (60s TTL) + `-c mcp_servers.<name>.enabled=false -c features.hooks=false --ephemeral`; invokes Claude with `--safe-mode --strict-mcp-config --tools "Read,Glob,Grep" --no-session-persistence` (preserving OAuth/Keychain subscriptions) and unwraps `.structured_output`. |
| **Prompt Cache & Timeout Hygiene** | Static instructions, `Frozen Spec`, and `Non-Goals` stay byte-identical at the top of R1 & R2 prompts (dynamic round headers, `durationMs`, P0 lists, and diffs sit strictly at the tail). Long-running MCP tools emit 15s `notifications/progress` heartbeats (0 LLM tokens) and coalesce duplicate in-flight `reviewDiff` retries idempotently. |
| **RCO Telemetry & Safe Prune** | Appends privacy-safe records to `<git-dir>/agent-gate/metrics.jsonl` on `close` (tracking R1 first-pass rate, `R1→R2` P0 resolution rate, takeover/rollback rates, and per-model breakdown). `prune` checks `--git-common-dir` across all linked worktrees before deleting orphan refs and never touches `metrics.jsonl`. |

---

## CLI & MCP Reference

<details>
<summary><strong>CLI Commands</strong></summary>

```bash
# Mode 1: Strong Plan/Advisor -> Weak Implementer
review-gate init --task-id feat-1 --mode advisor_impl \
  --spec "Add auth refresh helper" --verify "pnpm test" \
  --allow "src/auth/**" --protect-test "tests/auth/**" \
  --backend codex --model gpt-5.4 --effort high

review-gate check-scope --file src/auth/refresh.ts
review-gate check-scope --git
review-gate advisor --trigger repeated_verify_failure --question "TS2345 persists"
review-gate amend --allow "src/auth/**" --allow "src/types.ts"
review-gate takeover
review-gate approve
review-gate close

# Mode 2: Single Model Impl -> Strong Final Review
review-gate init --task-id fix-2 --mode final_review \
  --spec "Fix parser edge case" --verify "pnpm test" \
  --backend claude --model claude-opus-4-6 --effort high

review-gate review

# Mode 2 Gate-Only (e.g. T3 Code delegate_task; pipe verdict via stdin to keep working tree untouched)
review-gate prepare
review-gate record --round 1 --tree <sha> --nonce <nonce> --review-file - < /tmp/verdict.json
review-gate close

# Telemetry & Maintenance
review-gate status
review-gate metrics --format markdown
review-gate metrics --format html --open
review-gate prune --older-than-days 7 --dry-run
review-gate prune --older-than-days 7

# Installation & Adapters
review-gate install-skills --force [--with-pi-extension]
review-gate install-pi
review-gate mcp --role orchestrator|implementer
```

</details>

<details>
<summary><strong>MCP Tools (<code>review-gate-mcp</code>)</strong></summary>

| Tool | Role | Purpose |
| :--- | :--- | :--- |
| `gate_status` | `orchestrator`, `implementer` | Inspect active task state, worktree pointer, and Git scope summary |
| `gate_check_scope` | `orchestrator`, `implementer` | Validate a file path or full working-tree diff against the contract |
| `gate_ask_advisor` | `orchestrator`, `implementer` | Mode 1 bounded advisor call with fingerprint stagnation detection & MCP heartbeat |
| `gate_review_diff` | `orchestrator`, `implementer` | Mode 2 unified backend review (`verify_cmd` → snapshot → strong CLI reviewer) with heartbeat & dedup |
| `gate_init` | `orchestrator` only | Initialize task, snapshot `base_tree`, set worktree `active.json` |
| `gate_amend` | `orchestrator` only | Update contract or runner config without resetting round/advisor history |
| `gate_takeover` | `orchestrator` only | Transition to `takeover_active`, lifting implementer scope lock |
| `gate_approve` | `orchestrator` only | Mode 1: verify `verify_cmd` + Git-tree scope and mark `approved` before closing |
| `gate_close` | `orchestrator` only | Record telemetry to `metrics.jsonl`, clear `active.json`, delete pinned refs |
| `gate_prepare_review` | `orchestrator` only | Gate-Only: run pre-checks, snapshot tree, issue `{ round, tree_sha, nonce, prompt, schema }` |
| `gate_record_review` | `orchestrator` only | Gate-Only: verify tamper-binding token, validate schema + R2 partition, advance state |
| `gate_metrics` | `orchestrator` only | Return `json`, `markdown`, or `html` telemetry (supports `out_path` & `open: true`) |
| `gate_prune` | `orchestrator` only | Prune stale tasks & orphan refs across worktrees (preserves `metrics.jsonl`) |

</details>

---

## Research Foundations

`review-gate`'s boundaries are directly grounded in multi-agent & LLM-refinement research:

- **Bounded 1–2 Round Gains & Over-Refinement**: *Self-Refine* ([arXiv:2303.17651](https://arxiv.org/abs/2303.17651))
- **External Truth & Soundness vs. Style Critics**: *Cannot Self-Correct* ([arXiv:2310.01798](https://arxiv.org/abs/2310.01798)), *When Can LLMs Actually Correct Their Own Mistakes?* ([arXiv:2406.01297](https://arxiv.org/abs/2406.01297)), *LLM-Modulo* ([arXiv:2402.01817](https://arxiv.org/abs/2402.01817))
- **Nitpicking vs. Recall & Human Escalation**: *CriticGPT* ([arXiv:2407.00215](https://arxiv.org/abs/2407.00215))
- **Clean-Slate Independence & Deterministic State Machines**: *Degeneration-of-Thought* ([arXiv:2305.19118](https://arxiv.org/abs/2305.19118)), *MAST* ([arXiv:2503.13657](https://arxiv.org/abs/2503.13657)), *Talk Isn't Always Cheap* ([arXiv:2509.05396](https://arxiv.org/abs/2509.05396))
- **Weak-Refiner Degradation & Direct Takeover**: *Asymmetric Capacity Allocation in Self-Refinement Pipelines* ([arXiv:2608.21345](https://arxiv.org/abs/2608.21345))
- **Stall Circuit Breakers & Non-Destructive Rollback**: *Magentic-One* ([arXiv:2411.04468](https://arxiv.org/abs/2411.04468)), *PerFine* ([arXiv:2510.24469](https://arxiv.org/abs/2510.24469))
- **Critique Utility Telemetry**: *RCO* ([arXiv:2506.22157](https://arxiv.org/abs/2506.22157))
- **Prompt Cache Prefix Discipline**: *Don't Break the Cache* ([arXiv:2601.06007](https://arxiv.org/abs/2601.06007)), *Silent and Costly* ([arXiv:2610.34817](https://arxiv.org/abs/2610.34817)), *Context Has a Price* ([arXiv:2611.22238](https://arxiv.org/abs/2611.22238))