gates
v0.6.1Deterministic quality enforcement for Spec Kit projects at three boundaries: the agent boundary (Claude Code PreToolUse/PostToolUse/Stop hooks), the git boundary (pre-commit / pre-merge-commit / commit-msg), and the CI boundary (projected GitHub Actions / GitLab CI / Jenkins pipelines). One policy file, one verify entrypoint; CI runs the whole policy, and an earlier boundary skips only what the policy declares, by name.
How spec-gates works
spec-gates turns a project's quality rules into checks that fail closed
wherever code can change: while an agent works, when work is committed, and
in CI. One policy file (.specify/gates/policy.json) drives all three, one
entrypoint (verify.sh) runs the quality gate at each, and the runtime is
copied into the repository so it works for every clone and offline in CI.
agent edits ──► agent hooks ─┐
git commit ──► git hooks ─┼──► verify.sh --boundary <b> ◄── policy.json
pull request ─► CI pipeline ─┘ │
└──► attestation record (evidence)
The sections below follow that path: the three boundaries, the shared entrypoint, the evidence that proves enforcement still works, the spec, policy and constitution contracts, and how the runtime gets into a project and stays current.
The three-boundary model
Quality rules only matter if they are enforced wherever code can change. An agentic workflow has exactly three such places.
1. The agent boundary
While the agent is working. Claude Code exposes lifecycle hooks, and spec-gates uses four of them:
PreToolUse(Write|Edit)→protect-files.sh: refuses edits to the forbidden files (.envfiles, keys, certificates, credential files and sensitive directories: the listpre-commitandpr-check.shuse, see the git boundary), lock files, the project's own rules in.specify/gates/hooks.local.d/,.specify/gates/policy.json(always, whatever the policy says), and everyprotected_files.extraentry. A Write or Edit to.specify/memory/constitution.mdasks instead, under any policy (anextraentry naming it included): the constitution commands write it as one of their steps, so you approve that write once. It resolves.,..and//in the path first and matches ignoring case, since macOS filesystems are case-insensitive by default. Every rule, built-in orextra, also judges the fully resolved real path, with every symlink in the file and its parents followed, so a link inside the project (gdir -> .specify/gates,pol.json -> policy.json) or another spelling of the project root (/tmpand/private/tmp, a symlinked checkout) reaches the same verdict. A hard link topolicy.json, the constitution, a contract artifact or a project rule is recognized as that file. A path whose links it cannot resolve (a loop) asks.PreToolUse(Bash)→validate-bash.sh: refuses destructive commands (rmof root, home or a path outside the temp directories, read from the command without its data: quoted heredoc bodies not fed to a shell, literal commit messages andghbodies, redirect targets; force push with-f,--force,--force-with-lease,--mirroror a+refrefspec, hard reset,chmod 777, piping a download into a shell, discarding the whole working tree withgit checkout,git restoreorgit rmof.,:/or other pathspec magic in any option order,git checkout -f,git switch -for--discard-changes,git stash clear,git cleanwith-for--forceanywhere, …). A force-push refusal names the alternatives: a normal push, a new branch, or the forge's rebase (GitLab'sPUT /projects/:id/merge_requests/:iid/rebase). Withgit.allow_force_with_lease_on_branchesthe baregit push --force-with-lease <remote> <branch>...passes when every branch it names is none ofmain,masterand the remote's default branch (refs/remotes/<remote>/HEAD; unknown refuses); no named branch, a refspec it cannot read, or a cd it cannot follow refuses. Withgit.block_bulk_stagingit also refuses bulk staging:git addorgit stagewith-A(also in a cluster such as-vA),--all,--no-ignore-removal,--pathspec-from-file,.,:/and other pathspec magic, globs (quoted or not),"$PWD",~and directory arguments (relative to an earliercdin the same command), including behindenv,command,sudo, variable assignments and git's global options (-C,--no-pager, …). An argument it cannot resolve ("$f", a backtick substitution, arguments fromxargs, a path after acdit cannot follow) asks. Explicit files,-p, and the forms that stage only tracked changes (git add -u,--renormalize,git commit -a) stay allowed.validate-pr.sh: checks the title and body ofgh pr create|new|edit,glab mr create|new|update(also with-Ror--repobefore the subcommand) andgh apicalls on arepos/<owner>/<repo>/pullsendpoint with the commit-message rules. It reads each value as the shell would pass it and refuses one it cannot read literally: a variable, a command substitution (except the"$(cat <<'EOF' … EOF)"heredoc), a glob, a flag given twice, a clustered short flag such as-tfeat,gh api --input, or a PR command insidesh -c, behindevalor behindxargs. A PR command after a shell keyword (if …; then gh pr create …) or a wrapper and its options (env -i,sudo -u bob) is checked;gh api "$EP", whose endpoint only the shell knows, asks. A body file is read and its text checked: gh's--body-file <path>, and for glab, which has no description-file flag,--description "$(cat <path>)"or--description "$(<path)"with a literal path. A file it cannot read is refused.PostToolUse(Write|Edit)→post-edit.sh: formats the touched file per policy.Stop→format-changed.sh+verify-quality.sh: a stop whileverify.shis red is refused. The agent gets the failure list and keeps working. This turns "the tasks say run the tests" from a suggestion into an invariant, the property that matters for long, semi-attended/speckit.implementruns. The refusal holds once per stop: when the agent stops again right after it, Claude Code marks the retry withstop_hook_activeand both hooks let it through, so a gate the agent cannot turn green never locks the session. A red tree still cannot be committed (pre-commit) or merged (CI).
Every refusal says why and what to do instead, so the agent is redirected rather than stopped cold.
Block, ask, allow. The file and command hooks block on a rule match,
ask the human when they cannot judge, and allow everything else. "Ask" is
the PreToolUse permissionDecision: ask answer, which prompts in every
permission mode. The hooks ask:
- when a file name merely contains
credential,secret,password,passwd,tokenorkeystore, in any case (a test liketest_no_secret_leak.pyis not a credential), and on a Write or Edit to the constitution; - when a Bash command appears to modify a protected path:
rm,mv,sed -ior--in-place, a redirect (also>|), an--out/--outputoption,tee,find -delete,git rm,sort -oorrg --pre(which also asks anywhere inside the project, since its command runs on every file rg searches), also as/bin/rm,\rm,xargs rm, insidesh -coreval, or in an interpreter one-liner such aspython3 -c; anlnwhose target or link resolves to, contains or lies under one; or a redirect or changed argument that reaches one through an existing link (echo x > pol.jsonwithpol.json -> .specify/gates/policy.json). The path counts when the command names it, its parent directory, a brace, backslash or split-quote spelling of it, a variable the same command assigns, a variable or substitution it cannot resolve in front of the file name, a globextraentry such as**/*.lock.md, or a path relative to acdinto one or to the session's working directory (the hook inputcwd, which Claude Code keeps between calls). A read-only command such asgrep -n rm <path>and the literal message of agit commit -mdo not count as a change; - when a Bash command names a secret file the file hook refuses
(
cat .env). A read that only names a sensitive directory, such asls ~/.ssh/, runs; a command that reads every file under one (grep -r,rg,tar,zip,scp,xargs) asks; - when it bypasses the git hooks (
--no-verify,git commit -n, acore.hooksPathsetting, or a hook manager's skip variable such asHUSKY=0,LEFTHOOK=0orSKIP=), or sets a variable that changes what is enforced (see "Environment overrides are visible"); - when it creates commits that git runs no commit hook for
(
git cherry-pick,git rebase,git am,git revert, see the git boundary), or deletes a remote branch (git push origin :main,--delete); - in any state they cannot evaluate.
A project rule in hooks.local.d runs before any of these questions, so
its refusal wins. The hooks never silently allow. Without jq, or for input
that is not valid JSON, they read the field in a raw mode that keeps every
built-in block rule and still checks policy.json, the constitution and
the project's rules. It reads protected_files.extra when it is a list of
plain strings, on one line or many, and matches it as the jq path does; an
internal error, an undecodable, missing or repeated field, or a
protected_files.extra it cannot read asks. A malformed or invalid
policy.json cannot say what it protects either, so with jq the
Write/Edit hook asks before every edit and the Bash hook before every
command that appears to change a file. Doctor keeps failing until jq is
installed.
The Bash checks are heuristics. validate-bash.sh reads the command
text, not what the shell will run. It recognises the common spellings
listed above, blocks where a match is certain and asks where it is not,
but it cannot parse every shell form. The git hooks and the CI boundary
(pre-commit, commit-msg, pr-check.sh) are the enforcement backstop.
The Stop hook does not fail closed. When verify.sh cannot run (no
jq, no git, no policy), verify-quality.sh lets the session end and says
why. That is deliberate: a missing tool must never lock the agent in a
session it cannot finish. The gate still holds where it can: pre-commit
refuses every commit while verify.sh cannot run, pr-check.sh and
verify.sh in CI exit with an error, and the Write/Edit and Bash hooks
keep working in raw mode. Only a red gate, never a missing tool, refuses
a stop, and only the first one: the agent's next stop is let through
(see Stop above).
Project rules. A project adds its own refusals as scripts in
.specify/gates/hooks.local.d/<hook>/ for protect-files,
validate-bash, validate-pr, pre-commit and commit-msg. They run
after the shipped checks, so they can add a refusal but never remove one,
and upgrades never touch them. The agent cannot change them: Write/Edit
there is refused, a Bash change asks, and a commit that changes a rule
needs Protected-Change and Approved-By trailers like any protected
file.
2. The git boundary
When work becomes history. pre-commit blocks commits to main, scans
staged content for secrets and forbidden files (renamed and typechanged
files included), and runs the same verify
entrypoint. That run judges the working tree, not the commit: an unstaged
fix can let a broken commit pass (CI then fails), and an untracked file
can fail a clean one. When the working tree differs from the commit
(tracked changes the commit leaves out, for git commit -a and
git commit <paths> too, or untracked files that are not ignored),
pre-commit prints one line, gates: warning: the gate judges the working tree, not this commit: ..., with the counts. commit-msg enforces Conventional Commits and refuses
AI-isms, emoji (anywhere in the message, not only the subject; comment
lines and the scissors section are dropped first), AI branding and
Co-Authored-By trailers. The branding
list is policy (git.ai_branding.terms); a legitimate phrase that contains
a term, such as a product name a repository integrates, is allowed via
git.ai_branding.allow_phrases (matched literally, ignoring case, like the
terms).
The forbidden-file list is one list, in lib/secrets.sh, read by the
file and Bash hooks, pre-commit and pr-check.sh alike: .env and
.env.* files, SSH keys (id_rsa*, id_ed25519*, id_ecdsa*,
authorized_keys, known_hosts), keys and certificates (*.pem,
*.key, *.crt, *.p12, *.pfx, *.jks, *.keystore), credential
files (credentials, credentials.json/.yml/.yaml, .netrc,
.pypirc, gcloud-*.json, service-account*.json, aws-credentials),
and anything in or named .ssh, .gnupg, .aws or .gcloud, with or
without a trailing slash. Names ending in .example, .sample or
.template are exempt. The content scan looks for AWS, OpenAI, GitHub,
GitLab and Slack key shapes and for a password, secret, api_key or
token assignment of a quoted value of 8 or more characters. The keyword
must start a name or follow a character that is not a letter or digit
(DB_PASSWORD, --password; not identitySecret), and a value that
starts with $(, ${ or $NAME is a variable reference or command
substitution, not a literal, so it passes. The gates' own files, the
vendored .specify/extensions/gates/** and the projected
.specify/gates/**, skip that assignment rule while their content is
what was projected: the hash .specify/gates/.projected.sha256 records
for the file in the same snapshot (the staged index, or the commit
pr-check.sh scans), or the hash a released version shipped. Upgrades
overwrite these files, so a match there cannot be fixed by editing them;
an edited copy is scanned as before, and the key-shape rules scan every
file.
Subjects git writes itself are exempt from the Conventional Commits rule
only: a merge commit (recognized by MERGE_HEAD, not by its subject) and
the fixup!, squash! and amend! subjects of git commit --fixup and
--squash. A prefix counts only when the rest of the subject is the
subject of an existing commit, as git writes it; fixup! anything typed by
hand is judged like any other subject. Every other message rule still
applies to them.
git cherry-pick, git rebase, git am and git revert create commits
without running pre-commit or commit-msg (git's own behavior), so
neither the refusal of commits to main nor the secret scan nor the
message rules see them. The same holds for --continue and --skip,
which replay further commits (only a cherry-pick stopped on a conflict
runs the hooks for that one commit). Their result is checked only at the CI
boundary, where pr-check.sh repeats these pre-commit and commit-msg
checks over the pull request's commits: the secret and forbidden-file scan
(the same rules, from lib/secrets.sh, over the files each commit adds or
changes) and the protected-change trailers, plus the message rules for the
PR title and description (the commit on a squash merge). It does not
repeat the commit-message rules for each commit, nor the refusal of
commits to main, which branch protection covers on the server. The
agent's Bash hook asks before each of them, as it does for
--no-verify; --abort, --quit, --edit-todo and
--show-current-patch create no commit and are allowed.
A merge commit never runs pre-commit: git runs pre-merge-commit and
commit-msg instead. The pre-merge-commit hook runs the pre-commit
checks unchanged, so a local merge into main is refused and the secret
scan sees what the merge brings in. git calls it from 2.24 on; doctor says
so on an older git. A fast-forward creates no commit and runs no hook.
.git/hooks holds three copies of a small stub, not the hooks themselves.
.git/hooks is shared by every branch while the projected runtime is per
branch, so the stub runs the checked-out branch's
.specify/gates/hooks/<name>. The hook version always matches the
branch's runtime, and an upgrade needs no hook reinstall. A branch from
before gates was adopted has no runtime and is skipped: git tracks nothing
under .specify/gates there, in HEAD or in the index, and gitignored
leftovers such as attestations.jsonl do not count. A branch that tracks a
runtime but deleted its hooks is refused, so removing the hooks cannot
quietly turn enforcement off. A branch whose runtime predates
pre-merge-commit runs its pre-commit hook for a merge.
A branch that tracks something under .specify/gates but has no
projected libraries is refused too: pre-commit without
lib/policy.sh, commit-msg without lib/policy.sh or
lib/message.sh. That is a clone of a repo that commits policy.json
and gitignores the runtime, before anyone ran
bash .specify/extensions/gates/runtime/project.sh; the refusal names
that command. Only a runtime whose .runtime-version names a release
before 0.3.4 commits without lib/message.sh, with a warning that the
message rules were skipped.
Other hook managers. When husky, lefthook or the pre-commit framework
owns the hooks, gates adds its entry to the file that tool reads, never to
the files it generates, which its next install would rewrite.
project.sh --wire-manager appends the entry only where the result is
certainly still valid; otherwise it prints it.
| Owner | Where the gates entry goes | Notes |
|---|---|---|
husky (core.hooksPath under .husky/) | a line in .husky/<hook> | The script is created if missing, executable (husky 8, core.hooksPath=.husky, has git run it directly); your existing lines stay first. Under husky 8 an existing script without the execute bit fails the git check. A script with a top-level exit is left alone and the line printed, to go before the exit. |
| lefthook | a <hook>: block in lefthook.yml | Appended only when that hook has no block yet; otherwise printed for you to merge. A lefthook.toml, .json or .jsonc (also under .config/) is never edited: the entry is printed in its format. Run lefthook install if git does not run lefthook for that hook yet; until then the hook is reported as pending. |
| pre-commit framework | a repo: local item in .pre-commit-config.yaml | Appended only when repos: is the last top-level key and a block list (not repos: []); otherwise printed. Needs pre-commit 3.2+; run pre-commit install --hook-type <hook> for commit-msg and pre-merge-commit. Installed after projection, it runs the gates stub as <hook>.legacy (below). |
anything else (another core.hooksPath, a custom script) | nothing is written | project.sh prints the call-through line to add, before any exit. |
Ownership is judged by what the hook file runs. The stub, a hook copied
from an older release, and a hook whose only command is the call-through
to .specify/gates/hooks/<hook> (as some 0.3.x installs wrote them by
hand) are gates code: they are probed, and project.sh replaces them with
the current stub, which runs the same hook and also fails closed when the
branch's hook is missing. A lefthook.yml or .pre-commit-config.yaml
alone does not make that tool the owner: while the hooks directory holds
a gates hook and no hook the tool generated, the tool was never installed
and the repository is treated as having no manager. Where the tool is
installed, an older gates hook it has not replaced yet still becomes the
stub.
Proving the hooks run. A hook that exists is not a hook git runs. The
projected hooks answer GATES_PROBE=1 with a marker before reading any
policy, so a probe works with every rule off, and then refuse (exit 1).
Doctor and project.sh run the stub that way and fail unless the marker
comes back and the hook git runs exits non-zero: git refuses a commit
exactly when that status is non-zero, so the probe proves a refusal
reaches git, not only that the hook was reached. It runs the hook file
rather than a real git commit, which would commit whenever the chain is
broken. A hook another tool owns is read, not run, because running it
would also run that tool's steps (husky's default pre-commit is
npm test, under sh -e); the check looks for the gates call-through in
the tool's file, on a line that can run (not commented out, not after a
top-level exit, exec <command> or one-line if ...; then exit), and
--probe-git runs the full chain on request. The call-through counts
only in a form the check can prove refuses the commit: the gates hook as a
whole command (optionally behind exec and bash/sh, its path led by
./, $(...)/ or $VAR/), with plain arguments, an optional
|| exit, and at most a trailing comment. || true, &, a pipe, ;, a
leading true ||, echo or :, or a call inside a shell comment does
not count; neither does an indented line, which sits in a block. In a
script git runs directly (not husky, which runs its scripts under
sh -e), the call must also end the script on failure: under set -e,
behind exec, followed by || exit, or as the last command. Only the
configuration of the manager that runs the hook is read, and only where
it runs the call-through for that hook: in lefthook, a job under the
hook's own key without skip:/only:, not named (by tag or name) in the
hook's exclude_tags:, whose run: is the call in that form; in the
pre-commit framework, an item whose entry: is the gates hook and whose
stages: (or default_stages:) include the hook, an item without either
counting for pre-commit only. Other conditional exits in a script, and
lefthook's lefthook-local overrides or remote configs, are not read
statically; --probe-git covers them.
lefthook skips a pre-commit job while nothing is staged unless the job
has files to inspect, which would let git commit --allow-empty and
--amend on main through. The entry gates writes gives the job
files: echo lefthook.yml (the config file always exists) and puts
{files} in a shell comment of the quoted run: line, so the job runs on
every commit and the gates hook gets no arguments. The static check and the
probe fail a pre-commit job without that (or {all_files}), or with a
glob/file_types/exclude filter.
The probe calls each hook as git does: only commit-msg gets a message
file. lefthook's hook gets --job <gates job> (passed on to lefthook run), so no other job runs and nothing is rewritten. A hook a manager's
config calls but whose install command has not run yet is reported by
project.sh as pending that command; doctor fails on it, naming the
command, since a commit runs no gates check until then.
The pre-commit framework and .legacy. pre-commit install (with or
without --hook-type <hook>) does not overwrite a hook it finds: it moves
it to .git/hooks/<hook>.legacy and, on every call, runs that file first
(when it is executable), then its own items, and fails the hook when
either fails. Installed after projection, it moves the gates stub there.
The stub runs the gates <hook> under that name, so gates keeps running
and doctor reports "runs the gates stub it moved to <hook>.legacy".
project.sh refreshes an older stub found there (older stubs refused
every commit under the moved name) and asks for no config entry while the
moved stub runs. Two install orders work:
project.sh, thenpre-commit install --hook-type <hook>for each ofpre-commit,pre-merge-commitandcommit-msg: gates runs through<hook>.legacy.pre-commit install -f(--overwrite) deletes the.legacyfiles, and gates with them, unless the config calls gates.pre-commit installfirst, thenproject.sh --wire-manager(or--wire-managerafter the first order): the gates items go into.pre-commit-config.yaml. With a.legacystub still present gates runs twice per commit;project.shand doctor say so, andpre-commit install -f --hook-type <hook>removes the stub.
Doctor fails an older stub at <hook>.legacy and names the fix
(re-run project.sh).
Protected files get different treatment at the two local boundaries. The agent may never edit them, except the constitution, whose Write/Edit asks you first. At the git boundary a human is the committer, so an approved amendment has a path through: every staged protected path (added, modified, deleted, or renamed) must be declared in the message's trailer block, with an approver:
docs(constitution): ratify principle VI
Protected-Change: .specify/memory/constitution.md
Approved-By: Jane Reviewer
A staged protected path without a declaration, a declaration for a path
the commit does not change, or a missing Approved-By is refused. The
protected list is the union of the worktree policy and the committed one
at HEAD, plus the built-in hooks.local.d/** and the three
policy-contract artifacts (baseline.json, baseline.lock.json,
policy.effective.json), so a staged policy.json
cannot drop its own protection on the way in. A merge commit needs a
declaration only for a protected path that differs from every merged
parent, such as an edit made while resolving it; the merged commits carry
their own. git commit --amend cannot be told apart from a new commit
inside commit-msg, so an amend that drops a commit's trailers passes the
git boundary; pr-check.sh re-checks every commit in the range and
refuses it there unless the PR description declares the path. The trailer is an auditable
declaration, not a credential: real approval is enforced server-side by
CODEOWNERS plus branch protection. Setting git.protected_change_trailer
to false restores the unconditional refusal. The hooks read the switch
from the staged policy and HEAD's, not the working tree, so an
unstaged edit does not lift the refusal, and the commit that turns
it off is still judged by the trailer rule: it passes with a
Protected-Change trailer for each protected path it stages plus
Approved-By, and the refusal applies from the next commit on.
The one exception to the refusal is the commit contract.sh sync --update
makes. pre-commit lets it through only when, read from the index, the
branch is gates/baseline-<v> and the lock pins <v>, nothing is staged
but policy.json and the three artifacts, policy.json differs from
HEAD in extends.version alone, and the staged files pass the contract
checks (snapshot digest equals the pin, declaration equals the lock,
effective policy equals recomputation). Anything else stays refused. The
exception follows the shape of the change, not who runs it: a hand-made
commit of that exact shape passes too, and no hook can prove offline that
the snapshot is what the source publishes. That proof is the review of the
update branch, where pr-check.sh still requires the Protected-Change
trailers the update commit carries.
3. The CI boundary
When work leaves the machine. The projected pipeline job runs
verify.sh --boundary ci and the canary suite. Because it is the same
script and the same policy, CI is a backstop, never a surprise. The same
tool versions too: the job installs the lockfile's linters with npm ci
and the pinned shellcheck (mise or .tool-versions) with
.specify/gates/install-shellcheck.sh, which picks the release asset for
the runner's architecture and refuses one whose SHA-256 does not match
.specify/gates/shellcheck.sha256.
A third step, pr-check.sh, needs context only a pull or merge request
has, so it is deliberately not a verify.sh gate. It checks the PR/MR
title and description with the same message rules as commit-msg
(lib/message.sh, shared by all three boundaries); on a squash-merge
repository that text becomes the commit on the default branch, and no
local hook ever sees it. It also re-checks the protected-change rule for
every commit in the range, catching commits that never passed a local
hook. The rules for both checks, the text and the protected changes,
come from the policy at the base of the range, not the PR head, so a PR
cannot relax the rules it is judged by; policy.json and
hooks.local.d/** are checked even where the base sets
git.protected_change_trailer to false. A merge commit is checked for
the paths it changes against every parent, so merging the base into a PR
branch does not re-check the base's own changes. A declaration in the description covers every commit, since a
squash merge keeps the description and drops the commit trailers. GitHub
re-runs it when a PR is edited; GitLab starts no pipeline on an MR edit,
so a fresh pipeline is needed after one. In a GitLab job, one draft marker
at the start of the MR title (Draft:, [Draft], (Draft), WIP: or
[WIP], any case, followed by a blank) is dropped before the title is
checked: GitLab removes it when the MR is marked ready, so the merged text
never carries it. A marker anywhere else stays, and a title that is only a
marker still fails.
It also runs the pre-commit secret and forbidden-file scan, with the
same rules (lib/secrets.sh), over every commit in the range, so commits
that never ran pre-commit (git cherry-pick, rebase, am, revert,
--no-verify) are scanned before merge. Each commit is scanned for the
files it adds or changes (a rename under its new name), in its own copy,
and a finding is reported under the commit's hash and subject. A secret
added and removed again within the range still fails: it is in the history
the branch pushed and would merge, so rotate it and rewrite the branch. A
merge commit is scanned for the paths whose result differs from every
parent, so merging the base in does not re-scan the base's files.
A base policy that is not valid (broken JSON, wrong shape) stops the check
with exit 2 and names the problem, as verify.sh refuses it; it never
reads as "nothing is protected". A base with no policy at all is the PR
that adopts spec-gates: it is checked against the PR's own policy, and
policy.json, the constitution, hooks.local.d/** and the contract
artifacts are protected whatever that policy says. The log says so.
The code that runs the check comes from the base too. The projected
templates extract .specify/gates/pr-check.sh and lib/ from the base
revision (git archive) into a temporary directory and run that copy
against the PR checkout, pointing it at its own libraries with
GATES_RUNTIME_DIR. A PR that replaces pr-check.sh with exit 0 is
still judged by the base's copy. When the base has no pr-check.sh (the
adoption PR), the PR's own copy runs and the log says so. A base whose
pr-check.sh predates GATES_RUNTIME_DIR still loads the PR's
libraries, so this protection starts with the first base that carries a
release supporting it.
Adopting only the pr step
A pipeline that runs the gates step but not the rest of the template can
add the pr step on its own, without the hardened workflow. A
ci:pr hold instead leaves PR titles, descriptions and Protected-Change
declarations unchecked in CI, and doctor reports it as a [rec] saying
so. When project.sh reports the pr step missing or held, it prints
the step for the platforms the gates run on; it never writes a pipeline
file. Each form runs the same commands as the template: it extracts the
base revision's .specify/gates with git archive and runs that
pr-check.sh with GATES_RUNTIME_DIR, so a PR cannot replace the
check that judges it. Add it to the pipeline file that runs
verify.sh --boundary ci: doctor looks for the step there.
The step checks every commit in the pull request, including commits
made before it was added. An open branch with a protected-file commit
that carries no Protected-Change trailer (one made with --no-verify
before the trailers existed, say) fails it. Declare such commits in the
PR description, with a Protected-Change: <path> line per path and an
Approved-By: <name> line; pr-check.sh accepts declarations there.
GitHub: a step in the job that runs verify.sh --boundary ci, so the
required gates check covers it. That job checks out with
fetch-depth: 0 (without full history the base revision cannot be
read), and the workflow runs on pull_request with edited among its
types. A PR opened by Dependabot or Renovate is checked without its
description, which quotes upstream release notes nobody in the project
wrote; its title, protected changes and secrets are still checked. Add
other bots' logins to the list in GATES_PR_BODY.
# spec-gates pr step (GitHub): add under steps: of the job that runs
# verify.sh --boundary ci, so its required check covers it. That job
# checks out with fetch-depth: 0, and the workflow runs on
# pull_request with types: [opened, synchronize, reopened, edited].
- name: Check the pull request (text, protected changes, secrets)
if: github.event_name == 'pull_request'
env:
GATES_PR_TITLE: ${{ github.event.pull_request.title }}
GATES_PR_BODY: ${{ !contains(fromJSON('["dependabot[bot]", "renovate[bot]"]'), github.event.pull_request.user.login) && github.event.pull_request.body || '' }}
run: |
base="origin/$GITHUB_BASE_REF"
if git cat-file -e "$base:.specify/gates/pr-check.sh" 2>/dev/null; then
rt="$(mktemp -d)"
git archive "$base" .specify/gates | tar -x -C "$rt"
echo "pr-check: running the base revision's pr-check.sh ($base)"
GATES_RUNTIME_DIR="$rt/.specify/gates" bash "$rt/.specify/gates/pr-check.sh"
else
echo "pr-check: the base ($base) has no pr-check.sh (adoption PR); running the pull request's own copy"
bash .specify/gates/pr-check.sh
fi
GitLab: a job of its own, with full history (GIT_DEPTH: "0") and the
tools pr-check.sh needs, in merge request pipelines. With "Pipelines
must succeed" set, a failure blocks the merge.
In the GitLab template (extension/ci/gitlab/gates.gitlab-ci.yml), an
MR pipeline that a Renovate or Dependabot bot user started is checked
without its description, as on GitHub; the title, protected changes and
secrets are still checked. GitLab names no MR author, so the template
compares GITLAB_USER_LOGIN, the user who started the pipeline, with the
user names in its bots list (renovate-bot dependabot by default; put
your bots' user names there). A pipeline a person starts or retries
checks the description.
# spec-gates pr step (GitLab): add as a job to the pipeline file that
# runs verify.sh --boundary ci. pr-check.sh needs bash, git, jq and
# python3 (curl fetches a truncated description). Editing an MR title
# or description starts no pipeline; re-run it after such edits.
gates-pr:
stage: test
image: node:26-slim
timeout: 10m
variables:
GIT_DEPTH: "0"
before_script:
- apt-get update -q && apt-get install -y -q jq git python3 curl
script:
- |
set -e
bots="renovate-bot dependabot"
case " $bots " in
*" ${GITLAB_USER_LOGIN:-none} "*)
echo "pr-check: the MR pipeline was started by the bot user ${GITLAB_USER_LOGIN}; its description (quoted release notes) is not checked"
export CI_MERGE_REQUEST_DESCRIPTION="" CI_MERGE_REQUEST_DESCRIPTION_IS_TRUNCATED=false
;;
esac
base="${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}"
if [ -z "$base" ]; then
bash .specify/gates/pr-check.sh
elif git cat-file -e "$base:.specify/gates/pr-check.sh" 2>/dev/null; then
rt="$(mktemp -d)"
git archive "$base" .specify/gates | tar -x -C "$rt"
echo "pr-check: running the base revision's pr-check.sh ($base)"
GATES_RUNTIME_DIR="$rt/.specify/gates" bash "$rt/.specify/gates/pr-check.sh"
else
echo "pr-check: the base ($base) has no pr-check.sh (adoption MR); running the merge request's own copy"
bash .specify/gates/pr-check.sh
fi
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
Jenkins: a stage in the declarative pipeline's stages, on an agent with
bash, git and jq and a full-history checkout. Only the title is checked
(Jenkins exposes no description).
// spec-gates pr step (Jenkins): add as a stage to the Jenkinsfile that
// runs verify.sh --boundary ci. The agent needs bash, git and jq, and a
// full-history checkout; outside PR builds the check skips itself.
stage('PR check') {
steps {
sh '''
set -e
if [ -z "${CHANGE_TARGET:-}" ]; then
bash .specify/gates/pr-check.sh
exit 0
fi
base="origin/$CHANGE_TARGET"
if git cat-file -e "$base:.specify/gates/pr-check.sh" 2>/dev/null; then
rt="$(mktemp -d)"
git archive "$base" .specify/gates | tar -x -C "$rt"
echo "pr-check: running the base revision's pr-check.sh ($base)"
GATES_RUNTIME_DIR="$rt/.specify/gates" bash "$rt/.specify/gates/pr-check.sh"
else
echo "pr-check: the base ($base) has no pr-check.sh (adoption PR); running the pull request's own copy"
bash .specify/gates/pr-check.sh
fi
'''
}
}
One entrypoint
verify.sh --boundary agent|git|ci [--json] [--dry-run]
verify.sh --walk [--boundary agent|git|ci] [--json] [--dry-run]
Dispatch follows the policy's verify-quality.orchestrator:
none: per-tool walk (prettier, markdownlint, shellcheck) driven by the policy's include and exclude globs vialib/formatter-dispatch.sh. In a git work tree it skips untracked files git ignores (husky's generated.husky/_/, build output), since CI never sees them; a tracked file is checked even when an ignore pattern matches it (prettier runs with--ignore-path .prettierignore, so.gitignorenever hides a tracked file from it, while.prettierignorestill applies).task:task lint(error class) andtask test(warning class, or the classtest_severitynames:"test_severity": "error"makes a failingtask testfail the run), the fixed Taskfile convention.policy-inferseeds it when a Taskfile declares top-levellintandtesttargets.custom: a policy-supplied command, run from the project root, its exit code mapped through the hook's severity. Since 0.5.0 it runs from the project root whatever directoryverify.shwas started from; a command that relied on the caller's directory changes directory itself.
Every gate command can read the boundary it runs at from
GATES_BOUNDARY (agent, git, ci, or none for a run without
--boundary).
Every command the gates run (the orchestrator's, project gates, accept
blocks, the cover script) starts without git's per-repository variables
(GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE and the rest of
git rev-parse --local-env-vars). A git hook in a linked worktree sets
GIT_DIR and GIT_INDEX_FILE to absolute paths; a command that built a
throwaway repository with them set would act on the real one (#293). Its
own git calls find the repository from its working directory as usual.
To see what a commit holds, read the index git uses for it, which
git commit -a and git commit <paths> make a temporary one:
verify.sh exports its absolute path as GATES_GIT_INDEX_FILE
(outside a hook, the repository's own index), and
GIT_INDEX_FILE="$GATES_GIT_INDEX_FILE" git diff --cached --name-only
lists exactly the committed files.
Project gates. A project declares its own checks next to whatever
the orchestrator runs, under hooks.verify-quality.gates, an object
keyed by gate name:
"verify-quality": {
"orchestrator": "none",
"severity": "error",
"gate_timeout_s": 900,
"gates": {
"lint": { "command": "npm run -s lint" },
"typecheck": { "command": "npm run -s typecheck" },
"test": { "command": "npm test -- --coverage", "timeout_s": 1200 },
"build": { "command": "npm run -s build", "skip_at": ["agent"] }
}
}
They run after the orchestrator's gates, in key order, each as
sh -c "<command>" from the project root, and each is its own gate in
the text report, --json and the attestation. severity (error,
warning, info; default error) maps a non-zero exit as for any
gate, and the failure summary follows the rules below. Each runs under a
time limit: its timeout_s, else gate_timeout_s, else 600 seconds. A
gate over its limit fails with timeout after <n>s at load <x>, and its
process group is stopped (TERM, a two-second grace, KILL); a process
that leaves the group (a new session, a double fork) is not tracked. A
command that cannot start (exit 126 or 127) fails with command not found or not executable. Project gates are not read-only by contract,
unlike accept blocks: a gate may write files (a coverage report, a
build), and what it writes is the project's to manage.
Gate names match ^[a-z0-9][a-z0-9_-]{0,39}$ and may not take a
built-in name (prettier, markdownlint, shellcheck, task-lint,
task-test, custom, spec, contract, parity, policy, lock,
constitution). An older runtime refuses the new keys rather than
dropping the gates.
Declared skips, never at CI. skip_at keeps a slow or
network-bound gate out of an earlier boundary: ["agent"] keeps it out
of the Stop hook, ["agent", "git"] out of pre-commit too. CI cannot
be named: skip_at: ["ci"] is refused like any invalid policy (exit
1), because CI runs the full policy (constitution, Principle III). A
skipped gate starts no process and is reported by name, never as
passed: [skipped] build -- skipped by declaration at agent in the
report and --json, and "result": "skipped", "declared_skip": "agent"
in the attestation. The parity gate proves it: at CI every declared gate
must have run, and at an earlier boundary every declared gate that did
not run must carry a declaration naming that boundary; otherwise parity
fails with declared gates not run at <boundary>: <names>. Doctor lists
each gate with its severity, time limit and skips.
The built-in walk on its own. verify.sh --walk runs only the
built-in per-tool walk (prettier, markdownlint, shellcheck, as the
policy enables them), whatever the orchestrator: no contract, project,
spec or parity gate, and no attestation line. It is the stable way for a
custom command to include the built-in checks; doctor recommends it
when a custom_command or a project gate calls lib/formatter-dispatch.sh,
directly or one level down: in the npm, pnpm or yarn script the
command runs, or in a project file the command or that script names
(bash scripts/quality.sh). Deeper calls go unreported. Inside a gate run it joins that run's lock and prints one
##gates-fail## line for its first failure, so the calling gate's
summary names the failing file. A walk started from inside a walk
refuses (exit 1): the walk never runs the orchestrator, so a
custom_command that calls it cannot recurse.
A gate cannot run the suite it belongs to. Each gate command runs
with GATES_GATE_ROOT set to the project root, and a full (not
--walk) verify.sh run on that same root refuses with exit 1, so
the calling gate fails instead of recursing. Runs against other
directories (a sandbox, a fixture) are unaffected. A gate that runs
git commit in its own project, and so triggers the pre-commit gate
run, is refused the same way.
Exit codes: 0 green, 1 internal error, 2 gate failure. --json
emits a single machine-readable object for workflow steps and CI.
A failing step names its own failure. A failing or warning tool,
task or custom step keeps the last 2000 bytes of its output as the
gate's detail. The one-line text report reads the whole output: the
last line that carries ##gates-fail## <text> wins (the marker itself
is stripped from the report and the detail, which keep the text; the
detail leaves a marked line out when another line of the output
already holds its text, such as a linter's finding or a nested
verify.sh --walk report line, and always for the file linters).
The file-linter gates mark their first finding that way (a prettier
[warn] <file> line, a markdownlint <file>:<line> finding, shellcheck's
<file> line N: SC<code> ...), since their output opens with banners and
ends with a footer; without a marked line they show their first
non-empty line. A task, custom or project gate step without one shows
its last non-empty line, where such steps print their verdict, preceded
by its first non-empty line when the two differ (<first> | <last>), so
a tool that names the file and line first and the message last keeps
both.
A failing step keeps its output. The full output of each gate that
fails or warns (markers stripped) goes to
.specify/gates/output/<gate>.log, and the text report names it on the
next line (output: .specify/gates/output/custom.log). At the ci
boundary the report also prints each failed gate's output in the job
log, so the cause is there without a local rerun: in a collapsed group
on GitHub Actions (::group::), in a collapsed section on GitLab CI,
elsewhere its last 40 lines. Every line is indented, so no line of a
gate's output can act as a workflow command. Only
the run that holds the gate lock writes there, and a gate's file changes
only when that gate runs: a pass removes it, a failure or warning
replaces it. A gate a run does not run keeps the file of its last run,
so an agent-boundary run that skips a gate by declaration leaves the ci
run's output for it in place; a gate removed from the policy leaves its
last file until you delete it. --dry-run and a run nested in another
(a walk inside a gate command, a run in an accept block) write none. The directory ignores itself (its own .gitignore
of *), and the attestation still carries no tool output.
GATES_VERBOSE=1 streams each gate's output to stderr as it runs, under
a gates: output of <gate> line. Its output then passes through tee,
so a background process a gate command leaves running keeps the gate
open until that process exits (for a project gate, at most its time
limit, after which the gate fails as a timeout).
Output and secrets. The forge masks registered secrets in the job
log, never in a file: an uploaded artifact holds the output as written,
and anyone who can download it reads it (on a public GitHub repository,
any signed-in user, for 90 days by default). So at the ci boundary
each kept file is first scanned with the rules the pre-commit secret
scan uses (lib/secrets.sh). When one matches, or the scan cannot run,
the file is deleted and the gate's output is left out of the log too,
its summary included: the report reads output withheld: it looks like it holds a secret (<rule>); run the step locally to see it. Locally the
file is kept (it is ignored by git). The scan finds the token shapes it
knows; a value that only the forge knows is secret is masked in the log
and nowhere else.
The templates therefore upload no file. A project that wants the files
as an artifact adds the step itself, on a private repository only, with
restricted access and a short lifetime, and the scan above still runs
first. GitLab: artifacts: { when: on_failure, access: developer, expire_in: 1 day, paths: [.specify/gates/output/] }. GitHub: an
actions/upload-artifact step with if: failure() and
retention-days: 1. Jenkins: archiveArtifacts in a post { failure { } } block, readable only by those who may see the build.
One gate run per working tree. Two runs in one tree see each
other's writes (build output, test files) and fail each other, so a run
holds .specify/gates/.lock (a directory, created with mkdir; it
records the run's pid, boundary and start time, and project.sh lists
it in .specify/gates/.gitignore). A second run at the agent boundary
skips with gates: skipped: the gate run of pid N (git) is in progress
and exit 0, so the Stop hook never waits on a commit. It names what it
does not run: deferred: <gates> (the gates it would have run) and the
gates its policy skips at the agent boundary by declaration; with
--json, a {"result":"skipped",...} object with "deferred": [...]
(null when the policy cannot be read at that point) and
"declared_skip": [...]. Principle III
requires every gate a boundary does not run to be named. At the git and CI boundaries (and
without --boundary) it prints gates: waiting for the gate run of pid N (<boundary>) once and waits up to GATES_LOCK_WAIT_S seconds
(default 600), then refuses with exit 1, naming the holder. A lock
whose process is gone is stale: the next run takes it over and says so.
The lock is released on every exit, including an interrupt, and a run
started from inside the holder (an accept block, a hook it triggers)
finds the holder's pid in GATES_LOCK_PID and runs without the lock.
--dry-run takes no lock.
An invalid policy runs no gate. Before any gate, verify.sh validates
the policy it enforces (policy.json, or policy.effective.json in a
contract repo) with the same check as policy.sh validate: malformed
JSON, a missing hooks object, an unknown field or a wrong value (a
severity of Error, a spec.timeout_s of "abc", an
attestation.max_records of 0) is refused with exit 1 and the
validator's errors, exactly like a missing policy. The policy reader treats
an unreadable field as its default, so without this check a typo would
silently drop gates while every boundary passed. The git and CI
boundaries fail on exit 1. The Stop hook treats it as a setup error: it
prints the errors and lets the session stop, because an agent must never be
locked in by a broken configuration. The other agent hooks match:
protect-files asks before every edit (it cannot tell what the policy
protects), post-edit and format-changed format nothing, and doctor
reports the policy as [MISSING]; project.sh refuses to project under
it. A bad --boundary value, a repeated --boundary, --boundary or
--accept without a value (an empty value included), or an --accept
name that is not a feature, is a usage error (exit 1)
refused before any gate runs.
A missing --boundary warns. Without it, verify.sh runs every
gate, with boundary unspecified in the report, the --json object and
the attestation, and the exit code the gates decide. It prints one
deprecation warning on stderr naming --boundary agent|git|ci (stdout,
and so --json, is unchanged); a later release may refuse such a run.
project.sh and doctor ([rec]) name the lines in package.json,
Taskfile.yml/Taskfile.yaml and the Makefile that call
gates/verify.sh without --boundary.
Environment overrides are visible. GATES_POLICY_FILE replaces the
whole policy, so set on one command it would drop every gate the
repository declares. The git hooks, verify.sh --boundary git|ci,
verify.sh without --boundary and pr-check.sh ignore it and enforce
the policy the repository commits; verify.sh at the agent boundary
applies it.
Either way the run says so: a stderr line, an [override] policy line in
the text report, and a policy_override object (file, applied) in the
--json output and the attestation, whose policy_sha256 hashes the
policy actually enforced. The canary suite therefore probes its sandboxes
with their own policies under an inherited override. Other variables
that change what is enforced are reported where they act: GATES_SKIP=1
(the pre-commit quality gate) prints that verify did not run, and
GATES_SPEC_EXEC records the spec gate as skipped. validate-bash asks
before a command sets GATES_POLICY_FILE, GATES_SKIP,
GATES_ALLOW_MAIN_COMMIT, GATES_RUNTIME_DIR, GATES_TEST or
GATES_SPEC_EXEC; unsetting them (env -u) is allowed.
Evidence, canaries, and verified parity
Three separate silent-no-op enforcement bugs in this project's own history taught one lesson: an enforcement layer must prove it is still enforcing.
Attestation records. Every verify.sh run appends one compact JSON
line to .specify/gates/attestations.jsonl and embeds the same object in
--json: schema version, timestamp, boundary, the SHA-256 of the policy
file, and one entry per gate (resolved binary, detected version, lockfile
pin, candidate and checked file counts, result, duration). The log is
capped (attestation.max_records, default 200) by append plus atomic
rewrite, is gitignored by default, and never contains file contents.
Evidence loss cannot change a gate outcome: a write failure is a stderr
warning, never a result. doctor reads the latest record and fails on the
no-op signature, result=pass with candidates > 0 and checked = 0,
because no legitimate run looks like that.
Timeline and progress. Two optional files show a run while it
happens. GATES_TIMELINE=<file> gets one tab-separated line per gate and
per accept block as each ends: name, boundary, start and end (epoch
seconds), result, reason (fixed strings, or a covered block's line;
never command output). The line always has six fields, so an empty reason
leaves a trailing tab. Block names are accept <feature> <task-id>#<n>.
A CI step can render sections from it; for GitLab, for example:
while IFS="$(printf '\t')" read -r name _ start end result _; do
id="$(printf '%s' "$name" | tr -c 'A-Za-z0-9_' '_')"
printf '\033[0Ksection_start:%s:%s\r\033[0K%s (%s)\n' "$start" "$id" "$name" "$result"
printf '\033[0Ksection_end:%s:%s\r\033[0K\n' "$end" "$id"
done <"$GATES_TIMELINE"
GATES_PROGRESS=<file> gets gates: <HH:MM:SS> start <name> as each
gate and block starts and gates: <HH:MM:SS> end <name> <result> <n>s
as it ends. The pre-commit hook sets GATES_PROGRESS=/dev/stderr when
its stderr is a terminal and the variable is unset, so a long commit
shows what is running; otherwise its output is unchanged (and, as
before, it runs no gate when nothing is staged). verify.sh reads both
variables once and unsets them for everything it starts, so a nested run
(a fixture in an accept block, a canary sandbox) never writes to the
caller's files. A file that cannot be written warns once and changes no
outcome. A timeline or progress file inside the project is written
between accept blocks, so each block then takes its own read-only
snapshot and the lines never count as a block's writes.
Canaries. canary.sh (projected next to verify.sh) plants known
violations in mktemp sandboxes and requires the real entrypoints to
reject them, 19 probes in all:
- the format, markdown and shell probes run through
verify.shitself; when the tool is missing but the policy enables it, the probe fails as an enforcement gap, so a CI job that installed no linters is red; - the hook probes pipe crafted tool calls through the projected hooks, the command and file probes once with jq and once without it;
bulkandlocalprove the bulk-staging setting and that a project rule inhooks.local.drefuses its command while a plain command passes;- the PR-hook probe needs a clean PR allowed as well as bad ones refused, because a hook that fails to parse also exits 2 and would otherwise count as blocking;
- the git probes commit in sandbox repositories with the projected hooks installed: a key-shaped string and a token assignment (secret scan), a protected file without its trailer, and a message naming a branding term;
prrunspr-check.shover a sandbox range with an undeclared protected change and over a description containing an AI-ism;projectdeclares a project gate that always fails and skips the agent boundary:verify.sh --boundary cimust fail naming it, and the agent run must report itskipped by declaration at agent, since a declared skip never reaches CI (constitution, Principle III);covereddeclares a covering script that vouches for a failing accept block at agent and git:verify.sh --boundary cimust fail the spec gate on that block, since CI never asks the script, and the git run must report the block covered;worktreecommits in a linked worktree of a sandbox through a project gate that builds a throwaway repository (git init,add,commitin a temp directory): the sandbox's main repository must stay non-bare and the worktree's index unchanged, so gate commands cannot reach the caller's repository through git's hook variables (#293);spec,errexitandcontractare described with their gates below.
Hooks run by path, as Claude Code runs them, so their shebang picks the
interpreter (bash 3.2 on macOS). The suite copies the runtime from the
projected directory, so a broken projected gate, not just a broken source
tree, is what gets caught. Probes never read or write user project files.
An accepted probe fails the suite naming the gate; project.sh runs the
suite after every projection, and CI runs it on every build.
Pins-based parity. "Same script, same policy" is an argument; the
parity gate checks it. A synthetic parity gate inside
verify.sh compares every tool's resolved version against the project's
lockfile pin, and the record's policy hash captures policy identity, so
agent, git and CI runs are proven equivalent transitively. The lockfile is
the shared source of truth; no attestation has to travel between
boundaries. Drift fails the run by default (attestation.parity: error);
tools with no pin source are attested but exempt. When a node linter's
entry in node_modules/.package-lock.json (what npm last installed)
differs from package-lock.json, the failure says node_modules was installed from another lockfile; run npm ci: the usual cause is a branch
switch since the last npm ci. The gate still fails until the install
matches.
Spec conformance: acceptance criteria as executable gates
The tool gates hold code to linters; the spec gate holds a feature to
its own specification. It runs inside verify.sh on every run, after the
tool gates and before parity:
-
Discover: direct children of
specs/containing aspec.md, in lexicographic order, minusspec.excludeglobs. Nospecs/directory means zero features and a trivial pass. -
Parse: an awk fence state machine reads each feature's
tasks.md.```acceptfences become criteria (commands, optional# verifies:label, owning task), and checkbox counts are taken fence-aware so a- [ ]inside a code sample never counts. Malformed shapes (an unterminated fence, a command-less block, a block with no preceding task, a!command before the block's last command) fail the gate atspec.severitynamingtasks.md:<line>. Parsing is fail-closed by design: a criterion the gate cannot read is a red run, not a skipped check. -
Execute: for features whose
spec.mdsays**Status**: Complete(and any feature named via--accept), blocks run serially from the repository root underbash -eo pipefail, so a failing command or pipeline stage on any line fails the block, not just the last one. A!-negated command is exempt from errexit, which is why the parser refuses one that is followed by another command line (the body and terminator of a heredoc it feeds are not command lines);test -z "$(...)",if ...; then exit 1; fiand! cmd || exit 1fail the block wherever they stand. A pipe intogrep -qorheadfails a block that holds when the writer prints on after the reader has exited: SIGPIPE, which the failure names next toexit 141.out="$(cmd 2>&1)"; grep -q pat <<<"$out"avoids it, and doctor recommends that form for each such pipe. Output is captured (shown only on failure), with a per-block watchdog (spec.timeout_s, default 30s) that stops the block's whole process group (the failure readstimeout after <N>s at load <1-minute load average>, the load from/proc/loadavg,sysctl vm.loadavgoruptimewhere one can be read, so a slow block on a loaded machine is not mistaken for a hang), and snapshots around each block:git statusplus a content hash of every dirty or untracked file, git config in every scope, the hooks directory git uses, the files in.git/info/(attributes, exclude, sparse-checkout), every index entry flagged skip-worktree or assume-unchanged (the flag and a content hash, sincegit statusno longer reports edits to such a file), this worktree's path and lock when it is a linked one,HEADand every local ref, and gitignored files (checked by ctime). A block that changes any of them, including a write to a file that was already modified, agit config core.hooksPath, a commit, a tag or a new branch, fails its criterion, and nothing is ever auto-reverted. That includes a build into an ignored directory such asdist/: on a fresh CI checkout the directory is new and the block fails, while locally, where it already exists with identical content, the block may pass. A block that needs build output writes it to"$(mktemp -d)"and reads it from there. Repacking (git gc,git pack-refs) changes how git stores objects and refs, not what they say, and is not checked; neither is.git/info/refs, the ref list thatgit gcandgit update-server-infowrite for dumb transports. Other worktrees are left out: theirHEAD, their per-worktree refs, their entries, and the refs of the branches they have checked out (or are rebasing) before or after the block. A commit, a branch switch, or a worktree added or removed in a sibling worktree during the run does not fail a block. The flip side: a block that adds a worktree outside the project, or commits in another worktree, is not caught either (one inside the project shows up as an untracked directory).No process may outlive its block. Every process the block starts inherits the write end of a FIFO on descriptor 7, which the gate reads to EOF: the block ends when the last holder has exited. That EOF is awaited for the rest of the block's time limit, so a child the block killed without waiting passes however long its exit takes on a loaded machine, and no fixed grace decides. A process still holding the descriptor at the limit, or left in the block's process group after the EOF (one that closed the descriptor), is stopped and fails the block with
left a process running after it exited (stopped). A child that leaves the group or the session (set -m,setsid, a double fork) is found by the same descriptor, or byGATES_SPEC_BLOCK=<id>in its environment, which the gate looks for in/proc/<pid>/environon Linux and inps -Eelsewhere. What is found is killed, and the block fails withleft a detached process running (stopped). Not found: a process that closed descriptor 7 and also started a program without the marker (env -i,env -u GATES_SPEC_BLOCK, or overwrote its environment in memory). On macOSpsshows no environment for Apple-signed binaries (/bin/sh,/bin/sleep,/usr/bin/git,/usr/bin/perl), so there only the descriptor finds them: a/bin/shchild started through Node'schild_processor Python'ssubprocess, which pass no extra descriptors, is not seen on macOS. The process table is read once, before the after-snapshot, so a write such a process makes before then is still caught as a mutation; a later one is not.spec.snapshot_excludeexempts untracked or ignored paths another process writes during the run;cache/names the directory and everything under it, likecache/**, and a pattern of only*,?and/(which would exempt everything) makes the policy invalid. Editor temporary files are exempt without it, at any depth:*.swp,*.swo,*~,.#*,#*#and vim's4913write probe, which an editor holding a file open writes while a block runs. So is the state a Claude Code memory plugin keeps in the background,.claude/mind.*(its store, locks and write-ahead log, #327); what an agent edits under.claude/on purpose, such as settings or skills, stays checked. A.gitignoreentry is no substitute, since ignored files are checked too. One limit: inside a directory that is ignored as a whole, a new or deleted entry also changes the directory, and that change still counts, since it may be a deleted file; exempt such a directory throughspec.snapshot_excludeif an editor works in it. Writes inside a nested repository or worktree (a directory below the root with its own.git, such as an agent's worktree under an ignored.claude/worktrees/) are left out of the ignored-files check by default; a nested repository that appears in the working tree during a block still counts. Outside a git work tree there is nothing to check against, so blocks fail closed. -
Enforce: a Complete feature fails the
specgate on any unchecked task or failing block, naming the feature, the task or criterion, and the cause. Incomplete features are informational, counted on one line (spec: <n> informational, <m> enforced -- ...);GATES_SPEC_VERBOSE=1lists each instead (spec: <feature> -- N criteria parsed, not enforced (Status: ...)), and--jsoncarries every feature's outcome.Completeis the only token that enforces:Done,ImplementedorComplete (merged)do not, and there is no setting to add one. A Complete feature with zero blocks is flagged as having nothing executable to hold it to, but does not block. An enforced feature's blocks run at every boundary, each agent Stop, each commit and CI, so a block that takes seconds or reaches the network costs that on every turn; doctor's nudge to setCompletesays so.
Covered accept blocks. A project's own test gate often proves what
an accept block would re-run seconds later. spec.cover lets a project
script vouch for that, at the earlier boundaries only:
"spec": {
"severity": "error",
"cover": {
"script": "scripts/accept-covered.sh",
"at": ["agent", "git"],
"timeout_s": 30
}
}
At a boundary in at, before each accept block of an enforced (or
--accepted) feature, the spec gate runs
<script> <feature> <task-id> <block-file> from the project root, under
the gate watchdog, with stdout captured and stderr discarded. Exit 0
with exactly one non-empty line covers the block: it does not run, and
the line (control characters removed, cut to 200 characters) is its
reason. Anything else (another exit code, no line, several lines, the
time limit, a script that is not executable) runs the block as before,
so the script can never fail a block. The script's own limit is
spec.cover.timeout_s (default 30 s), separate from the block's
spec.timeout_s (default 30 s): a script that runs out of it costs its
limit and then the block's full run. Such a block's reason, in the
report, the attestation and the timeline, begins with
covering timed out after <N>s; block ran. The guards:
- Never at CI.
attakesagentandgitonly;"ci"is refused like any invalid policy (exit1), and a run without--boundarycovers nothing. The parity gate also fails at CI if any block was covered, and thecoveredcanary proves a script that vouches for a failing block cannot make CI pass (constitution, Principle III). - Protected. The script is protected at every boundary like
policy.json, whateverprotected_files.extrasays: a commit or pull request that changes it needsProtected-ChangeandApproved-By, and the agent hooks ask before an edit. A declared script that is missing, or resolves outside the project, refuses the run (exit1); doctor reports it[MISSING], and a script that is not executable as a[rec](every block then runs). - Named. A covered block is
<feature> <task-id>#<n>(<n>is its position among its task's blocks). The report shows-- covered: <reason>(covered (informational)for an--accepted incomplete feature), the spec gate's summary names every covered block (so--jsondoes too), and the attestation records it withresult: covered, the reason anddeclared_skip, the same field a gate skipped by declaration carries. - A weakening. Adding
spec.cover, or a boundary toat, is a weakening deviation under a policy contract.
A covered block counts in the spec gate's checked total, so a run in
which every block was covered is not taken for a no-op. After the script
runs, the next block takes a fresh read-only snapshot, since the script
may write to the tree.
Recursion guard. An accept block that invokes verify.sh (this
repository's own blocks do) would re-enter the spec gate and recurse.
Blocks execute with GATES_SPEC_EXEC=1 exported, and verify.sh runs no
accept blocks when it is set. Since any caller can set it, the spec gate
is then reported as skipped with the reason (text, --json, and the
attestation), and validate-bash asks before a command that sets it.
Consumers that must probe the spec gate from inside a block (the canary
suite, the test suites) clear the sentinel explicitly for their sandboxed
runs.
Evidence and self-test. The attestation record gains a spec gate
entry (candidates = features, checked = blocks executed or covered)
and a top-level spec object with per-run counts and per-feature
outcomes (enforced-pass | enforced-fail | informational | no-criteria).
Each feature result lists every block it evaluated in blocks, in
order: task, ordinal, verifies, result (pass, fail,
timeout, mutation, covered), a fixed reason (or a covered
block's line) and duration_s; blocks_covered counts the covered
ones. A spec
canary projects a sandbox feature marked Complete with a false accept
block and requires the sandboxed gate to reject it: stubbing the block
runner to a no-op fails the canary suite naming the spec gate. The
errexit canary plants a block whose first line fails and whose last
passes, so a runner that judges a block by its last command alone fails
the suite too. doctor
reports what the gate sees (features, blocks, complete count), fails on
parse errors, and nudges when every task is checked but the Complete
flip is missing.
Policy as a versioned contract
The tool gates hold code to the policy; the contract gate holds the
policy itself to an organization's baseline. A repository opts in by
declaring extends (source and version) in policy.json, which turns that
file into an overlay on a versioned upstream document:
- Sync (the only network moment).
contract.sh syncfetches the declared version (shallow by tag, with a full-clone fallback for commit ids; branch names are refused, since a moving pin is not a pin), validates it against the policy schema, refuses chained baselines, and writes three committed artifacts: the canonicalized snapshot (baseline.json), the pin (baseline.lock.json: source, version, SHA-256 digest), and the materialized effective policy (policy.effective.json), a deterministic recursive merge where the overlay wins and arrays replace wholesale. - Enforce. Every boundary reads the effective policy through the same
resolver.
GATES_POLICY_FILEtakes precedence where it applies (the agent boundary and the library seams the test suites use); the git and CI boundaries ignore it (see One entrypoint). The attestation'spolicy_sha256hashes what was actually enforced. - Prove (offline, every run). The synthetic
contractgate runs before the tool gates (policy integrity precedes policy enforcement) and proves four invariants from local files alone: artifacts present, snapshot matching the pinned digest, declaration matching the pin, and the effective policy matching a byte-for-byte recomputation. Any violation fails closed, naming the drifted artifact and the repair command.
Transparent deviation. Overlays may override anything, including
weakening baseline rules, but never silently. Overrides on fields with a
defined order (enabled true→false, severity along error > warning > off, narrowed include, widened exclude) are classified weakened;
other overrides are changed; strengthenings and additions are ordinary
overlay behavior. The inventory is recomputed live from snapshot and
overlay (it cannot go stale), printed informationally without affecting
the exit code, counted in the attestation contract object, and reused
verbatim by propose.
Reviewable drift, both directions. sync --update [version] moves the
pin to an explicit version or the highest tag (an awk numeric comparator,
since BSD has no sort -V), building the change on a
gates/baseline-<v> branch in a temporary worktree so the checkout keeps
enforcing the old pin until the branch merges. propose applies the
deviating paths onto the baseline document in a temporary clone and
delivers it upstream as a branch and PR (or a patch under
.specify/gates/proposals/ when gh cannot), carrying the origin, the
pinned version, per-deviation classification, and a required rationale.
Evidence and self-test. Attestations gain a contract gate entry and a
top-level contract object (source, version, digests, deviation counts). A
contract canary syncs a sandbox against a fixture baseline inside the
sandbox, tampers the effective policy, and requires the sandboxed gate to
reject it. doctor reports the full contract state from local information
and fails on exactly the invariants the gate blocks on. Repositories
without extends see none of this machinery.
Constitution as an enforceable contract
A constitution is a set of claims about how a project behaves. Left as
prose, those claims drift from the enforcement that is supposed to back
them: the document says commits to main are refused while the git
boundary quietly allows them. Feature 004 binds each principle to the
boundary that proves it.
Elicit, then annotate. /speckit.gates.constitution interviews the
project into a profile (type and postures), then filters a bundled corpus
of provenance-carrying fragments into a candidate menu (constitution.sh fragments, mandatory tier first, filtered by project type). Each principle
the user keeps is materialized by constitution.sh draft into a
byte-deterministic document carrying one enforcement marker per principle:
<!-- gates:enforce surface=git-hook ref=pre-commit -->
The marker is an HTML comment (invisible when rendered, surviving prettier
and the core command's fill and version pass) bound by position to the
principle heading above it. Principles are the ### headings under
## Core Principles; sub-headings in other sections (Additional
Constraints, Governance) are prose, and a heading or marker inside a
fenced code block is example content, never a principle. The grammar is fixed: a surface from
policy | agent-hook | git-hook | ci | accept | scanner | prose, a ref
required for all but prose, and an optional expect for policy surfaces.
A malformed marker, or one outside Core Principles, is fail-closed: check
and doctor fail naming constitution.md:<line>, because an unreadable or
unchecked claim is worse than no claim.
Align. constitution.sh align evaluates, per annotated principle,
whether its surface is actually wired, all from local files with no
network: a policy key present in the effective policy (and equal to
expect; a list or object must be non-empty, and expect names an entry
the list contains or a key the object has), the ref read as a full dotted
path (hooks.markdownlint.severity; a ref not starting with a top-level
section such as git or attestation is short for hooks.<ref>); an
agent-hook present, executable and referenced in settings.json; a
git-hook installed, executable and delegating to the runtime; a ci
pipeline with a live verify.sh --boundary ci step that also runs the
named template step (gates, canary, pr) or, for any other ref, names
it, where live means what doctor's CI drift check reads (below); an
accept block that parses
and verifies the named criterion; a scanner rule in the tool's config.
Each principle is active, missing (with a concrete proposed change), or
pending-boundary (the whole boundary is not projected yet). A policy
proposal follows policy.schema.json, so applying it makes the principle
active; a marker no valid policy can satisfy (a path the schema lacks, an
expect outside the allowed values or below the schema's minimum) is
proposed as an annotation fix instead. align and check refuse (exit
1) a policy verify.sh would refuse, whether named with --policy or
resolved, since nothing in it is enforced. Proposed policy changes target the overlay, so with a live contract they flow
through sync into the effective policy like any other deviation. align
never writes; applying is the session's job, change by change, with
approval.
Prove. constitution.sh check and the doctor constitution section
report one line per principle (enforced | gap | prose-only) on every run
and exit non-zero on any gap or malformed marker, at fixed severity. A
constitution with no markers gets one informational nudge and never fails;
prose principles are listed and never checked. The corpus adopts the
spec-kit-charter registry
layout (manifest.yml + fragments/<category>/<name>.md), so charter
consumes each fragment's body while spec-gates consumes its frontmatter:
one registry, two consumers, no converter.
Projection and upgrades
Why projection, not symlinks or plugin-resident hooks
The runtime is copied into .specify/gates/ and .claude/hooks/gates/.
Three reasons: enforcement must survive the extension being removed;
collaborators who clone the repository get enforcement without installing
anything; and CI can run the entrypoint from the checkout with no network
access. The cost is that projected copies can drift from the extension
version or be edited locally, which is what the rest of this section
manages.
One reviewable step
.specify/extensions/gates/runtime/project.sh does the whole projection in
one invocation: it copies the runtime, sets execute bits (including on the
installed extension's git hooks, which Spec Kit's zip extraction leaves
non-executable), merges the agent hooks into .claude/settings.json
append-only, installs or wires the git hooks, writes the manifest, and
proves the result with the canary suite and the git probe. --dry-run
shows the plan first, and a second run changes nothing. One command means
one approval, where a permission classifier would refuse dozens of
individual file writes. It never writes policy.json; when a release adds
a policy setting (marked x-since in the schema), project.sh lists it
once, on the first upgrade that ships it, for the maintainer to adopt in a
reviewed change.
Local edits survive upgrades
project.sh records a hash of every projected file in
.specify/gates/.projected.sha256, with the version that wrote it. On the
next upgrade, a file that no longer matches its hash is a local edit: it is
reported (exit 3) and nothing is written until the maintainer keeps it,
which holds it in .specify/gates/.upgrade-holds from then on, or takes
the new version (--take-upstream, which also releases an existing hold).
A deletion is never held: every projected file is run by a hook, a gate,
the canary suite or CI, so --keep-local on a deleted file is refused,
and a held file that is missing fails project.sh and doctor until
--take-upstream restores it. Doctor recommends doctor.sh --canary
while any file is held, since only the canaries show that a held edit
still blocks.
Doctor flags a held file whose upstream copy changed since the hold, so a
hold never silently pins an old version of a hook. A project projected by 0.3.x has no manifest; there
project.sh compares each file against the hashes of what the 0.3.x
releases shipped (lib/known-releases.sha256), so only real edits stop
the upgrade. Doctor reports the same state between upgrades: local edits
that are not held, holds that went stale (the held file now equals the
installed copy), and CI pipelines missing a template step (the gates,
canary and PR-check steps, recognized by command on GitHub, GitLab and
Jenkins; ci:<step> in the holds file records a deliberate omission).
Only a live step counts: one that runs on a push or pull request and can
fail the pipeline. Doctor first removes, as text, what never runs or can
never fail: comments (# in YAML, // and /* */ in a Jenkinsfile);
steps or jobs under if: false; a command only printed by echo or
printf; a command followed by || true, || :, || exit 0 or
|| echo; a command with --dry-run; anything after an unconditional
exit 0 in the same run block; GitHub continue-on-error: true on the
step or job, and a workflow whose only triggers are workflow_dispatch
and schedule; GitLab allow_failure: true, when: manual or
when: never on the job, rules that never let a job run (every rule up to
the first unconditional one says when: never or manual; under
workflow: this stops the whole file), an only:/except: that keeps a
job out of branch and merge request pipelines (only: [tags],
except: [branches]), and a hidden .name: job nothing extends; a
Jenkins stage under when { expression { false } } and an sh step with
returnStatus: true.
The gates step is then proven, not searched for: denying inert forms one by one always leaves another. It counts only when all of these hold:
- the command, after one layer of quotes, is exactly
bash .specify/gates/verify.sh --boundary ci(bash,./and the directory are optional;--jsonmay come before or after--boundary ci), with nothing else on the line: no;,&&,||,&,|,:,if,exit,true, env prefix, second--boundaryor--dry-run; - it is the whole value of a GitHub
run:, a GitLabscript:orbefore_script:item (anafter_script:failure does not fail the job), or the string of a Jenkinsshstep (sh '...',sh(script: '...')); or the last line of such a|block or'''string. Nothing before it in the same shell (earlier lines of the block, earlier GitLab script items) holds a heredoc, atrap, anexit 0or a\continuation into it. One more form saves the status for steps that must always run:rc=0(orrc=) on a line before the step, the step followed by|| rc=$?, andexit "$rc"(orexit $rc) as the last line of the same block, with nothing between that exits, traps, execs, opens a heredoc, assignsrcor continues a line (any variable name, the same in all three places); - in place of the
verify.shcommand, a script of the repository may stand:[bash |sh ][./]<path>naming a file outside.specify/gates/(no.., not absolute) whose own text runs the step as its last command or in the save-and-exit form. Scripts are followed one level: a script that script calls is not read. Thecanaryandprsteps also count in a repository script a live pipeline line runs, one level deep; - a GitHub workflow has
pushorpull_requestamong itson:events; - the pipeline file never names
GATES_SPEC_EXEC(skips the spec gate) orGATES_POLICY_FILE(replaces the policy), in anyenv:,variables:orwithEnv; - a Jenkins
shstep is not insidecatchError,warnErrorortry.
A pipeline that calls verify.sh but has no proven gates step fails, and
the line names what to change; a repository with no such pipeline at all
gets a recommendation. verify.sh itself refuses a repeated --boundary.
A ci:<step> hold for a step the pipeline runs is stale and fails; one
naming no template step gets a recommendation to remove it. A hold for a
step the pipeline lacks is a [rec], not an [ok], naming the check CI
gives up (for pr: PR titles, descriptions and Protected-Change
declarations are not checked in CI); the pr step can be added on its
own (see "Adopting only the pr step" above).
The check reads files, so it has limits. Read as live: a GitHub
if:, continue-on-error: or event filter (branches:, paths:)
computed by an expression or narrowing the trigger; conditional GitLab
rules (an if: that never matches, an earlier conditional when: never),
a job reached only through extends: or an alias, and an exit 0 in
before_script: ahead of a script: step; a GitHub shell:
override; CI/CD variables set outside the file (GitLab project settings,
Jenkins job configuration) and Jenkins triggers, which live in the job,
not the Jenkinsfile; a Jenkins when other than a literal false; a
Jenkins step in a closure that is never called. Rejected although it may
be fine: the gates command followed by other commands in the same block
(move it to its own step, or make it the last line), and a path written
with a variable, or a script called more than one level down. The canary
and PR-check steps are still recognized by command after the removals
above, not proven. The proof that the gates
ran is the CI run's own log: verify.sh prints a
gates: boundary=ci failed=N warnings=N summary line.
Interrupted and unusual installs
Spec Kit's extension remove and extension add are two commands, not a
transaction. If the add fails, the projected copy of project.sh
(.specify/gates/project.sh --check) reports the half-done upgrade and the
command that finishes it, and doctor fails until it is done. A 0.3.x
projection has no projected project.sh: re-run the add, then the
installed project.sh. The git hook stubs in .git/hooks are shared by
every branch and worktree and run the checked-out branch's projected
hook; the pre-merge-commit stub falls back to the branch's pre-commit
hook on a branch projected before that hook shipped (0.3.x), so rolling
back to 0.3.x means removing that stub as well. A checked-out tree with
no runtime and nothing tracked under .specify/gates (a linked worktree
of a repository that keeps .specify/ untracked, or a branch from before
adoption) has nothing of its own to run. The stub then looks at the main
worktree of the same repository (the parent of
git rev-parse --git-common-dir, never a path from elsewhere): when its
hook declares that it loads its runtime from GATES_RUNTIME_DIR, the stub
runs it with that variable set, judging the checked-out tree; otherwise
it skips with one line naming that runtime and why it cannot judge the
worktree, or that there is no runtime at all. The projected hooks declare
it: they load their libraries, .runtime-version and the
main worktree's policy from that runtime and scan the worktree's index,
so the secret scan, the forbidden files, the main-branch block and the
message rules apply there. A policy file inside the worktree is never
read, GATES_POLICY_FILE stays ignored, a GATES_RUNTIME_DIR other than
the main worktree's .specify/gates is refused, and verify.sh does not
run (it judges a projected tree; the hook says so). A
specify extension add --dev install renders the gates skills as symlinks
that exist only on the author's machine; doctor fails on symlinked,
dangling or missing skills. doctor --installed-only, run from the
installed copy, checks an install with nothing projected yet.
Toolchain parity
Parity has an analogous requirement on the toolchain itself: a linter's
findings depend on its version, so "the same policy at every boundary" is
only true if the same tool versions run at every boundary. Node linters
are pinned by package-lock.json. Tools npm cannot pin, currently
shellcheck, are declared with mise or in .tool-versions (asdf format),
where the gap is not theoretical: Ubuntu's apt ships 0.9.0, which reports
SC2015 findings that 0.11.0 does not, so an unpinned CI turns a green
local run red for reasons no diff explains. The parity gate reads every
source, so drift at any boundary fails the run naming the tool, the
resolved version and the pin, instead of surfacing as mysteriously
different lint output.
The pin sources, in precedence order:
package-lock.json, for the node-resolved linters (prettier, markdownlint-cli2) only. The npmshellcheckpackage is a downloader wrapper whose version is no shellcheck release, so it pins nothing. The gate runs a shellcheck on PATH other than that wrapper when there is one, since the pins below describe such an install, and attests the version the binary it ran reports, never the wrapper'spackage.json.- mise: the
[tools]table of the first project config mise documents that names the tool (.mise.toml,mise.toml,mise/config.toml,.mise/config.toml,.config/mise.toml,.config/mise/mise.toml,.config/mise/config.toml), at the version themise.lockbeside it locks; without a lock entry, the config's version counts only when it is exact (x.y.z), since a request such as"latest"or"22"pins nothing. Keys may carry a backend ("aqua:koalaman/shellcheck","npm:prettier"), and the value may be a string, an inline table'sversion, or an array's first element.mise.local.toml,mise.<env>.tomlandconf.dfragments are not read: they are uncommitted or selected per run, so another boundary cannot share them. .tool-versions.
Two sources that pin a tool at different versions fail the parity gate
naming each source and version; the run does not pick one. A mise file
the gate cannot read (an unterminated string, a malformed table header, a
line that is no key = value) fails it naming file:line. The reader
is a small TOML subset in awk, so spec-gates adds no dependency for it.
Out of the project's lint scope
Projection has a second cost that is easy to miss: our files now live in
someone else's repository, so their repo-wide tooling reaches them. A plain
prettier --check . or markdownlint-cli2 "**/*.md" lints the projected
runtime and the installed extension against the consumer's style, and any
fix they apply is erased by the next upgrade. No shipped formatting solves
this, because every style choice fails somebody's config. Vendored content
belongs out of lint scope, the same way node_modules does. So the
extension ships a nested markdownlint config at its own root
(nearest-config resolution keeps our docs quiet under a default sweep),
and in a repository that uses prettier project.sh reports the missing
.prettierignore entries for .specify/gates/, .specify/extensions/
and .claude/hooks/gates/, appending them only with --add-lint-ignores,
since that file is the consumer's. An entry for a parent directory
(.specify/, .claude/**) counts as covering the paths under it. A packaging test asserts the shipped
tree stays clean under default tooling.
Threat model honesty
The agent boundary raises the cost of noncompliance; it does not make
noncompliance impossible. An agent with unrestricted Bash can, in
principle, rewrite its own hook wiring: .claude/settings.json, the
projected hooks in .claude/hooks/gates/ and the runtime in
.specify/gates/ are not protected by default. Add them to
protected_files.extra to have Write/Edit refused and Bash changes asked
about, as policy.json and the project's own rules are (the constitution
asks for both).
The Bash check is itself a heuristic over command text, which is why it
asks rather than claims to block.
Defense in depth is the point of the three-boundary design. Whatever an agent changes locally still has to pass the git hooks (whose own changes need a reviewed trailer when protected) and then CI and server-side branch protection. The boundaries an agent cannot touch backstop the ones it theoretically could.
CI is only as independent as the code it runs, and a pull request brings
its own copy of most of it. The PR check runs the base revision's
pr-check.sh and libraries, so a PR cannot replace the check that judges
its protected changes. The rest still comes from the PR head:
verify.sh, canary.sh and, on GitHub and GitLab, the pipeline file
itself, so a PR (pushed with --no-verify) can rewrite the steps that
run on it. The human backstop is required, not optional: branch
protection (or a ruleset) that requires the gates check and a review, and
CODEOWNERS entries for .specify/gates/** and the pipeline file
(.github/workflows/, .gitlab-ci.yml, Jenkinsfile) with code-owner
review required, so a change to the enforcement itself needs an owner's
approval.
Spec Kit compatibility
spec-gates relies on the Spec Kit extension mechanics: the extension.yml
manifest (schema 1.0), specify extension add --from <url>, the
after_implement and before_constitution lifecycle hooks, and the
workflow-engine gate and shell steps. They were first verified against
Spec Kit v0.12.4; the install, upgrade and --dev behaviors this
release depends on were rechecked against 1.0.13. requires.speckit_version
stays at >=0.12.0. Two installer gaps shape the upgrade path: add --from
verifies neither checksum nor signature (the README's upgrade steps do both
explicitly, and diff the installed files against the verified zip), and
zip extraction keeps the execute bit only on *.sh files (project.sh
restores it).
Two upstream facts shape how spec-gates positions itself. First, Spec
Kit's own gate steps and lifecycle hooks are advisory and
human-gated: a gate blocks only inside specify workflow run and merely
pauses (does not fail) in CI or any non-interactive context. Second, its
lifecycle hooks are not git hooks, and nothing upstream projects git or CI
enforcement into a repository. spec-gates exists to bind those advisory
checkpoints to boundaries that actually fail closed: a rejected tool call,
a blocked commit, a red build.
Stats
Version
Install
Using the Specify CLI
specify extension add gates --from https://github.com/schwichtgit/spec-gates/releases/download/v0.6.1/gates-0.6.1.zip