turnstile

agent
Security Audit
Warn
Health Warn
  • License — License: MIT
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Low visibility — Only 7 GitHub stars
Code Warn
  • process.env — Environment variable access in claude-code/bin/turnstile-hook.ts
Permissions Pass
  • Permissions — No dangerous permissions requested

No AI report is available for this listing yet.

SUMMARY

Agent pipeline enforcement for OpenCode and Claude Code: plan approval, test gates, and a tamper-evident audit trail — enforced by hooks, not prompts.

README.md

turnstile

ci
npm
coverage
deps
license

Gates the runtime enforces, not requests the model can ignore.

Turnstile is an OpenCode v2 plugin that runs your work
through an enforced pipeline: planner → plan-reviewer → executor →
test-runner → reviewer. Like its namesake, an agent can't proceed until each
stage pays the toll: a plan, an approval, a green test run. The journal is
the receipt. The same gates also run on Claude Code through command hooks;
see Claude Code adapter.

turnstile runs the ensemble end to end: planner → plan-reviewer → executor → test-runner → reviewer, with blocked dispatches (red) until VERDICT: APPROVE and verified GATE: PASS evidence flip each gate green, and every decision lands in turnstile.jsonl

A real run: the two red BLOCKED by turnstile: lines flip green once the
plan approval and verified GATE: PASS land. Every decision appends to
turnstile.jsonl.

What you see:

BLOCKED by turnstile: no plan approval for ".opencode/plans/issue-42.md". …
VERDICT: APPROVE crit=0 high=0 med=2 low=1
GATE: PASS tests=12 passed=12 failed=0

Blocked (red), then approved (green), then tests pass (green). You never
type any of this: the markers are the machine's language. Subagents emit
them, turnstile checks them, and your only vocabulary is plain prompts.

TL;DR: try it in two minutes

npx opencode-turnstile init      # install the plugin + pipeline agents
npx opencode-turnstile check     # verify the install (incl. plugin loadability); must exit 0

Then restart OpenCode (or opencode service restart) so the plugin
loads. Adding just the plugin still enforces the gates, but the pipeline
needs agents to dispatch against, so run init (or bring your own, see
docs/usage/install.md):

// ~/.config/opencode/opencode.json
{ "plugins": ["opencode-turnstile"] }

After restart the orchestrator dispatches the pipeline on your prompts,
blocked work says BLOCKED by turnstile: <reason> instead of proceeding,
and every decision is journaled; see it with
npx opencode-turnstile status. To bypass the gates for a task, put
USER WAIVER: in your own prompt.

Using it for real work

You never invoke the pipeline stages directly. Start a task the way you
already would, and the enforcement wraps it. The one habit to build: open
with the planner.

turnstile, the enforced pipeline: requirements (optional) → planner → plan gate (VERDICT: APPROVE or human approval) → executor (cites chunk-N / AC-n) → test-runner → test gate (GATE: PASS) → reviewer ×2 → review gate (VERDICT: APPROVE ensemble) → landing gate → push

1. Start a task by invoking the planner. Paste an issue or a topic into
your prompt and ask for a plan:

Work on issue #42 (flaky retry in the upload path). Start from the planner:
produce a plan with a decomposition, then run the pipeline through review.

The planner writes a plan with numbered AC-n / chunk-N entries to
.opencode/plans/. From here the pipeline drives itself: the PIPELINE:
status line on each result names the next stage:

PIPELINE: planner=done plan=PENDING tests=RED reviewer=0/2
next=plan-reviewer — dispatch the next agent in this same turn

2. The plan gate fires. The plan-reviewer must record VERDICT: APPROVE
before any executor dispatch is allowed. A VERDICT: BLOCK sends the work
back to the planner; nothing for you to do unless you want to override:

PLAN APPROVED: ship it as-is, the retry heuristic is good enough for now

(in your prompt; see Waivers and approvals).

3. The executor is gated on the approved plan and must cite chunk-N /
AC-n entries from the decomposition, so implementation traces to the plan.

4. Tests gate the reviewer. The test-runner must emit
GATE: PASS tests=… and a matching exit-0 test execution must exist in the
task's history.

5. The reviewer closes the loop. Approval requires two unwaived reviewer
dispatches (ensemble), and a counted VERDICT: APPROVE must be grounded in
the task's journaled verification facts: a prior GATE: PASS or a recorded
test-run evidence hit. An ungrounded verdict is not counted; the reviewer is
re-prompted once (bounded by the shared marker-retry budget) to cite the
verified gate pass or test run it rests on. Once credited, the landing gate
releases git push.
A provably no-op push is exempt by default (emptyDiffExempt).

Enforcement is dormant until engaged: turnstile arms when your prompt
provides a plan or asks to run the planner/pipeline, and sleeps again on task
completion or TURNSTILE OFF: (alwaysEnforce: true restores always-armed).
Once engaged there is no audit-only mode. Per-feature opt-outs are listed in
Configuration.

When a gate fires early, the block message names the reason:

BLOCKED by turnstile: no plan approval for "<plan path>". Dispatch the
plan-reviewer subagent first; proceed with executor only after the
plan-reviewer's first line is `VERDICT: APPROVE crit=<n> high=<n> med=<n>
low=<n>`, or obtain an explicit user waiver (a user prompt this task must
contain the literal marker 'USER WAIVER:' followed by the user's words).

A full annotated session, with every dispatch, block message, waiver, and
the journal entries behind them, is in
docs/usage/worked-session.md.

What it enforces

Gates are decided in execute.before hooks; every gate has a human escape
hatch. Full detail (guards, state fields, escape ladders, diagrams) lives in
docs/architecture/gates.md.

Gate In one line
Plan approval executor dispatches blocked while the plans dir holds a pending plan (no reviewer VERDICT: APPROVE or human approval); editing the plan's spec region invalidates an earlier approval
Reviewer dispatch gate reviewer dispatches blocked until a GATE: PASS verified by a real exit-0 test execution in this task
Reviewer round cap Max 2 reviewer dispatches per task; waived dispatches bypass and don't count
Reviewer ensemble A reviewer APPROVE credits the landing gate only at ≥2 unwaived reviewer dispatches, and only when grounded in a journaled GATE: PASS or test-run evidence hit (ungrounded verdicts are uncounted and re-prompted once for a citation)
Loop caps Per task: planner 3, plan-reviewer 3, test-runner 4, 16 total dispatches; exhaustion blocks and journals an escalation entry
Decomposition gate executor dispatches must cite chunk-N / AC-n when a plan has a ## Decomposition block
Read horizon Warns at 8 whole-file read calls per session, blocks at 15 (prefer grep/glob)
Tool-call policy bash/shell commands and write/edit paths matched against a configured denylist (default empty; the empty lists are the off switch)
Commit-lint git commit -m subjects must be conventional commits when gitGates.commitMessages is on (default)
Landing gate git push without a credited reviewer VERDICT: APPROVE blocks; a repeat attempt forces the interactive human ask
Marker parsing GATE: / VERDICT: markers parsed from task results and child text; only marker-contracted emitters flip state — echoes are journaled suppressed
Question pause an executor QUESTION: pauses pipeline dispatches for the task until you answer (the next dispatch prompt), cancel with QUESTION CANCELLED:, or the configured timeout resolves it (hold default)
Trace & telemetry JSONL journal of dispatches, gate transitions, verdicts, blocked calls, errors, per-session token/cost usage
Journal concurrency Concurrent OpenCode instances share one journal safely: chained appends and the approval sidecar write under a per-file lock with an in-lock re-read; lock contention degrades to an unlocked write with a journaled journal-lock: warning, never blocking enforcement
Decoding clamps reviewer/plan-reviewer temperature = 0; executor/test-runner/debugger ≤ 0.2
Compaction Injects a "preserve verbatim" instruction, then the live gate-state snapshot, de-tokenized so it can never re-parse as a marker

A few behaviors worth knowing; the mechanics live in
docs/architecture/gates.md and
docs/architecture/hooks.md:

  • State lifecycle. A new user prompt resets the session's gate state,
    except when continuation carry (default on) re-arms it for a prompt in the
    same worktree/branch with earned credit. An interrupted review carries the
    same way: the task re-opens with its green gate, dispatch counts, and plan
    approval intact.
  • Maintenance dispatches. A bookkeeping-only executor dispatch (plan file
    named in the prompt, diff touching only docs/prose surfaces) skips the
    plan-approval and decomposition gates (capped at 4 per plan); any
    src/, tests/, bin/, scripts/, or config touch gates it as ordinary
    implementation work.
  • Parent hands-on edits. Direct write/edit calls in the parent (and
    any non-pipeline subagent) are always gated: the first block throws, a
    repeat attempt raises a human permission ask (always / once /
    reject). Writes to the platform temp directory are exempt scratch.
  • Parent file-writing bash. Confident file-writing bash commands
    (redirects from writer commands, tee f, sed -i, cp/mv/dd/…) run
    the same ladder; output capture never gates. toolPolicy.bashWriteGate: false opts out (telemetry continues).
  • CI/CD configuration protected class. toolPolicy.cicdGuard (default
    true) protects CI/CD configuration paths (.github/workflows/**,
    .gitlab-ci.yml, Jenkinsfile, …) from parent write/edit and write-shaped
    bash commands; registered child sessions are exempt (any edge-registered
    subagent, not just the executor, mirroring the hands-on exemption).
    toolPolicy.cicdPaths replaces the built-in pattern list (regex sources,
    case-insensitive); toolPolicy.cicdExtraPaths appends opt-in deployment
    manifests; toolPolicy.cicdAllow exempts matching paths; anchor a pattern
    on the repo's directory name (e.g. "git/turnstile/\\.github/") to scope a
    global-config exemption to one repository. Relative paths without a repo
    marker cannot be scoped per-repo from the global config.

Waivers and approvals

Turnstile reads a waiver, a human plan approval, or an explicit task-retirement
marker only from the user's own prompt: the plugin checks which channel the
marker arrived through, never what an agent's dispatch prompt says.

  • USER WAIVER: in your prompt waives gates; naming agent stages scopes
    it. The landing gate is not waiver-released: git push always needs the
    credited reviewer verdict or your permission reply.
  • PLAN APPROVED: in your prompt approves the plan like a reviewer
    verdict, with human provenance; it replays across restart.
  • TASK DONE: in your prompt retires the session's active task; the
    next admitted prompt starts a fresh task scope. Child results and dispatch
    prompts never retire a task; only your prompt does. Config:
    taskDoneMarker renames the literal. Full semantics:
    docs/usage/configuration.md.
  • Permission escalation. A retried landing or hands-on attempt escalates
    to you through OpenCode's permission surface; reply always, once, or
    reject. Turnstile assumes a human answers these asks; an auto-accepting
    host (session.permissions: "autoaccept") degrades them to delays, one
    reason "block" is the default.

Full lifecycle semantics: docs/usage/waivers.md.

User plan review (opt-in)

With planUserReview: true, turnstile inserts a human checkpoint after the
planner: the plan-reviewer dispatch blocks until you answer from your own
prompt with PLAN REVIEWED: (accept; edit the plan file first if you
wish) or PLAN REJECTED: (retire the task scope). The literals work only
in your own prompt, waivers do not bypass the pause, and the pending state
survives a restart. Config: planReviewAcceptMarker /
planReviewRejectMarker rename the literals.

Requirements phase (opt-in)

With requirementsPhase: true, an ungated requirements leg precedes the
planner for non-trivial tasks: a requirements subagent returns a spec with
numbered acceptance criteria and Open Questions; open questions come to you
before planning. The phase is soft: its only enforcement surface is a loop
cap (maxRequirementsRounds, default 2). Config: agents.requirements
renames the agent.

Suspend and resume

Two prompt markers pause enforcement for the whole session, read only from
your own prompt:

  • TURNSTILE OFF: suspends blocking: would-be blocks are journaled as
    suspended audit entries, but nothing throws and no ask is forced.
    The suspension survives a restart.
  • TURNSTILE ON: resumes enforcement with fresh task state.

When both markers appear in one prompt, the later one wins. Config:
suspendMarker / resumeMarker rename the literals, and
allowSuspend: false disables both. Inspect the live state with
node bin/cli.mjs status (in-repo) or npx opencode-turnstile status.
When the journal has token-usage rows, status appends a per-task token/cost
rollup with a total line (--json carries it in a tokenUsage key); log
renders each token-usage row and a totals line.

opencode-turnstile log

Prints a chronological, human-readable timeline of one session's journal,
ending with a summary line. Read-only.

opencode-turnstile log                 # most recent session
opencode-turnstile log <sessionID>     # a specific session
opencode-turnstile log --json          # machine-readable output

opencode-turnstile stats

Aggregate rollups over the journal tail: near-miss rate by day, waiver
frequency per gate and per worktree, the gate-fail reason breakdown, and
token/cost per task. Read-only.

opencode-turnstile stats          # human-readable tables
opencode-turnstile stats --json   # machine-readable output

opencode-turnstile ps

Prints the live pipeline view for one session: which pipeline children are in
flight (agent, round, dispatch age) and what the parent is waiting on.
Read-only; "in flight" is inferred from the journal tail, so a child killed
mid-run shows running with a growing age.

opencode-turnstile ps                 # most recent session
opencode-turnstile ps <sessionID>     # a specific session
opencode-turnstile ps --json          # machine-readable output

opencode-turnstile prov

Prints the decision-provenance ledger: prov:stated (every admitted parent
prompt, verbatim after mechanical secret redaction), prov:denied (human
permission denials), prov:waiver (human gate waivers), and prov:override
(a parent write/edit following a pipeline-child write to the same path).
Read-only; capture is dumb, derivation is offline.

opencode-turnstile prov                 # every session, interleaved
opencode-turnstile prov <sessionID>     # a specific session
opencode-turnstile prov --json          # machine-readable output
opencode-turnstile prov --tail 100      # last 100 events
opencode-turnstile prov --verify        # check the journal hash chain + anchors

Capture is gated on decisionLedger.enabled (default true).

opencode-turnstile prov-views

Offline derived views over the decision ledger: classifies prov:stated
prompts by origin, computes the chatter noise rate, and aggregates
taste-drift signals. Purely read-time: journal rows are never rewritten, and
no derived value feeds gates.

opencode-turnstile prov-views                 # every session
opencode-turnstile prov-views <sessionID>     # a specific session
opencode-turnstile prov-views --json          # machine-readable output

opencode-turnstile review

Renders a per-task review bundle: the plan-delta evidence chain for one task,
read from the journal sinks alone (including rotated and archived
generations). It folds the plan verdict history, the bound plan file's
## Decomposition items with their per-item journal evidence (dispatches,
writes to paths the item names, plan-impact classifications), the files
touched (unmatched writes called out), the gate history with waivers and
refusal stamps, the reviewer verdicts (credited and uncredited), and the
recovery/continuation rows. Read-only: nothing is written, and it works with
trace: false (the JSONL journal is always written; the trace file is never
touched).

opencode-turnstile review                 # most recent session
opencode-turnstile review <sessionID>     # a specific session
opencode-turnstile review --json          # machine-readable output
opencode-turnstile review --plans-dir <path>   # plan-file directory
                                               # (default .opencode/plans)

JSON output contract

Every read-only subcommand (status, stats, log, ps, prov,
prov-views, review, evidence) prints one JSON document with --json:

{ "schema": 1, "generatedAt": "<ISO-8601>", "command": "<name>", "data": { ... } }

schema is the contract version: keys are added only; a rename or removal
bumps schema. Timestamps are ISO-8601 strings. Empty collections are []
or {}, never null or missing. With --json, stdout is exactly one JSON
document; notices go to stderr, and errors print
{ "schema": 1, "generatedAt": "...", "command": "<name>", "error": { "code": "<usage|journal-read|internal>", "message": "..." } }
with a nonzero exit (2 for usage errors, 1 otherwise). The evidence
exception: --out writes the bare artifact (its own
turnstile-evidence/v1 schema), and only stdout output carries the
envelope.

Markers

Subagents must emit these as the first line of their output. These examples
are the canonical syntax; CI asserts the parser in src/markers/markers.ts accepts
exactly them.

GATE: PASS tests=12 passed=12 failed=0
GATE: FAIL tests=12 passed=10 failed=2

VERDICT: APPROVE crit=0 high=0 med=2 low=1
VERDICT: BLOCK crit=1 high=0 med=0 low=2

QUESTION: should chunk 3 use worker pools or a queue?

The parser accepts these markers wrapped in markdown backticks and credits
them identically to the bare form; only a marker that does not match the
fields above is treated as absent. A QUESTION: marker carries free text
(no counted fields); only the executor's deliveries open a question.

Waiver and approval markers (must appear in the user's prompt, verbatim; a
dispatch prompt that merely contains the marker unlocks nothing):

USER WAIVER: <the user's words>
USER WAIVER: I approve proceeding to the <agent> stage
PLAN APPROVED: <the user's words>

Install

Turnstile ships as the npm package
opencode-turnstile.
Pick one way to install it; do not combine the plugin-array path with the
CLI install:

  1. Plugin only: add "plugins": ["opencode-turnstile"] to
    ~/.config/opencode/opencode.json and restart. Gates enforce; agent
    definitions are not installed.
  2. Full install: npx opencode-turnstile init installs the plugin and
    the pipeline agent definitions into ~/.config/opencode.
  3. From a clone: clone the repo and run npm run init (symlink mode)
    so installed artifacts stay live against your edits.

Turnstile has no npm lifecycle hooks: installing the package never writes to
~/.config/opencode; that happens only when you run an explicit command.
Modes, conflicts, the ledger, upgrades, uninstall, and per-agent model pins
are covered in docs/usage/install.md.

Verify the running version

After upgrading, restart every OpenCode process that hosts sessions: the TUI
or desktop app, and any persistent service (opencode service restart,
opencode serve, ACP providers). A running host keeps the previously loaded
plugin module, so sessions it serves keep enforcing the old version until it
restarts, with no error to tell you.

To confirm what a machine is actually running, read the newest setup row in
the journal; it stamps the plugin version and load time:

grep '"type":"setup"' ~/.local/share/opencode/metrics/turnstile.jsonl | tail -1

If that row's version is older than the installed package, a process still
runs the old module: restart it. npx opencode-turnstile check verifies
files on disk, not the loaded module. The opencode-turnstile status
command reports this gap directly (a loaded plugin: line, or pluginLoad
in --json).

Verify a clone with:

npm install
npm run ci            # lint, format:check, typecheck, check:markers, test gate enforcing 100% line/branch/function coverage
npm run ci:installed  # install:check — run after `npm run init` on a machine with artifacts

For behavior-preserving changes, npm run test:differential compares HEAD
against a reference commit scenario by scenario; the worked example lives in
docs/usage/differential-characterization.md.
A self-host smoke (fresh session, one full pipeline cycle on a trivial task)
is described in docs/usage/field-tested.md.

Configuration

Defaults live in code (src/config/config.ts); override via
~/.config/opencode/turnstile.json, a project-local
.opencode/turnstile.json, environment variables, or any combination
(precedence: defaults < global file < project file (.opencode/turnstile.json,
repo root) < env; config is read once at setup; restart
sessions to apply). Copy
examples/turnstile.example.json as a
starting point: every key is optional and matches the code defaults. (One
exception: the example writes agents.bareOutput: [] and
agents.reviewerSet: [] because JSON cannot express the "unset" sentinel;
the loader re-derives both either way.)
The knobs most people touch:

Key Default Meaning
alwaysEnforce false dormant-until-engaged; true restores always-armed from the first prompt
gateEvidence enforce flag/off revert to flip-on-trust for GATE: PASS
requireTestOverlap false when true, a GATE: PASS needs file overlap between executed tests and the change set; see configuration
testOverlapExempt [] globs the overlap rule never applies to (docs, generated code)
testOverlapTestFilePattern cross-ecosystem list regex list deciding which paths count as test files; extend for runners the defaults miss
escalation block repeat-attempt escalation mode; the plan-gate escalation is mode-gated (block blocks, ask prompts)
gitGates.commitMessages true validate git commit -m subjects as conventional commits
gitGates.landingGate true gate git push on a credited reviewer VERDICT: APPROVE
reviewEnsemble enforce advise credits a single-reviewer APPROVE unconditionally
reviewEnsembleDiversity off agent/model require distinct reviewer agents / models across the counted ensemble dispatches; identities are observed at reviewer result delivery
planUserReview false pause the pipeline after the planner until you accept or reject; see User plan review
questionTimeoutMinutes 0 minutes before an unanswered executor question resolves per questionTimeoutAction; 0 holds indefinitely
questionTimeoutAction hold hold keeps blocking past the timeout; resume clears the pause and lets the next dispatch proceed with a warning line naming the question
questionCancelMarker QUESTION CANCELLED: prompt literal that cancels a pending executor question without answering it
requirementsPhase false dispatch the requirements subagent before the planner; see Requirements phase
sessionSummary quiet one recap line at session end for active sessions (on adds an all-green line for idle ones; off disables)
tokenUsage summary token-usage journaling: summary journals one rollup row per session at session.idle; per-message journals one row per completed assistant turn; off disables
toolPolicy.bashDeny [] regex denylist for bash/shell (e.g. worktree/branch/merge ops)
toolPolicy.bashWriteGate true gate confident file-writing bash commands through the hands-on ladder
toolPolicy.cicdGuard true protect CI/CD configuration paths (.github/workflows/**, .gitlab-ci.yml, Jenkinsfile, …) from parent writes; registered child sessions exempt (any edge-registered subagent); false disables
toolPolicy.cicdPaths the built-in CI/CD list the protected class as case-insensitive regex sources; a configured list replaces the default wholesale
toolPolicy.cicdExtraPaths [] appended to the protected class (opt-in deployment manifests: k8s/, terraform/, Dockerfile, …)
toolPolicy.cicdAllow [] exemption patterns checked before the class; anchor on the repo's directory name (e.g. "git/turnstile/\\.github/") to scope a global-config exemption to one repository; a pathDeny match still blocks
maxReviewerRounds / others 2 / 3 / 3 / 4 / 2 / 16 per-leg (incl. requirements) and total dispatch caps per task
tokenBudgetMode advise per-task token/cost budget: advise journals one advisory row per exceeded cap per task and never blocks; enforce blocks further dispatches; off disables
maxTokensPerTask 0 per-task token ceiling (all five token components, task root + children); 0 = unlimited; requires tokenUsage ≠ off
maxCostPerTaskUsd 0 per-task cost ceiling in USD (host-precomputed turn cost); 0 = unlimited; requires tokenUsage ≠ off
agents.* stage names rename recognition when you bring your own agents; agents.reviewerSet (default: the single agents.reviewer name) lists the reviewers eligible for ensemble dispatches, so reviewEnsembleDiversity: "agent" is satisfiable by configuring a second reviewer
plansDir .opencode/plans where the decomposition scan looks
decisionLedger.enabled true observe-only decision ledger (opencode-turnstile prov)
loopGuard.enabled true loop guard: suspends agents stuck repeating identical tool calls or gate/verdict cycles
loopGuard.tool.threshold 8 identical tool calls (same tool + arguments) per session before the result is rewritten into a synthetic failure
loopGuard.test.threshold 4 same-target GATE: FAIL cycles per task before executor dispatches block
loopGuard.review.threshold 2 same-marker VERDICT: BLOCK cycles per task before reviewer dispatches block
tamperEvidence.enabled false per-record SHA-256 hash chain over every journal row + Merkle epoch commits
secrets.patterns [] extra secret-pattern regexes appended to the built-ins for journal redaction and the write-time guard (append semantics; built-ins are never replaceable)
secrets.writeGuard advise write-time secret guard: off disables, advise journals + nudges and never blocks, enforce blocks the matching write
secrets.entropy false advisory-only high-entropy literal flag (never blocks)

Invalid keys are ignored, journaled, and summarized once into the session
context; a malformed config file never breaks the host. The full table
(every key, default, and environment variable: TURNSTILE_TRACE,
TURNSTILE_METRICS_DIR, TURNSTILE_CONFIG, TURNSTILE_PROJECT_CONFIG) is in
docs/usage/configuration.md;
schemas/turnstile.schema.json ships with the package for editor
completion.

Show the evidence on your PR

The journal is per-machine; your teammates never see it. Turn the last
task's evidence into a shareable artifact: derived counts, canonical marker
lines, and shas, never session IDs or prompts:

npx opencode-turnstile evidence --task latest --out .turnstile/evidence.json

When run from inside an OpenCode session, latest means this session's own
last task; a concurrent session in another checkout can never end up in your
artifact.

Commit the JSON and Markdown pair and a GitHub Action upserts one sticky
comment per PR; evidence --validate re-checks a committed artifact in CI.
The comment states what it is: a correlated claim, not proof. Re-emit and
commit both files after every code push to a PR: the journal is per-machine,
so CI can post the committed badge but never refresh it. A stale badge means
exactly one thing: a code commit landed and nobody has re-emitted since. How
staleness is decided, and the one workflow quirk around first-time
contributors, are in
docs/journal/replay.md.

turnstile evidence posted on a pull request: one sticky comment with the plan verdict, the verified test counts, and the journal head sha

What turnstile is not

Turnstile is a speed bump and an audit trail, not a security boundary. A
GATE: PASS is a claim correlated with evidence; the journal records what
was claimed and is treated as sensitive data (see
SECURITY.md); the denylist is a deterrent, not a sandbox; MCP
tools remain unguarded. The full threat model:
docs/architecture/security.md.

Behavior contract

  • Zero runtime dependencies: the package ships with none; devDependencies are
    tooling only.
  • Fail-open by design. Every hook body is guarded; internal errors are
    journaled and the tool call proceeds. The only thrown errors are the
    deliberate BLOCKED by turnstile: ones.
  • docs/architecture.md (with the section files under docs/architecture/)
    is the authoritative reference for enforced contracts; the doc comment atop
    opencode/turnstile.ts summarizes it. CI keeps the marker examples in this README
    in sync with the parser regexes.
  • Host API is the OpenCode v2 promise-plugin shape
    ({ tool.hook, session.hook, permission.hook, event.subscribe }, with the
    permission hook registered when the host exposes it).
  • Host compatibility is checked at setup against the shipped range
    (HOST_COMPAT in src/hooks/host-compat.ts); see the matrix below.

OpenCode compatibility matrix

OpenCode host turnstile (current) Status
≥ 2.0.22, < 3.0.0 0.19.x Supported (tested: 2.0.22, 2.0.27, 2.0.29, 2.2.0, 2.2.5, 2.2.7, 2.3.0, 2.3.2, 2.4.1, 2.4.3)
≥ 3.0.0 or < 2.0.22 all Refuses to enforce at setup; upgrade turnstile
version unreadable all Enforces; one-time journal warning

2.4.1 verified for the token-usage surface; the 2.0.x event contract is
preserved by construction and cannot be live-verified where only 2.4.1 is
installed.

On an incompatible host turnstile toasts the upgrade instruction and
registers no hooks (a full no-op: fail-open):

turnstile 0.15.0 expects opencode >=2.0.22,<3.0.0; you're on 3.1.0 —
upgrade turnstile (npm i opencode-turnstile@latest) or pin opencode

npx opencode-turnstile status --check-updates (opt-in, network, cached 24 h)
reports when a newer turnstile is published.

Claude Code adapter

Turnstile also runs on Claude Code through command hooks instead of a
promise plugin. Copy claude-code/hooks/hooks.json into the project's
.claude/settings.json hook block (or merge its three surfaces:
PreToolUse on Task and the write tools, SubagentStop, and Stop);
each entry invokes claude-code/bin/turnstile-hook.ts, a thin CLI that
reads one hook payload from stdin and prints the verdict JSON. A block maps
to Claude Code's deny contract (exit 2); every internal error fails open.

The adapter enforces a two-gate profile: the plan gate (an Agent/Task
dispatch is denied while a decomposed plan lacks approval) and the review
gate (GATE: PASS / VERDICT: APPROVE marker capture on child results and
stops, with a stop-continuation cap so a session cannot continue silently).
State lives per session under
~/.local/share/opencode/metrics/claude-code/, guarded by a pidfile lock.

Environment variables:

  • TURNSTILE_SHIM_BUDGET_MS: the wall-clock ceiling for one hook
    invocation (default 5000, capped at 60000); bounds the state lock's
    retry loop.
  • TURNSTILE_CC_STOP_CONTINUATION_CAP: how many marker-less stops a
    session may re-prompt through before the block is terminal (default 8).

Plugin directory and agents

The adapter is also a valid Claude Code plugin directory:
claude-code/.claude-plugin/plugin.json names the plugin, hooks/ carries
the hook wiring, and claude-code/agents is a symlink to the repository's
agents/, so both harnesses consume the same agent definitions; edit a
template in agents/ and both see the change. Load it from a
checkout with --plugin-dir <path>/claude-code. Distribution is a local
plugin directory, not a marketplace; the decision and its revisit trigger
are recorded in
docs/adr/0001-cc-plugin-distribution.md.

Live probe suite

scripts/probe/run.mjs is a model-independent probe suite for the Claude
Code adapter: it drives the real shim CLI as a subprocess and asserts the
enforcement contract (allow with exit 0, the unmatched-agent-type telemetry
row, fail-open on unparseable input, and a deliberate block reaching the
child at exit 2 with the decision/reason JSON on stdout and the reason
on stderr). The block probe exercises that CLI exit-2/JSON/stderr mapping
with an injected BlockError at the deps seam; end-to-end gating through a
real dispatch is untested until the profile gates wire into the shim. The
suite is version-pinned: it first checks the installed
claude CLI against the pinned version (2.1.334), because the payload
shapes it asserts were measured on that line. A version mismatch fails the
run; a missing CLI reports PROBE: SKIPPED and exits 0, so local runs and
CI jobs without the CLI stay green.

node --experimental-strip-types scripts/probe/run.mjs            # live run
node --experimental-strip-types scripts/probe/run.mjs --dry-run  # list the suite, no probes

CI wiring: run the probe as a first, optional stage of the Claude Code
adapter's CI job. The skip contract makes the stage green when the CLI is
unavailable; the version pin makes it red when the CLI drifts from the
measured line, which is the signal to re-measure the payload shapes.

More documentation

  • docs/architecture.md: the architecture
    reference entry point (an overview plus links into the section files under
    docs/architecture/, with rendered diagrams).
  • docs/modules.md: the authoritative module map (every
    file under src/ with its responsibility).
  • docs/journal.md: the journal reference entry point
    (file layout, the entry-type catalog, rotation, replay, and tamper
    evidence, each in its own section file under docs/journal/).
  • docs/usage.md: the usage entry point (a worked
    session, waivers and approvals in full, installing and maintaining, the
    complete configuration table, journals and retention, and the status
    command).
  • SECURITY.md: journal sensitivity and trust model.

Reviews (0)

No results found