---
name: guardrails
description: >-
Turn review findings into rules that catch the whole bug class every time: a per-repo bug-class ledger,
an eliminate-or-record decision for every finding (type or API wrapper, lint rule, CI check, test
generator), risk-tiered review (none for low-risk changes, one combined code and security review at
trust boundaries, no re-review of fix rounds), self-merge gates for agent PRs, model checking for
state machines with safety promises, and metrics (reverts, fix-forwards, findings per review) to lower
review over time. Tested recipes for Go, TypeScript, Python, GitHub Actions and semgrep. Use after any
review finding or escaped bug, for "ban this API", "make sure this never happens again", "does this
PR need review", "can the agent merge this", "set up a repo for agent PRs", "bug-class ledger",
"revert rate", or "TLA+ for this flow".
---
# Guardrails
A review catches one bug once. A guardrail catches its whole class on every PR, from every agent, without
anyone remembering to look. This skill runs that loop: every finding becomes a rule or a recorded class,
review time goes only where no rule reaches, proof of behaviour replaces reading raw code, and the numbers
decide when review can shrink.
Paths below are relative to this skill's folder.
## When it applies
- A review finding, a CI failure that was a real bug, or a production bug: before you close it.
- Setting up a repo where agents open many PRs.
- Deciding whether a PR needs review, and whether an agent may merge its own PR.
- Once a month: deciding whether review can be lowered (or must be raised) on the evidence.
## 1. Keep a bug-class ledger
Copy `ledger-template.md` to `docs/bug-classes.md` in the repo and point to it from the file agents read
first (`AGENTS.md`, `CLAUDE.md` or the contributing guide): "read docs/bug-classes.md before opening a PR".
- A class is a shape, not an instance: "identity taken from a field the caller controls", not "the CLA
check trusted the git author name".
- Each class records where it was seen, the decision (eliminated, guarded, recorded), the guard and the
test that proves the guard fires.
- The review log at the bottom gets one row per review: tier, MUST and SHOULD counts, classes hit.
`scripts/review-metrics.ts` reads it.
- The template starts with ten common classes. Keep the ones your repo can have and delete the rest.
## 2. Every finding: eliminate the class, or record it
Fix the instance, then pick the strongest option that is cheap enough, in this order:
| Option | What it looks like | Strength |
| --- | --- | --- |
| Make it unrepresentable | A type only the auth middleware can build (`VerifiedUser`); a `Program` constant set instead of a command string; one `safefile.Write` that is the only writer | The bug can't be written |
| Ban it mechanically | A lint rule that forbids the dangerous API everywhere except one reviewed choke point | Caught before review, every time |
| Check it in CI | A script that fails the build: workflow lint, doc claims, repo invariants | Caught before merge |
| Generate the tests | Differential fuzzing against a reference parser, property tests, a model checker | Finds inputs nobody thought of |
| Record only | A ledger entry plus a concrete attack input on the review checklist | Depends on a reviewer remembering |
Rules for a guardrail:
1. **It ships with a planted bad example it must catch, and a good one it must pass.** A rule nobody has
seen fail is not a guardrail.
2. **Its message names the bug class and the fix**, so the agent that hits it can fix the code without
asking anyone.
3. **The allowed exception is one narrow path** (`internal/run/`, `src/safefile/`), excluded by path in
the config, never by inline "ignore" comments scattered through the code.
4. **Run it on the whole repo when you add it.** Fix the existing hits in the same change, or list them as
a dated baseline in the ledger. Never silence them quietly.
5. **Fix the instance and add the guard together** (same PR, or the next one, linked in the ledger).
Recipes, each with a planted bad and good example under the repo's tests: `recipes/README.md`.
| Bug class | Recipe |
| --- | --- |
| Untrusted input executed | depguard on `os/exec`, gosec G204, ruff `S` plus banned APIs, eslint `no-restricted-imports` on `child_process`, semgrep `shell-string-from-variable`, zizmor template injection |
| Identity from a spoofable field | custom Go analyzer `identityheader`, eslint and semgrep header rules, `getpass.getuser` banned, semgrep `spoofable-git-identity` |
| Two parsers disagreeing | differential fuzz test against a reference (`recipes/go/differential`) |
| Secrets in output | forbidigo on `fmt.Print*`, semgrep `secret-in-output`, persisted checkout credentials (zizmor) |
| Unsafe file writes | forbidigo on `os.WriteFile`/`os.Create` outside `safefile`, gosec G304/G306, eslint `no-restricted-properties`, `tempfile.mktemp` banned |
| Allowlists that fail open | semgrep `fail-open-allowlist` (Go, Python, TypeScript), eslint rule |
| Docs claiming untested facts | `recipes/ci/check-doc-claims.ts` |
| Plaintext secrets in transit | gosec G402, ruff S501, eslint and semgrep `plaintext-url` / `tls-verification-off` |
| Flaky shared-resource tests | semgrep `fixed-resource-in-test`, ruff S108 |
| A state machine breaks its promise | TLA+/PlusCal model (`recipes/tla`, section 5) |
## 3. Review by risk tier
Sort each PR by the highest tier any of its changes hits. Write the path globs for each tier in the
ledger's "Risk tiers" section so agents sort the same way every time.
| Tier | Changes | Review |
| --- | --- | --- |
| **0: gates only** | Docs, tests only, comments, renames and moves with no behaviour change, dependency bumps that pass CI, features off by default with no always-on path, generated files | No reviewer. The gates in section 4 decide. |
| **1: one combined review** | Trust boundaries: auth and identity, outside input that becomes commands, queries, files, HTML or prompts, secrets, network egress, file writes, consent and permissions, parsers and sanitizers, concurrency, migrations, money | One reviewer, first look, covering code and security in one brief |
| **2: review plus proof** | Tier 1 where a state machine makes a safety promise (approvals, payments, locks, merge queues, handoffs) | Tier 1 plus a model check or a runtime proof of the promise |
Why one combined review: in practice, separate code and security reviewers rarely find the same bug, and
one reviewer whose brief lists both concerns, with attack inputs, still finds the security bugs. Two
reviewers double the cost of the tier for little gain.
The review brief:
- The diff, what the change is meant to do, the ledger classes that apply, and attack inputs for each.
Never the builder's own conclusions: a reviewer handed a verdict tends to confirm it.
- Output is MUST and SHOULD only. Every finding has a failing input and a `file:line`. No "looks good"
lists, and nothing the test suite already reports.
- A MUST closes only with a test that fails without the fix.
**No re-review of fix rounds.** Accept a fix on a test that fails without it plus the author's own read of
the fix diff. The one exception: parser, sanitizer, concurrency or security-boundary code where the first
round found a MUST gets one more review of those hunks only. If that round still finds a MUST, make the
design smaller instead of reviewing a third time.
After every review: each finding goes through section 2, and the review gets a row in the review log.
## 4. Self-merge gates
An agent may merge its own PR only when every gate holds. Gates that fail send the PR to a person.
1. **Required checks are green on the exact head commit.** Merge with the head pinned so a push that lands
after the checks can't slip in. This race is the one `recipes/tla/MergeGate.tla` models.
```bash
head=$(gh pr view "$PR" --json headRefOid -q .headRefOid)
gh pr checks "$PR" --required --json name,bucket -q '.[] | select(.bucket != "pass" and .bucket != "skipping") | .name' # must print nothing
gh pr merge "$PR" --squash --match-head-commit "$head"
```
2. **Tier 0, or the review ran on this head's diff** and every MUST is closed by a test.
3. **The ledger is updated:** every finding has a class and a decision.
4. **Runtime changes carry proof** made on the head commit (the `pr-proof` skill).
5. **The repo's invariants pass:** whatever the repo lists as always true (migrations reversible, no route
without an auth check, a bundle size budget), as a CI job.
6. **Not a one-way door.** Deleting or rewriting data, permission or visibility changes, releases and
publishing, billing settings, key rotation: a person merges these.
7. **Small and revertable:** one concern, and `git revert` of it is clean.
After the merge, watch the main branch's checks (and the canary, if there is one). On red, revert first
and investigate after.
Branch protection, required checks and who may bypass them are set by a person once:
`references/human-steps.md`.
## 5. Model checking: when it earns its place
Use TLA+ or PlusCal when a flow has **several actors or steps that interleave, and a safety promise**
("only a checked commit is merged", "a payment is captured at most once", "an approval is never answered
for a question it didn't show"), especially with retries, crashes or restarts in the middle. Skip it for
CRUD, layout and pure functions; property tests cover those.
`recipes/tla/MergeGate.tla` is the minimal worked example: a pusher, CI and a merger. With
`CheckSha = FALSE` (the merger reads "green" without asking for which commit), TLC finds a 5-state trace
where an unchecked commit is merged; with `CheckSha = TRUE` it checks 424 states and finds none.
```bash
java -cp tla2tools.jar tlc2.TLC -config MergeGateBuggy.cfg MergeGate.tla # exit 12: invariant violated, trace printed
java -cp tla2tools.jar tlc2.TLC -config MergeGate.cfg MergeGate.tla # exit 0: no error found
```
How to write one, read a trace, and carry the invariant back into code: `references/model-checking.md`.
To draw a checked model as a statechart with the shortest path to each bad state, use the `statechart` skill.
## 6. Lower review on evidence
```bash
bun scripts/review-metrics.ts --repo owner/name --days 30 --ledger docs/bug-classes.md --json metrics.json
```
It reports merged PRs, the revert rate, the quick fix-forward rate and MUST findings per review, overall
and per tier, as a table and as JSON. It needs only the `gh` CLI, logged in, and reads nothing but PR and
commit metadata.
- **Reverts** are revert PRs and direct revert commits, counted once per reverted PR.
- **Fix-forwards** are fix PRs (by title, branch or a bug label) merged within `--fix-days` of an earlier PR,
each tied to one PR: the one it names (`#123`), else the most recent PR on the same files. Files that more
than a tenth of the window's PRs touch don't count as shared. The "named" count is firm; the
"same files" ones are an estimate, so compare the rate with itself over time rather than with other repos.
- **Drop a class from review checklists** once its guard has a planted-bad test and has held for a month.
- **Move a path down a tier** when its last 20 reviews found no MUST and that tier's reverts plus
fix-forwards are under your target. **Move it back up** on the first escaped bug there.
- **Pick the targets yourself** and write them in the ledger. A reasonable start: reverts under 2% and
fix-forwards under 5% of merged PRs, then tighten them as the guards pile up.
- **Raise review** when the rates rise, before arguing about why.
## Report
```
Finding: <one line> Class: <ledger id, new or existing>
Decision: eliminated (<guard>) | guarded (<check>) | recorded (<why no guard>)
Guard proof: <test that plants the bad pattern> -> caught; good example -> clean
Repo-wide run: <n existing hits, fixed | baselined in the ledger>
Tier for this PR: <0|1|2> because <path or trigger> Merge: self (all gates) | person (<gate that failed>)
```
## Rules
- Never close a finding without a ledger decision.
- Never weaken a guard to get a PR through; change the code, or change the rule in its own reviewed PR.
- A guard without a planted-bad test is a draft, not a guard.
- Review time goes where guards can't reach. If a reviewer keeps finding the same class, that class needs a
guard, not a sharper reviewer.
- People decide one-way doors, risk targets and tier boundaries (`references/human-steps.md`).