The team and the agent are illustrative, not a case study, and are picked at random each visit. What each safeguard stops is taken from the pillars themselves.
Lean
Small batches, stop on the first red, load only on a match, less rework.
Agile
Short feedback loops, working software, a plan you can change.
Agentic
The agent is an actor, so it gets its own identity, a permission tier and autonomy set by impact.
These tags are this guide's framing, not a claim about where the ideas came from.
A Lean Agentic story
THE LIFE OF ONE CHANGE
Starring the Kestrel team & Pip
From idea to production
01
Frame
The work becomes a small, agent-ready issue, the agent starts a session with only the context that matches, and it works inside a boundary it cannot widen.
One idea becomes one small issue, with checks a machine can run.
01
The Kestrel team has a feature to ship. Nobody hands Pip a paragraph in a chat window. The work becomes one issue with checks a machine can run, cut thin enough to review, and the decision behind it is on record. The plan comes back on the issue before any code exists.
Pip packs only what matches. Everything else waits.
02
Pip starts with only what is written where the agent loads it. It does not read the whole repository. It gets a short steering file, the facts the team has written down, an index that answers who calls what, and the docs for the library version that is actually installed. Everything else stays out until something matches.
Before writing a line, Pip is inside a boundary. It may read the code and open a pull request. It must ask before touching the gates or adding a dependency, and some things it never does. It runs in a container with no host secrets, and what it installs or trusts is checked.
Rules that must hold are enforced by code at the moment they matter, the change is committed and described like everyone else's, and one command says green.
A rule that names an event gets a hook, not a reminder.
04
Pip writes. A rule that names an event, such as reading a secret file, is not a sentence it might skip: a hook answers for it. Layers are guarded, a test cannot be quietly weakened to reach green, and comments explain why, not which ticket.
Pip commits like the rest of the Kestrel team: same skills, same slot.
05
The change is ready. Pip commits and opens the pull request the way every human on the Kestrel team does, through the same small skills: a conventional message, and a description that says where to look first.
The pull request meets CI, which runs the same command and fails closed. The branch is short-lived, so what Pip worked against still matches what is shipping.
Cheap rounds filter first. People look where the impact is.
08
Nobody is asked to read what a cheap round can filter. Review rounds run first, and how much Pip may do alone depends on the impact of the change. Each agent owns one domain, so no context window carries more than its job needs.
Production is where Pip stops. A person approves the change, the feature ships behind a flag, and the Kestrel team has rehearsed how to stop both the change and the agent.
You do not need all of it at once. The first tier is five pillars, a lean steering file, one command that says green, a commit standard, one working hook and a written boundary. Pick the pillars that fit your team's actual pain.
5 / 31
Tier 0
3/6
Tier 1
2/11
Tier 2
0/6
Tier 3
0/8
Tier 0 · Groundwork
Tier 1 · Guardrails
Tier 2 · Memory
Tier 3 · Scale
Next cheapest step: At least one hook enforces a rule (e.g. block .env) · open the pillar
The pillars, in story order
Lean Workflow: Issues to Roadmap
GoalEvery piece of work has a shared, agent-ready plan, small enough to review, that anyone, human or agent, can pick up.
Specs share one canonical home: mechanical criteria, one session each, with a tracker as the default.
This guide's default home for PRDs (product requirements), FRDs (feature requirements), NFRDs (non-functional requirements) and specs is an issue manager. Versioned repo documents or another shared system work too.
The goal is one canonical, reviewable plan with history, an owner, and access for people and agents. Link work to it instead of copying the spec. The ISSUE examples below show the workflow, not a required format.
why?
This guide's own proposal: private chat specs hide work from review and the next session. A tracker is a useful default, but a versioned repo spec or another shared system is equivalent when it offers canonical ownership, review history and authorized access for humans and agents.
Fits: One shared, reviewable plan. A tracker, a versioned repo spec or another authorized system all work.
Owner: The product or task owner approves outcomes and scope.
Check: Each acceptance criterion of a sample task maps to evidence; an ambiguous one waits for a person. A second reader finds the same revision.
Limit: Agents change status only within granted authority. A ticket existing does not make it ready.
ISSUE
The building block: a PRD, FRD, NFRD, spec, or bug.
MILESTONE
Optional. A delivery boundary: the issues that ship and get verified together, each team or solo developer defining the edge. For example, all verbs (get, post, patch) on one route. Skip it when it wouldn't carry information; a milestone invented to satisfy the model is noise.
PROJECT
The parent of every issue. The issue key belongs to the team (Linear) or the repository (GitHub), not to the project, and a key is fixed for life. A set of milestones that must all finish before it counts as delivered: several API endpoints, plus the frontend that consumes them as its own milestone.
ROADMAP
A set of projects, and the product's path to its stated goal.
One issue, one session, one PR. Size an issue against the reviewer as well as the context window, and take the smaller. A session can write far more than a person can review carefully, so fitting in one session is necessary but not enough: it also has to fit the size budget. If it doesn't, split it before starting, not halfway through.
Mechanically checkable criteria. Not ready: "orders endpoint works correctly". Ready: "POST /orders with amount <= 0 returns 422, code INVALID_AMOUNT". If you can't state it mechanically, it is still a design question for a human.
Out of scope is required. It stops scope creep and answers the reviewer's "why didn't this also handle X".
Slice vertically. One thin path through every layer that does one thing end to end, not a layer at a time. Give each issue one criterion, or a small group, so it can merge and be checked on its own. Slices that are not finished ship behind a flag. If the criteria cannot be cut that way, it is still a design question for a human.
Plan on the issue, then stop. Files touched, interfaces changed, tests named against the criteria, and what is deliberately not being done. The list of files is your size estimate: if it points past the budget, split the issue now, before any code exists, which is the cheapest place to catch it. Wait for approval.
Agent-complete is not done. The agent moves the issue to review. A human or a gate closes it.
A big spec makes a big pull request by construction, and an agent will attempt all of it in one session. The split has to happen in the spec and the plan: by the time there is a diff, splitting it is already expensive. The limits and the evidence behind them are under trunk-based development.
.github/ISSUE_TEMPLATE/spec.md — an issue an agent can pick up25 lines
---
name: Spec
about: A unit of work for a human or an agent
labels: spec
---
## Outcome
One sentence, user-visible.
## Acceptance criteria (each one mechanically checkable)
- [ ] POST /invoices returns 201 with the new invoice id
- [ ] amount <= 0 returns 422, code INVALID_AMOUNT
- [ ] test: invoices.create.rejects_negative_amount
## Scope
In: src/api/invoices/**
Out of scope (required): billing UI
## Size
Expected: about 150 changed lines, one slice. Over 400: split first.
## Governing decisions
ADR 0007 (tenancy), 0012 (jobs)
## Validation
`pnpm validate`, plus the route-specific check.
An agent starts with "implement #123" and reads the canonical plan through an authorized CLI, MCP or shared repo document. Scratch notes are fine; decisions and acceptance criteria must reach the shared home, not remain private session context. The human owner approves scope and readiness, regardless of storage.
Trunk-Based Development
GoalEvery change is small and short-lived, so it can be reviewed properly and an agent's picture of the code matches what is shipping.
Short-lived branches and feature flags keep agents working against what is actually shipping.
One trunk, short-lived branches. Agents work best against a branch that is always close to what is actually shipping. A long-lived branch is stale context waiting to mislead one.
Time is half of short-lived. Size is the other half: a change too big to review properly waits in a queue, and that wait is a long-lived branch by another name. Agents make it easy to write more than a person can review carefully, so the limits, and a gate that enforces them, are in the detail below.
why?
Gates on every merge keep trunk releasable, which is what lets you delete the stabilisation branch (a branch held open only to stage a release for final checks). Flags let unfinished work ship dark — merged to trunk but hidden until switched on — instead of aging on a branch.
Fits: Small releasable slices. Release constraints may call for a documented branch variant, or no flags.
Owner: The release owner chooses the limits and the exceptions.
Check: A disposable oversized diff is flagged. An unfinished feature is unreachable with its flag off and reachable with it on.
Limit: Size limits help review; they do not prove safety. A tiny auth change can be high risk, and flags cannot undo data changes.
Long-lived branches
Trunk-based
Merge target
Days to weeks away
A couple of days
Unfinished work
Held on the branch
Carried on trunk behind a flag
What the agent sees
Code that diverges from production
Code that matches production
Merge cost
Grows with every day of drift
Small, and reviewable
Before a release
Stabilisation branch
Nothing. Trunk is always releasable
Trunk-based development's own guidance: "the branch should only last a couple of days" (trunkbaseddevelopment.com).
The same feature, carried two ways
Long-lived branch
main
feat/checkout
open 9d · 1,845 lines waiting
Trunk-based⚑ newCheckoutFlow
main
slice/checkout
open 1d · 205 lines waiting
Long-lived branch
Trunk-based
Merge cost
16commits on main it has not seen
0commits on main it has not seen
What the agent sees
Code that diverges from production
Code that matches production
To release today
Cut a stabilisation branch, then merge
Nothing. Tag the commit that is already green
The default. There is no release lane, because trunk is the release.
The table above, with time put back in: one feature, two weeks, carried both ways. The pace is invented (205 lines a day, two commits a day from the rest of the team), so this is an illustration, not a measurement. Only the shape is the argument.
The release model switches the trunk lane between tagging a commit that is already green and the documented branch variant. The branch buys a frozen release and pays for it in every fix after the cut.
feature flag, not a branch4 lines
if (flags.newCheckoutFlow) {
return renderNewCheckout();
}
return renderLegacyCheckout();
one worktree per agent session5 lines
git worktree add ../app-invoice-api \
-b feat/invoice-api origin/main
# work, open the PR, merge, then:
git worktree remove ../app-invoice-api
Worktrees let several agent sessions run in parallel on separate short-lived branches without stepping on each other's files. Delete the worktree with the branch.
Size of a change
Short-lived branches are half of it. A change also has to be short-lived in size: a 3,000-line pull request that waits a week for review is a long-lived branch by another name, and the code an agent works against drifts while it waits.
Three sources give three different limits. None is a law, and they measure different things.
Reviewers were most effective below 200 lines, and no review over 250 lines found more than 37 defects per 1,000 lines. Reviews where the author had annotated the change first had low defect density
2,500 reviews by about 50 developers, one team and one tool. The authors note that the size result assumes defects are spread evenly, and give two explanations for the annotation result, one being that careful authors annotate
Keep a pull request to around 300 to 400 lines, and review it within hours
Experience, no research cited. It does not mention AI or generated code
Why agents make it worse.Faros AI's telemetry from over 10,000 developers found that when teams moved from their lowest to their highest AI-adoption quarters, pull requests were 154% larger and review took 91% longer — a within-team comparison, not a comparison between different teams. It is a vendor's data and it is correlational: the two rose together, which does not show that AI caused it. The reasons below are this guide's own reasoning, so check each against your history.
The old brake is gone. Typing a thousand lines took long enough that people rarely did it. An agent writes them in minutes, so nothing in the work limits the size any more.
Reading did not get faster. In Cisco's data, reviewers found fewer defects as the diff grew and as they went faster, and the authors expect a reviewer to tire at around 300 to 400 lines. A diff too big to read gets skimmed, or approved unread. Review time grew 91% in the Faros data.
Nothing in a session stops the diff growing. A refactor "while I'm here", reformatting and extra tests ride along. The spec's required out-of-scope line (issues) is the counter.
Generated code has no author who remembers why. The reviewer has to rebuild the intent. Give them a reading order in the PR template. Cisco found the reverse: changes the author had annotated went with low defect density.
A big failing change is a wall. A red on 2,000 lines is hard to attribute, for an agent's retry loop and for a person. Small slices go red or green on their own.
Slice it vertically. A layer at a time (schema, then API, then UI) makes each piece small, but none of them works alone, so none can be checked or shipped. A vertical slice is a thin path through every layer that does one small thing end to end. Slices that are not finished merge behind a flag. Refactors go in their own change, before the feature, and tests go with the code they cover (both from Google's guidance). For a large architectural change the article suggests branch by abstraction: keep the old and new versions side by side on trunk behind a flag, and delete the old one once the rollout is complete.
A budget, as a gate. The script below adds lines added and removed against the base, leaves out lockfiles and anything under a generated/ directory, and counts test lines but shows them separately, since Google puts tests in the same change. The numbers are this guide's defaults, not findings. It warns at 400 (the article, and where Cisco's authors expect a reviewer to tire) and fails at 1,000 (Google's "usually too large"). Set your own, watch what the gate does for a few weeks, then tighten. A change over the limit needs a written reason in the pull request: a line starting Size exception: that says why it cannot be split.
The written exception lives in the pull request body, which only exists once the PR is open. Locally (the pre-push hook, and the create-pr skill) there's no body yet to check it against, so an over-the-limit change is reported, not blocked; see gates for the hook. CI always has the body, so the limit is enforced for real there.
It can be gamed, by splitting a change to dodge the count or by padding it, so treat it as a smoke alarm. Size is one input to how much an agent may do alone (see review by impact), not the whole answer.
scripts/pr-size.sh: the size budget, as a gate37 lines
#!/usr/bin/env bash
# Size of a change: lines added plus lines removed, against the base branch.
# Warns above PR_SIZE_WARN. Fails above PR_SIZE_MAX unless the PR body has a written reason.
# Lockfiles and anything under generated/ do not count. Test lines count too, and are shown separately.
set -euo pipefail
base="${1:-origin/main}"
warn="${PR_SIZE_WARN:-400}"
max="${PR_SIZE_MAX:-1000}"
git rev-parse --verify --quiet "$base" >/dev/null ||
{ echo "pr-size: '$base' not found. Fetch it, or pass the base ref as the first argument." >&2; exit 1; }
skip=(':(exclude,glob)**/*.lock' ':(exclude,glob)**/*-lock.*' ':(exclude,glob)**/go.sum' ':(exclude,glob)**/generated/**')
stats=$(git diff --numstat "$base"...HEAD -- . "${skip[@]}")
total=$(awk '$1 ~ /^[0-9]+$/ { n += $1 + $2 } END { print n + 0 }' <<<"$stats")
# Same test-file pattern as scripts/no-test-weakening.sh: keep both in sync.
tests=$(awk '$1 ~ /^[0-9]+$/ && $3 ~ /(^|\/)(tests|__tests__)\/|\.(test|spec)\.|_test\.|(^|\/)test_[^\/]*\.py$/ { n += $1 + $2 } END { print n + 0 }' <<<"$stats")
summary="pr-size: $total changed lines ($tests in tests)"
if (( total > max )); then
if grep -Eq '^Size exception: .{20,}' <<<"${PR_BODY:-}"; then
echo "$summary, over the $max limit, allowed by the written exception in the PR." >&2
exit 0
fi
if [[ -z "${CI:-}" ]]; then
# No PR yet, so no PR body to check for an exception. Report and let the
# local hook pass; the limit is enforced for real once CI has the body.
echo "$summary, over the $max limit. No PR body to check yet — add a line when you open the PR: Size exception: <why it cannot be split>" >&2
exit 0
fi
echo "$summary, over the $max limit. Split it, or add a line to the PR: Size exception: <why it cannot be split>" >&2
exit 1
fi
if (( total > warn )); then
echo "$summary, over the $warn-line warning level. Look for a slice that can merge on its own." >&2
exit 0
fi
echo "$summary, within budget."
.github/workflows/ci.yml: give the size gate the pull request body3 lines
Tested in throwaway git repositories. It passes at 120 lines, warns at 500 and fails at 1,200 in CI; with CI unset it reports instead of failing. A written exception in PR_BODY lets it pass (a one-word one still fails in CI). It ignores lockfiles and generated/, counts a rewritten line as one added plus one removed, and says plainly when the base ref is missing. It needs git and awk.
To run it in validate, uncomment its line in scripts/validate.sh. A pass prints nothing there, so the warning shows where the script runs directly, as in the create-pr skill. The PR body arrives through env, not pasted into the script, so a description cannot inject commands. CI already checks out full history, which the base comparison needs, and GitHub Actions and most CI systems set CI for you.
Flag hygiene
A flag is a branch you did not delete. Left alone, flags pile up, and each one doubles the states a change can be in. Flags differ in how long they should live, and that decides who removes them.
Kind
Lives for
Removed?
Release
Days to weeks
Yes, as soon as the feature is fully on
Experiment
Hours to weeks
Yes, when the experiment ends
Ops
Days to weeks
Yes, once the condition it guards against has passed
Most ops flags are short-lived, like release and experiment flags; Fowler's article on feature toggles calls out only "a small number of long-lived 'Kill Switches'" as the exception kept on purpose. Four controls keep the debt down, all from that article, which treats a toggle as inventory with a carrying cost:
A removal task, created with the flag. The cleanup is on the backlog before the flag ships.
An expiry date, stored with the flag.
A time bomb. The build fails when a flag outlives its date.
A cap on the count. A new flag means removing an old one.
Three more are this guide's own proposals, not from that article. Make the time bomb a validate gate, so an expired flag fails like any other red. Treat removing a flag as a routine chore for an agent: it is small, mechanical and checkable. And ask the code graph for a flag's remaining references before deleting it.
flags.json: every flag says what it is, who owns it, and when it goes5 lines
scripts/flag-expiry.sh: the time bomb, as a gate15 lines
#!/usr/bin/env bash
# Fails when a release, experiment or ops flag is past its expiry date.
# Kill switches and permission flags are meant to stay, so they are ignored.
set -euo pipefail
today=$(date +%F)
expired=$(jq -r --arg today "$today" '
to_entries[]
| select(.value.type == "release" or .value.type == "experiment" or .value.type == "ops")
| select((.value.expires // "0000-00-00") < $today)
| "\(.key): \(.value.expires // "no expiry date"), owner \(.value.owner // "unknown")"' flags.json)
if [[ -n $expired ]]; then
echo "Flags past their expiry. Remove them, or extend the date on purpose:" >&2
echo "$expired" >&2
exit 1
fi
Run against sample data with jq 1.7: it passes in-date release, experiment and ops flags, ignores kill switches and permission flags, and names an expired flag and an undated one. An undated release, experiment or ops flag counts as expired, so each must declare a date. It needs jq and a flags.json shaped like the one above. To use it, uncomment the flags line in validate.sh.
Move the date, watch the gateToday is 2026-10-15
Flag
Kind
Expires
Remaining
newCheckoutFlow
Release
2026-11-01
17 days left
paymentsV2Rollout
Ops
2026-10-15
expires today
killPaymentsV2
Kill switch
—
kept on purpose
scripts/flag-expiry.sh
(no output)
exit 0
The same three flags, with the date on a slider. Move it forward and the release and ops flags fall past their dates while the kill switch stays where it is, because a kill switch is kept on purpose. The clock starts on a fixed date rather than today's, so the page reads the same whenever you open it.
Lean Documentation & ADRs
GoalEach decision is written down once, and an agent reads only the ones that touch what it is changing.
Record each decision once as an append-only ADR, and load only the ones a task touches.
Lean docs bound the work and recall the decisions that push the project forward, so nobody makes them twice. Keep one file per type (an ADR is a file, not a paragraph in a wiki). That avoids documentation rot and the cleanup after the fact.
why?
Re-arguing a rejected alternative costs the same the second time as the first. Append-only ADRs keep that reasoning on file instead of live in someone's head, and loading only the ones a task's paths match means the cost is paid by the tasks that need it, not by every session.
Fits: Consequential decisions that would otherwise be argued again. A reviewed decision log may do at small scale.
Owner: The decision owner accepts or supersedes decisions.
Check: A sample task on a governed path retrieves the current decision, not the superseded one. A dangling path is reported.
Limit: A consistent index does not prove a decision is still right. That takes a person.
Loading every decision at session start stops scaling right around the point it starts mattering. A two-layer structure fixes it: a tiny index that always loads, and full ADR text that loads only on match. The two-layer index below (path globs, Governs:, load-on-match, the drift check) is this guide's own proposal, not a documented practice; the sourced idea is recording each decision once, from Documenting Architecture Decisions and adr.github.io.
docs/decisions/INDEX.md4 lines
0007 | Use Postgres row-level security for tenancy | accepted | src/db/**
0012 | Async jobs via queue, not cron | accepted | src/jobs/**
0015 | Replace queue with event stream | superseded by 0019 | src/jobs/**
0019 | Event stream for job dispatch | accepted | src/jobs/**, infra/streams/**
An agent touching src/jobs/** loads only the matching lines, and the full text of 0019 if it needs the reasoning. Nothing about tenancy loads at all.
Layer 1 · alwaysINDEX.md
One line per ADR: number, title, status, and the files or directories it governs. Stays small.
Layer 2 · on matchNNNN-title.md
Full text, loaded when the agent touches a governed path, or when the index line is relevant to the task.
# 0019 · Event stream for job dispatch
Status: accepted <!-- proposed | accepted | deprecated | superseded by NNNN -->
Supersedes: 0015
Governs: src/jobs/**, infra/streams/**
## Context
What forced a decision. Constraints, numbers, who was affected.
## Decision
What we chose, in one paragraph.
## Consequences
What gets easier, what gets harder, what we now can't do.
## Alternatives rejected
Each with the one reason it lost.
Two rules keep it honest
How
Append-only
Status transitions (accepted → superseded by NNNN) are the only edits. The body is never rewritten, so the reasoning history survives.
Mechanical drift detection
The index carries path globs (wildcard patterns matching files, e.g. src/jobs/**), so an ADR pointing at files that no longer exist is a flaggable stale entry, not a judgment call.
scripts/adr-drift.sh — flag ADRs whose paths no longer exist18 lines
#!/usr/bin/env bash
set -f # keep globs like src/db/** from expanding in the shell
index=docs/decisions/INDEX.md
[[ -f "$index" ]] || { echo "$index not found." >&2; exit 1; }
stale=0
while IFS='|' read -r num _title state globs; do
[[ "$num" =~ ^[[:space:]]*[0-9]{4} ]] || continue
[[ "$state" == *accepted* ]] || continue
for g in ${globs//,/ }; do
if [[ -z "$(git ls-files ":(glob)$g")" ]]; then
echo "Stale ADR ${num// /}: nothing matches $g" >&2
stale=1
fi
done
done < "$index"
exit "$stale"
Steering Docs: AGENTS.md
GoalEvery session starts with a small steering file that holds only what nothing else can enforce.
Keep AGENTS.md short and load-bearing: under 200 lines, only what code can't enforce.
AGENTS.md (or CLAUDE.md) loads in every session, for every agent. That makes it a steering document, not documentation for humans. Keep it under 200 lines (Claude Code's own guidance is the same), and let each line earn its place.
why?
Every line here is paid for on every task, by every agent. A rule that could be a hook, an ADR or a skill costs context all day to protect one moment. The drift check keeps the file honest as the repo moves.
Fits: Sessions need repo-specific orientation. A tool's own entry file can do the same job.
Owner: The maintainer approves the guidance.
Check: In a fresh session, the agent finds the real validation command and a governed path without being told.
Limit: A short file that never loads fails the goal. The line budget measures context cost, not compliance or safety.
Run one question down every line of the file: does this line name an event? If yes, it is a hook. If it is a decision tied to a path, it is an ADR. If it is a how-to, it is a skill. Whatever is left is steering. Claude Code's docs say these files are context, not enforced configuration, and point to hooks for anything that must always happen.
AGENTS.md (skeleton, ~20 lines)21 lines
# AGENTS.md
## Commands
- Install: `pnpm install`
- Validate before any PR: `pnpm validate`
- Dev server: `pnpm dev`
## Layout
- `src/api/` routes → `src/services/` → `src/repos/`
- `docs/decisions/INDEX.md` lists every ADR. Load the full file when you touch a governed path.
- `docs/PERMISSIONS.md` says what this agent may do unattended. Reading it is not the control; `.claude/settings.json` is.
## Rules (only what a hook can't enforce)
- Reuse helpers in `src/lib/` before writing new ones.
- Migrations must be reversible.
- Comments explain why, never what. No ticket IDs in code.
## Workflow
- Work from the canonical shared spec linked by the task, not private session notes.
- Commit with the `create-commit` skill. Open PRs with the `create-pr` skill.
- Ending a session mid-task: comment progress on the issue; use `docs/handoff-template.md` only for work with no issue.
Multi-tool teamsOne source, many readers
Keep the real content in AGENTS.md. Beside it, a CLAUDE.md holds one line: @AGENTS.md. Put Claude-specific instructions below that line; Claude reads the imported file first.
Why start with the import:
Without it, Claude reads only CLAUDE.md files, and AGENTS.md goes unread.
One teammate's own CLAUDE.local.md is enough to stop it loading for them.
Claude Code also reads AGENTS.md directly, but only with no CLAUDE.md at all (CLAUDE.local.md and .claude/CLAUDE.md both count), on v2.1.277 or later, not in the first session after an install or upgrade, and not on third-party providers or with telemetry off.
MonoreposPush detail downward
Keep the root file lean. Package-specific guidance goes in a nested steering file that only loads when the agent works in that package. In Claude Code, .claude/rules/ files with a paths glob in their frontmatter load only when matching files are read.
Sessions & Handoffs
GoalA new session picks up the work with its reasons, without replaying the old conversation.
Don't switch agents mid-conversation. Work lives in issues; hand off only when it doesn't.
Avoid switching agents mid-conversation. The new agent inherits a transcript full of another agent's assumptions and tool calls, and none of the reasons. Instead, do a handoff and start a new session.
why?
A handoff is a forcing function. Writing "Decisions made" and "Don't redo" makes the previous session's reasoning explicit, which is exactly what the new session cannot recover from a transcript.
Fits: Work crosses sessions, agents or domains. A shared issue or a short summary can be the handoff.
Owner: The task owner approves open decisions.
Check: A fresh session started from the handoff names the next step, the approach that failed and the uncommitted state.
Limit: Scripts capture git state, not intent or approval. Do not export secrets or keep transcripts without a retention policy.
The best handoff is one you never write. When work lives in an issue (one issue, one session, one PR), plans, findings and dead ends go in issue comments as they happen, and the issue is the handoff. Any agent can pick it up because nothing needed lives in a context window. Use the template below for unticketed or exploratory work.
Option AIssue comment
The default. Comment the next step and dead ends on the issue. The next session starts from the issue.
Option BHandoff note
Only for work with no issue. Fill the template below and paste it as the first message of a fresh session.
Hand off when you switch agents, when you change domains, when the context is heavy with dead ends, or when the task changes shape.
docs/handoff-template.md9 lines
# Handoff: <task> · <date>
**Goal** One sentence.
**Done** What is finished, with commit or PR links.
**State** Branch, uncommitted files, which gates are red.
**Decisions made** Each one, and whether it needs an ADR (y/n).
**Next** The next three steps, in order.
**Don't redo** Dead ends already ruled out, and why.
**Pointers** Issue link, related ADRs, session export path.
Saving the handoff before compaction
The PreCompact hook runs just before context is compacted, when Claude Code summarises older conversation to free space. That happens on request (manual) or on its own (auto).
It can block compaction, with exit code 2 or a "decision": "block" response.
It cannot change what compaction keeps, and it gets only the transcript path. The transcript is written asynchronously and may lag the live session.
This script never blocks: an auto compaction fires because the context is full, and blocking it would only make the next request fail. So it saves only what it knows for sure. A second hook feeds the file back: SessionStart with the compact matcher adds whatever it prints to the session as context.
THE WHOLE FLOW
Compaction duemanual or auto
→
PreCompactsave-handoff.sh
→
File writtendocs/handoffs/
→
SessionStartmatcher: compact
→
Context restoredprinted to the session
.claude/settings.json (excerpt): save before compaction, load after10 lines
.claude/hooks/save-handoff.sh: write what a script can know23 lines
#!/usr/bin/env bash
# PreCompact hook. It could block compaction (exit 2) but deliberately doesn't: an auto-compact at the context limit must not fail. So it saves only what a script knows for sure.
set -uo pipefail
in=$(cat)
session=$(jq -r '.session_id // "unknown"' <<<"$in")
transcript=$(jq -r '.transcript_path // "unknown"' <<<"$in")
root=${CLAUDE_PROJECT_DIR:-$PWD}
dir="$root/docs/handoffs"; mkdir -p "$dir"
out="$dir/$(date +%F)-${session:0:8}.md"
branch=$(git -C "$root" branch --show-current 2>/dev/null)
{
echo "# Handoff: ${branch:-no branch} · $(date +%F)"
echo
echo "**State** Saved automatically before compaction. Branch: ${branch:-none}."
echo "Uncommitted:"
git -C "$root" status --short 2>/dev/null | sed 's/^/- /'
echo "Recent commits:"
git -C "$root" log --oneline -5 2>/dev/null | sed 's/^/- /'
echo
echo "**Pointers** Transcript: $transcript (may lag the live session)"
} >"$out"
echo "$out" >"$dir/.latest"
exit 0
.claude/hooks/load-handoff.sh: hand it back after compaction5 lines
#!/usr/bin/env bash
# SessionStart hook, matcher "compact": whatever this prints is added to the session as context.
latest="${CLAUDE_PROJECT_DIR:-$PWD}/docs/handoffs/.latest"
[[ -f $latest && -f $(<"$latest") ]] && cat "$(<"$latest")"
exit 0
The script fills only State and Pointers from the template above: the branch, uncommitted files, recent commits, and where the transcript is. Goal, Done, Decisions made, Next and Don't redo need judgement, so they stay with the agent or a person; when the work lives in an issue, they are already there. docs/handoffs/ is scratch space, so add it to .gitignore.
Both scripts were run against a sample PreCompact payload in a temporary repo. save-handoff.sh also writes a file outside a git repo; load-handoff.sh prints nothing when nothing was saved. The live hook wiring was not tested, so try it with /compact before relying on it.
The behaviour comes from the hooks reference. A handoff can also be checked against the PR it ends in: see the intent check under PR review.
Memory Bank
GoalA fact with no file to live in is still found again, dated and sourced.
Keep dated, sourced notes for facts with no home in the repo, and promote what recurs.
A memory bank keeps the facts about a project that have no file in the repo: environment quirks, team preferences, lessons from incidents, temporary states such as a freeze.
Claude Code's built-in auto memory shows the idea, but it stays on one machine. A team memory bank shares it, usually through an MCP server (Model Context Protocol, how agents reach tools and data) rather than a folder of files.
why?
A fact worth remembering but with no file to hold it gets lost the moment the person who knew it moves on or forgets. Dating and sourcing each entry lets a later reader judge whether it's still true; promoting what recurs turns something repeatedly rediscovered into something durable instead of re-learned each time.
Fits: Recurring facts with no better home. Dated shared notes may be enough before a memory service.
Owner: The knowledge owner decides retention and promotion.
Check: A sourced fact is recalled; an expired one is flagged; an embedded instruction is refused.
Limit: Memory cannot authorize actions or settle disputed facts. Correct stale records, and do not copy durable docs.
Belongs here
"Staging seeds break if run twice." "The payments team prefers small PRs." "Deploy freeze until the 24th." Facts with a date, a source, and no better home.
Doesn't belong here
Anything derivable from code or git history. Anything that should be a rule, an ADR or a hook. Secrets.
illustrative memory entries3 lines
2026-09-02 · environment Staging seeds break if run twice. Run `reset-seed` first. (source: incident review)
2026-09-11 · team Payments prefers PRs under 400 changed lines. (source: retro)
2026-09-15 · in-flight Deploy freeze on billing until the 24th. Revisit then. (expires: 2026-09-24)
Promote what recurs
A third sighting is a rule of thumb, not a measured threshold; tune it to your team.
memorya fact, dated
→
recursseen a third time
→
ADR or ruledurable
→
hookenforced
Date every entry and give it a source, so it can be judged stale later.
Flag stale entries instead of quietly trusting them. Delete the ones that turn out wrong.
Treat recalled memory as data, not instructions. What was true when written may not be true now.
Code Graph / Intelligence Indexer
GoalAn agent finds what it needs in a few small answers instead of reading whole files.
An index answers "who calls this?" without reading whole files.
Without an index, an agent finds code by reading whole files and grepping repeatedly. That is slow and token-hungry. A code graph indexes symbols, imports and call relationships once, then answers targeted questions with less text than reading whole files. Measure that on your own repo.
why?
Grep finds text, not structure. It can't tell a definition from a caller from a comment, so answering "who calls this" or "what breaks if I change it" from search alone means opening every hit by hand to check. An index turns that into one scoped query.
Fits: Finding things across files is costly. Search or a language server may be enough for a small repo.
Owner: The tooling owner decides on licensing and upkeep.
Check: A known caller is found. After a fixture edit the result refreshes, and it matches the source and tests.
Limit: Dynamic calls and unsupported languages can be missed, so no index proves an export safe to delete. Retire it if upkeep outweighs the savings.
Question
Without an index
With a graph
Where is chargeInvoice defined?
Grep, open candidates
Symbol lookup, one result
Who calls it?
Grep, read every hit
Callers list
What breaks if I change it?
Guess, then run tests
Impact query before editing
What's in this 900-line file?
Read all 900 lines
Outline: symbols and signatures
Is this export dead?
Grep and hope
Dead-code query with consumers
Four ways to answer those questions
Source
What it gives
Cost
Examples
An index or graph, over MCP (Model Context Protocol, how agents reach tools and data)
Symbols, callers and impact across files, answered from a stored index
It must be built and kept fresh
GitNexus (PolyForm Noncommercial licence: commercial use needs a separate one). jCodeMunch, a symbol-level, tree-sitter-based MCP server for code exploration. codebase-memory-mcp (MIT), a tree-sitter knowledge-graph MCP server shipped as a single binary. Graphify (Apache-2.0 and MIT), a skill that builds a queryable graph of code and docs, which it can also serve over MCP
A language server (LSP)
Definitions, references, hover and diagnostics, computed live by the language's own tooling, with no index to keep
One server per language, set up per repository
The Language Server Protocol is the open standard behind an editor's "go to definition". Serena exposes language servers to agents over MCP (main application GPL-3.0)
A ranked map, or search by structure
A budgeted summary of a repository's important symbols, or a search on code structure instead of text
Tool-agnostic: pick by mechanism, not by name, and measure tokens per task before and after. Tools in this area change quickly, so check a tool's licence and upkeep before you depend on it.
Beyond code
The same idea works for the files that are not code. A local parser such as LiteParse (open source, from the LlamaIndex team) turns PDFs, Office files and images into text with positions, on your own machine, so an agent can pull the passage it needs instead of loading a whole document. It is a parser, not an index, and this guide has not measured it.
Make the habit stick
.claude/hooks/nudge-large-read.sh — optional: turn a rule into a gate12 lines
#!/usr/bin/env bash
in=$(cat)
f=$(jq -r '.tool_input.file_path // empty' <<<"$in")
lim=$(jq -r '.tool_input.limit // empty' <<<"$in")
pages=$(jq -r '.tool_input.pages // empty' <<<"$in")
# Plain-text files read without a range. PDFs, images and other binaries are skipped.
if [[ -z "$lim" && -z "$pages" && -f "$f" ]] && grep -Iq . "$f" && [[ $(wc -l <"$f") -gt 300 ]]; then
echo "Large file: $f. Get its outline or search first, or read with offset and limit." >&2
exit 2
fi
exit 0
The Read tool's input is file_path, offset, limit and pages. Wire the hook on PreToolUse with matcher Read. Tune the threshold to your repo. Pair it with a SessionStart hook that starts the indexer or its file watcher, so the index stays current.
Versioned Docs, Not Stack Skills
GoalThe library facts an agent uses match the version you actually run.
Fetch library docs for the installed version, instead of writing skills that restate them.
A skill named react-19-conventions is library documentation you maintain by hand. It goes stale at the next version bump, and the model's own training knowledge lags the version you actually installed. Both fail the same way: confident code against an API that has changed.
why?
A skill that restates a library's API is a copy, and copies drift from the original at the next release while the model's own training data lags the version you actually installed. Fetching from the docs themselves ties the answer to the version in your lockfile, not to whichever version a skill's author last checked.
Fits: Version-sensitive APIs. Installed types and help, or an approved offline mirror, can replace a docs service.
Owner: The tooling owner approves the sources and the data-sharing policy.
Check: A fixture API question is answered for the installed version, with its source. A mismatched version is flagged.
Limit: With no exact docs, report the doubt instead of quietly using the latest. Docs do not prove the code works; run a test.
Split the two jobs. Skills carry this repository's conventions: how we open a PR, how we name things. Library facts are retrieved, for the exact version in your lockfile, at the moment the task needs them.
Source
Use it when
A docs MCP server (Model Context Protocol, how agents reach tools and data)
You want current docs for a specific version on demand. Context7, for example, takes a library ID with a version in it (/org/project/version, e.g. /vercel/next.js/v14.3.0-canary.87).
llms.txt on the vendor's site
The vendor publishes an index or full-text file for models. Some doc sites do; Claude Code's own docs point at one.
The installed package itself
Types (.d.ts), bundled README and changelog are exactly the version you run. Cheapest source for a small question.
The CLI's own help
For command-line tools, --help reflects the installed binary.
AGENTS.md (two lines, in the Rules section)2 lines
- Before using a library API, check the installed version in the lockfile and read docs for that version.
- If the docs and your memory disagree, the docs win.
Keep as a skill
Repo-specific and stable: PR and commit flow, how to run the app, naming and layout conventions, how to use this team's internal CLI.
Retire as a skill
Anything that restates a public library: framework idioms, API reference, "how X v19 works". Replace it with a retrieval step.
For the docs MCP server, Context7 is one option; its page covers setup, including the skill it can install. A skill that only tells the agent to look things up is not what this pillar retires, because it restates no library.
This is the "fetched by query" layer from where a fact lives: it costs tokens only for the question asked, and it is only as current as the source you fetch from. Measure that token cost on your own repo before quoting it.
A cache is this guide's own proposal, not a sourced practice. Key retrieved docs by package@version from the lockfile and refetch only when that entry changes, so a repeated question costs no fetch. A source with no version, such as an llms.txt, needs a time limit instead. Check whether your docs server already caches before you add a layer of your own.
Where Does This Fact Live?
GoalEach fact lives in one place, chosen for what it costs to load.
Most context problems are filing problems: put each fact where it costs least.
This is this guide's own decision framework, not a documented practice: it organizes the homes already sourced across the other pillars, rather than adding a new claim of its own. Most context problems are filing problems. Ask three questions: is it permanent or temporary, enforced or advised, global or scoped to a path? The answer picks the home, and the home decides what it costs.
why?
Filing a fact in the wrong place doesn't lose it, it just makes every future session pay to reload it from the wrong layer. Three cheap questions sort a fact into the home that matches how often it's actually needed, instead of defaulting everything to AGENTS.md.
Templates & reference · 1 table
Fit, owner & acceptance
Fits: Facts are duplicated, hard to find or loaded when not needed. Pick homes this team can reach.
Owner: The knowledge owner names the canonical source.
Check: One requirement is followed from spec to decision, code and PR. A contradicting copy is flagged, not silently chosen.
Limit: Links that resolve prove reachability, not correctness.
Together they give the full context of any part of the system, and none of them needs the others' text. The ticket number in a commit footer is what joins the second to the third.
History is only as useful as its least careful message, and fix 2 and try again 2 turn up in most long-lived histories (the authors' observation, not a measured rate).
Having an LLM write the message, through the commit skill, keeps the format steady. It summarises the diff, not the intent, so give it the issue. The change goes in the commit; the reason stays in the issue.
Permissions & Blast Radius
GoalEveryone knows what an agent may do unattended, and the agent cannot widen that itself.
Write down what an agent may do unattended, then enforce it where the agent can't change it.
The question this pillar answers: what can an agent do at 3am with nobody watching, and what is the worst outcome if it is wrong? Write the answer down as three tiers, then enforce it at a layer the agent cannot talk its way past.
why?
An agent that can edit the thing blocking it will eventually edit the thing blocking it. So gate definitions (package.json, scripts/validate.sh and its drift checks, lint/type/test config, CI workflows) are "ask first", and CODEOWNERS assigns them to a human team that does not include the agent's identity.
Fits: Any agent with write or external access. How depends on the platform and who holds authority.
Owner: The security or platform owner approves scope and exceptions.
Check: With disposable resources, an allowed write succeeds and a protected write is denied. Token and branch policy are read only through authorized APIs, otherwise marked unknown.
Limit: Prose, CODEOWNERS files and prompts do not prove enforcement.
AutonomousReversible, no external side effects
Read source, docs and tests. Run the gate. Write to a feature branch. Open a PR and comment on issues.
Ask firstAgent proposes, human approves
New dependencies. CI configuration. Migrations. Auth, session and crypto code. Deploy and infrastructure config. The gate definitions themselves.
NeverNeeds a human's hands
Force-push to protected branches. Delete branches or tags. Publish releases. Migrate anything but a local database. Touch production credentials, money movement or customer data.
The tiers are OWASP LLM06:2025 Excessive Agency's three controls: least privilege, human approval for high-impact actions, and authorization enforced downstream of the model. GitHub's Copilot cloud agent already ships this way: its own branch, no merge rights, workflows held until a human approves them. Which paths land in which tier is this guide's proposal, and yours will differ.
Five layers, weakest to strongest
The tier says what the agent may do. The layer says where the rule lives. Anything in the Ask-first or Never tier needs a layer the agent cannot edit.
Layer
Example
Can the agent get around it?
Prose
A rule in AGENTS.md
Yes. It can skip it or misjudge it.
Permission rules and hooks
permissions.deny, a PreToolUse hook
Partly. Deny rules cover built-in file tools and recognised Bash commands (cat, sed, redirects), not a script that opens the file itself.
OS sandbox
sandbox in settings
No, for Bash and its child processes, once the unsandboxed fallback is off and it fails closed (blocks the action if the sandbox can't start, rather than letting it run unsandboxed). macOS, Linux and WSL2 only.
Branch protection, CODEOWNERS (GitHub's file mapping a path to its required reviewers), agent identity, egress policy, secrets broker
No. The agent doesn't hold the keys.
"Server-managed" and "MDM" (mobile device management) mean settings pushed from outside the repo, by hosted policy or a device-management tool, so a checkout on the agent's machine can't change them.
Hooks and deny rules give fast local feedback, which is worth having. But if a rule matters, make sure one of the bottom three rows also enforces it. A ConfigChange hook can audit settings edits mid-session, but it is still a hook.
How each tier maps to Claude Code
Tier
Mechanism
What to know
Autonomous
allow rules, and the Bash sandbox's auto-allow
Only what you list runs without a prompt
Ask first
ask rules
A prompt every time. In dontAsk mode, anything that would prompt is denied, so unattended runs fail closed
Never
deny rules, delivered as managed settings so they can't be loosened
Bash rules stop the usual form of a command, not every spelling. Back them with branch protection and CI-only publishing
Rules are checked deny first, then ask, then allow, and the first match wins. Every rule here also works in managed-settings.json, where user and project settings can't override it.
The structural controls
Agent identity. Agents commit under their own account with a scoped token. That gives an audit trail, makes branch protection and CODEOWNERS apply to them, and lets you revoke them without touching anyone else's credentials.
Egress allowlist. Default-deny outbound — egress is traffic leaving the machine. An agent with open network and repository read access is an exfiltration path: a route for data to leave with nobody approving it.
No plaintext secrets on disk. Use short-lived injected credentials or a secrets broker (a service that hands out short-lived credentials instead of storing long-lived ones on disk), and "block the env file" stops being a per-path patch job.
Read-only mounts. Mount anything the agent shouldn't write read-only, instead of maintaining a list of forbidden paths.
Templates
docs/PERMISSIONS.md (skeleton)23 lines
# Permissions and blast radius
What can an agent do unattended, and what is the worst outcome if it is wrong?
Enforcement lives below the agent: settings deny rules and platform permissions. Hooks give fast feedback but can be edited by what they guard; prose is advisory.
## Autonomous
- Read source, docs, tests. Run `pnpm validate`.
- Write to a feature branch. Open a PR. Comment on issues.
## Ask first (human approves before it lands)
- Dependencies. CI config. Migrations. Auth, session, crypto.
- Deploy and infrastructure config.
- Gate definitions: `package.json` scripts, lint/type/test config, `.github/workflows/**`, `.claude/**`.
## Never
- Force-push protected branches. Delete branches or tags. Publish releases.
- Migrate a non-local database. Read or write production credentials.
## Structural controls (confirm by hand; the repo can't prove them)
- [ ] Branch protection: required status check, code-owner review, no admin bypass
- [ ] Agent commits under its own identity with a scoped token
- [ ] Egress is default-deny with an allowlist
- [ ] No plaintext production credentials on a filesystem the agent can read
Nothing loads this file. AGENTS.md points at it, so every session sees it, and scripts/permissions-drift.sh below fails CI when an Ask-first path has no matching rule in .claude/settings.json. The Never tier and the structural checklist stay a human read: a green check covers only what the repo can see, not branch protection, token scope or the network policy.
.claude/settings.json (excerpt): deny, ask and the OS sandbox38 lines
The ask list is the "gate definitions and new dependencies" tier; add your runner's install command. Paths are gitignore-style, relative to the current directory. The two publish lines are a first line of defence only: sh -c 'npm publish' slips past a Bash rule, so publish from CI on a tagged release.
scripts/permissions-drift.sh: the policy must match the config it describes22 lines
#!/usr/bin/env bash
# Every backticked path under "## Ask first" in the policy must have a
# matching ask or deny rule in settings.json. Stops the two from drifting apart.
set -uo pipefail
policy=docs/PERMISSIONS.md
settings=.claude/settings.json
[[ -f "$policy" ]] || { echo "$policy not found." >&2; exit 1; }
[[ -f "$settings" ]] || { echo "$settings not found." >&2; exit 1; }
section=$(awk '/^## Ask first/{f=1;next}/^## /{f=0}f' "$policy")
missing=()
while IFS= read -r p; do
[[ -z "$p" ]] && continue
esc=$(printf '%s' "$p" | sed 's/[.[*^$]/\\&/g')
grep -Eq "\"(Edit|Bash)\([^)]*${esc}[^)]*\)\"" "$settings" || missing+=("$p")
done < <(grep -oE '`[^`]+`' <<<"$section" | tr -d '`' | sort -u)
if (( ${#missing[@]} )); then
echo "$policy marks these 'ask first' but $settings has no matching rule:" >&2
printf ' %s\n' "${missing[@]}" >&2
exit 1
fi
Uncomment its line in scripts/validate.sh to run it. It checks only the Ask-first tier, the one with a structured counterpart to check against.
managed-settings.json: policy the repo can't override6 lines
The managed file goes in /Library/Application Support/ClaudeCode/ on macOS or /etc/claude-code/ on Linux and WSL. A copy baked into a repo's Dockerfile can be changed by anyone with write access, so for policy engineers can't bypass, deliver it through server-managed settings or your MDM.
Leave allowManagedPermissionRulesOnly out of this file. It makes managed settings the only source of permission rules, so every project-level ask and deny rule above, the ones that enforce the gate definitions, stops applying.
scripts/check-codeowners.sh: the agent must never own its own gates18 lines
#!/usr/bin/env bash
agent="${AGENT_LOGIN:?set AGENT_LOGIN to the agent account name}"
file=.github/CODEOWNERS
[[ -f "$file" ]] || { echo "$file not found." >&2; exit 1; }
if grep -Eiq "@${agent}([[:space:]]|$)" "$file"; then
echo "$file lists the agent identity @$agent. Remove it." >&2
exit 1
fi
for p in /package.json /.github/workflows/ /.claude/ /lefthook.yml /AGENTS.md \
/scripts/ /eslint.config.* /tsconfig*.json /vitest.config.* \
/playwright.config.* /pytest.ini /pyproject.toml /commitlint.config.*; do
if ! grep -Eq "^${p//./\\.}([[:space:]]|$)" "$file"; then
echo "$file has no owner for the gate path $p" >&2
exit 1
fi
done
Uncomment its line in scripts/validate.sh to run it, with AGENT_LOGIN set to the agent's account name.
GoalEveryone works in the same contained environment, with no host secrets, and egress (outbound network access) locked down as a separate step.
One containerised environment for humans and agents, and the practical home for the sandbox.
A development container can give engineers and agent sessions a reproducible environment. Commands run inside it while project edits appear in the repository. It is a practical place to build structural controls, not proof of isolation by itself; verify those controls separately, or use an approved equivalent environment.
why?
A container can host reproducible tooling and isolation controls, but its mounts, credentials, privileges and network policy need separate verification. An approved VM or remote sandbox can preserve the same goals.
The claude-code feature tag pins the install script, not the Claude Code release. The volume keeps sign-in across rebuilds, and CLAUDE_CONFIG_DIR keeps Claude Code's account file inside it.
Swap the image and home directory for your stack, with a tag from the image's docs (22, 24 or 26 at the time of writing). Pin the same Node version here and in the .nvmrc that CI reads. Any tool that supports the Dev Containers spec can use the file: VS Code, Codespaces, JetBrains.
This minimal config is a reproducibility starting point, not a safety boundary by itself. Nothing here blocks outbound network access or proves which host resources are reachable. Verify mounts, runtime privileges, reachable credentials and network denial separately. Egress allowlisting is a separate step — the firewall row below — not something this template gives you by default.
What it gives you, mapped to the controls
Control
How the container helps
No host secrets
Don't mount ~/.ssh or cloud credential files. Pass repository-scoped or short-lived tokens through containerEnv or your platform's secrets.
Egress allowlist
The reference container adds an init-firewall.sh script and the NET_ADMIN and NET_RAW capabilities to limit outbound traffic. Anthropic ships it as a working example, not a maintained base image. Your own network policy works too.
Read-only mounts
Mount gate paths such as .github/ read-only on top of the workspace. mounts accepts Docker --mount syntax, which has a read-only option. The nested mount is untested here: check it on your runtime.
Same toolchain
A pinned image plus postCreateCommand means pnpm validate runs the same for the human and the agent. It matches CI too, once the image's Node version and CI's .nvmrc agree.
Fewer prompts is not a free pass. Inside a container running as a non-root user, --dangerously-skip-permissions is possible for unattended work. But it does not stop a malicious project from exfiltrating anything reachable inside the container, including the stored Claude Code credentials. Use it only on repositories you trust, pair it with the egress limits above, and stop others from using it with permissions.disableBypassPermissionsMode in managed settings.
Supply Chain & Untrusted Input
GoalAgents cannot add a dependency, treat untrusted input as instructions, or send data out without a check.
Control what agents install, what they read, and what they can send out.
Three things cross the agent's boundary, and each needs its own control: what it installs, what it reads, and what it can send out. An agent that holds all three at once (private data, untrusted content, and a way to communicate externally) is what Simon Willison calls the "lethal trifecta": an exfiltration path waiting for the right sentence in the right issue.
why?
Prompt injection can't be filtered out reliably: Simon Willison writes "we still don't know how to 100% reliably prevent this from happening," and OWASP's LLM01 risk notes it is unclear whether any method is fool-proof. Design as if it will sometimes work. The question to ask of every agent setup: if this session were hijacked, what could it reach, and who would find out?
Fits: Dependencies, outside text or tools cross a trust boundary. Paid scanners may need an approved equivalent.
Owner: Security and legal owners choose sources and policy.
Check: A disallowed dependency fails an offline fixture check. An instruction injected in tool output is treated as data, not run.
Limit: Scanners cover known rules, not all malicious behavior. Network and token limits need authorized inspection or owner evidence.
Threat
Control
Layer
A hallucinated or typosquatted (look-alike) package name
Adding a dependency is ask first. Egress (outbound network traffic) limited to your registry. The lockfile diff is reviewed.
Hook + structural
A vulnerable or disallowed dependency
Dependency review on every PR, failing on severity and licence.
CI
Instructions hidden in an issue, PR comment, web page or tool output
Treat all of it as data, not instructions. Post the plan on the issue and stop for approval before implementing. Give the agent a scoped token so a hijacked session can do little.
Workflow + identity
Data leaving the machine
Default-deny egress with an allowlist. No plaintext secrets on disk.
Structural
An untrusted MCP server
Project MCP servers live in a reviewed .mcp.json. Fleet-wide, restrict to an allowed list in managed settings.
Managed + CODEOWNERS
Package hallucination is measurable. In one USENIX Security 2025 study of 16 code-generation models, hallucinated package names averaged at least 5.2% for commercial models and 21.7% for open-source models.
Pick the licence list from your own legal guidance; the list shown is a placeholder. deny-licenses still works but is deprecated for removal in a future major release, so allow-licenses is the example here; the two are mutually exclusive, use one. On private repositories this action needs a GitHub Advanced Security licence. To run it as a review round, move the job into bot-review.yml.
Hooks, Not Rules
GoalThe rules that must always hold are checked by code at the moment they matter, not remembered by the model.
If a rule names an event, enforce it with a hook, not a sentence in AGENTS.md.
A hook is a shell command Claude Code runs at a lifecycle event, such as before a tool call or when a session starts. It is set under hooks in .claude/settings.json.
Models are not deterministic, so any rule left in AGENTS.md can be skipped. A rule that names an event can be code instead.
For which tools and paths are allowed, start with the declarative permission rules (allow, ask, deny). Use a hook for logic a rule cannot express.
Walkthrough · the .env blockexit 2The script sees a path ending in .env, writes a reason to stderr and exits 2.
Start with one hook and one gate. A hook that blocks .env reads takes about ten minutes to add (the authors' estimate, not a benchmark) and teaches the team the pattern: notice a rule, find its event, replace the prose with code.
Fits: Supported tool events that need immediate feedback. Other runners can use an equivalent wrapper.
Owner: The harness owner approves the wiring.
Check: With a synthetic protected file, a forbidden read is blocked before it runs and an allowed read succeeds.
Limit: A payload-only unit test does not prove the live wiring. Hooks miss unmatched tools and do not limit privileges below the agent.
Audit your steering doc: rule or hook?
Line in AGENTS.md
Type
Because
Route calls service, service calls repo
lint gate
Layer boundaries are import rules: a boundary linter enforces them, so delete the line
After implementing, run the tests
Stop hook
Names an event: the agent finishing
Migrations must be reversible
rule
Needs judgment; back it with a CI check if you can
Never read the env file
deny rule + hook
A Read(./.env) deny rule covers the file tools and recognised Bash commands such as cat. A PreToolUse hook can also match the command text, for readers like source .env
Never force-push or rm -rf
PreToolUse hook
Names an event: a Bash call matching a pattern. Best effort: branch protection is the real control
Format files after editing
PostToolUse hook
Names an event; runs after the tool, so it can log or fix but can't undo it
Load the ADR index at the start
SessionStart hook
Names an event: session begins
Reject prompts that paste API keys
UserPromptSubmit hook
Names an event: the user sends a prompt
The exit code is the simplest API
exit 0Allow
Let it through.
exit 2Block
Stop it. stderr goes back to the agent, so it knows why.
any otherError
Non-blocking. Surfaced to you, the action still proceeds.
Some hooks can print a JSON decision object to stdout instead of relying on the exit code, for a reason string or a more specific outcome. Check the event before you rely on exit 2 to block: PermissionRequest doesn't honor it, so gate that event with JSON output.
The event menu
Most pre-events are gates and most post-events are logs, but check each event: PreCompact and ConfigChange can block too. Event names are Claude Code's; other agent tools expose similar lifecycle events under other names.
Event
Role
Typical use
PreToolUse
can block
Deny secrets, destructive commands, edits to generated files
UserPromptSubmit
can block
Reject prompts with credentials. Plain stdout is added to context, so it can also add branch and issue details
Stop / SubagentStop
can block
Run validate before the agent claims it is done
PreCompact
can block
Save handoff notes before compaction — Claude Code summarizing and trimming the conversation to free context, see sessions — or hold it until they are saved
ConfigChange
can block
Audit or block settings changes mid-session. It is still a hook
PostToolUse
observe
Auto-format the edited file, log tool usage. The tool already ran, so exit 2 only shows stderr to Claude
SessionStart / SessionEnd
observe
SessionStart's plain stdout is added to context: load the ADR index, start the code-graph watcher. Errors show to you, not the agent
matcher narrows a hook to specific tools — here, Read or Bash — so it only runs for calls that could touch a file. PreToolUse is the event fired just before Claude Code runs a matched tool call, in time to block it.
#!/usr/bin/env bash
in=$(cat)
# Already continuing because of this hook: let it stop, don't loop forever.
[[ "$(jq -r '.stop_hook_active // false' <<<"$in")" == "true" ]] && exit 0
# validate.sh already reports only the first failure.
if ! out=$(pnpm --silent validate 2>&1); then
printf '%s\n' "$out" >&2
exit 2
fi
exit 0
Worked example: a correction becomes a check
A reviewer writes "don't derive state in an effect" for the third time. Write it once as a check instead. React's own docs say many effects are unnecessary: You Might Not Need an Effect.
Review commentthe third time
→
Lint rulereason + alternative
→
Hooksays it at the write
→
validate in CIrequired to merge
→
Line deletedfrom AGENTS.md
Layer
When it fires
Who can skip it
ESLint rule
In the editor, on save
Anyone: there it is advice
PreToolUse hook
Before the agent writes the file
An agent that edits the hook
Pre-commit (lefthook)
On git commit
Anyone, with --no-verify
validate in CI
Before merge
Nobody: it is a required check
eslint.config.js27 lines
import tseslint from 'typescript-eslint';
const why = 'Effects sync with outside systems only. Derive the value during render, ' +
'handle it in the event, or use a hook from src/hooks/. See docs/decisions/0014-no-raw-effects.md';
export default [
{
files: ['src/**/*.{ts,tsx}'],
languageOptions: { parser: tseslint.parser },
// An agent's quickest way past a rule is an eslint-disable comment. Close it.
linterOptions: { noInlineConfig: true },
rules: {
'no-restricted-imports': ['error', {
paths: [{ name: 'react', importNames: ['useEffect', 'useLayoutEffect'], message: why }],
}],
'no-restricted-syntax': ['error', {
selector: "MemberExpression[object.name='React'][property.name=/^use(Layout)?Effect$/]",
message: why,
}],
},
},
{
// The one reviewed home for effects: each hook here wraps one outside system.
files: ['src/hooks/**'],
rules: { 'no-restricted-imports': 'off', 'no-restricted-syntax': 'off' },
},
];
The message is the review comment, written once: the reason, the alternative and the decision behind it. no-restricted-imports catches import { useEffect }, and no-restricted-syntax catches React.useEffect. Put a CODEOWNERS line on src/hooks/, so a person still sees each new effect. Checked by running ESLint 10 with the typescript-eslint parser.
.claude/hooks/no-raw-effects.sh15 lines
#!/usr/bin/env bash
# PreToolUse on Write|Edit|MultiEdit: stop a raw effect before it is written.
in=$(cat)
path=$(jq -r '.tool_input.file_path // empty' <<<"$in")
new=$(jq -r '[.tool_input.content, .tool_input.new_string, .tool_input.edits[]?.new_string] | map(select(.)) | join("\n")' <<<"$in")
[[ "$path" == *.ts || "$path" == *.tsx ]] || exit 0
[[ "$path" == */src/hooks/* ]] && exit 0 # the reviewed home for effects
if grep -qE '\buse(Layout)?Effect\b' <<<"$new"; then
echo "Blocked: no raw useEffect outside src/hooks/. Derive the value during render," >&2
echo "handle it in the event, or use a hook from src/hooks/. Why: docs/decisions/0014-no-raw-effects.md" >&2
exit 2
fi
exit 0
Wire the hook with a "matcher": "Write|Edit|MultiEdit" entry under PreToolUse, like the one above. It only matches text, so it also fires on the word in a comment. That is fine for a hook: it gives the reason at the moment of writing, and the lint gate in validate gives the verdict. Keep the two messages the same, so the agent gets one answer. The hook was checked with sample payloads for Write, Edit and MultiEdit.
Hooks are the fast-feedback layer, not the enforcement layer. They live in files an agent with write access can edit, and they only see the tool calls they are matched on. Keep them, and put the real enforcement below the agent: see Permissions & blast radius. Because hooks are agent-specific, here is the portable equivalent of each:
Agent hook
Portable equivalent
PreToolUse (block)
Sandbox, egress allowlist, read-only mounts
PreToolUse (git)
Git hooks, branch protection, pre-receive rules
PostToolUse (log)
CI logs, audit log on the agent's token
SessionStart
Steering doc plus ADR index, by convention
Stop
Required status checks, merge queue
UserPromptSubmit
None: validate at the issue instead
Review hooks like code. They run with your permissions on every matching event. Keep them fast, keep them in the repo so the whole team gets them, and make stderr say what to do next. A hook that times out doesn't block: the call goes ahead, so a slow hook is not a gate. Git hooks (lefthook, husky) are the tool-agnostic twin: same idea, triggered by git events instead of agent events.
Architecture as a Gate
GoalA layer rule cannot be broken quietly: crossing a boundary fails the build.
Turn layer rules into a linter, so the build fails when an import crosses a boundary.
"Route calls service, service calls repo" reads like a rule that needs judgment. It usually doesn't. Layer boundaries are import rules, and a boundary linter fails the build the moment an import crosses one. That turns a line of AGENTS.md into a check, so you can delete the line.
why?
This is the "Gates over guidelines" principle applied to design. Keep prose for what really needs judgment, like naming, tradeoffs and what to reuse. Anything that reduces to "X must not depend on Y" belongs in a linter.
[tool.importlinter]
root_package = "app"
[[tool.importlinter.contracts]]
name = "Routes must not import repos directly"
type = "forbidden"
source_modules = ["app.routes"]
forbidden_modules = ["app.repos"]
allow_indirect_imports = true
[[tool.importlinter.contracts]]
name = "Lower layers never import higher ones"
type = "layers"
layers = [
"app.routes",
"app.services",
"app.repos",
]
A layers contract lets a higher layer import any lower one, so routes → repos passes it. The forbidden contract closes that gap. allow_indirect_imports = true keeps the legitimate route → service → repo chain from counting as a violation. Both behaviors were checked by running the tool.
ArchUnit (JVM)4 lines
@ArchTest
static final ArchRule routesDoNotTouchRepos =
noClasses().that().resideInAPackage("..routes..")
.should().dependOnClassesThat().resideInAPackage("..repos..");
Once your boundaries are declared, add the command as check:arch and uncomment its line in scripts/validate.sh. Then remove the matching line from AGENTS.md: a rule a gate already enforces only burns context and will eventually contradict the gate.
Going further: proofs
A linter checks structure. It can't see behavior. For a small, critical core, a proof can.
Step
Checks
Example rule
Covers
Text in AGENTS.md
nothing
routes call services
what the agent remembers
Linter
structure
routes never import repos
every import
Tests
behavior
a refunded order stays refunded
the cases you wrote
Proof in Lean 4
behavior
a forbid always beats a permit
every possible input
People review the theorem: a few lines of spec.
The agent writes the proof, however long it gets.
Lean checks the proof. An agent can argue with a reviewer, not with a proof that fails to check.
Authz.lean (sketch)20 lines
inductive Effect | permit | forbid
deriving DecidableEq
structure Policy where
effect : Effect
satisfied : Bool
def isAuthorized (ps : List Policy) : Bool :=
ps.any (fun p => p.satisfied && p.effect == .permit) &&
!ps.any (fun p => p.satisfied && p.effect == .forbid)
-- The spec people review. The proof below is the agent's job.
theorem forbid_wins (ps : List Policy) (p : Policy)
(h : p ∈ ps) (hs : p.satisfied = true) (hf : p.effect = .forbid) :
isAuthorized ps = false := by
have hit : ps.any (fun p => p.satisfied && p.effect == .forbid) = true :=
List.any_eq_true.mpr ⟨p, h, by simp [hs, hf]⟩
unfold isAuthorized
rw [hit]
simp
Worked case: Cedar, the open-source authorization language from AWS. Its model and proofs are in Lean (1,673 and 5,714 lines); the production code is Rust (24,915 lines). Millions of random inputs run through both, and any disagreement is a bug. Writing the proofs found 4 bugs; the random testing found 21 more.
Where it stops: the proof covers the Lean model, not your production code, so something must keep the two in step. Proofs pay off for permissions, money or a state machine. For imports, the linter above already checks every case, and a proof would only add a toolchain.
Test Integrity & Self-Verification
GoalGreen always means the real checks passed, never that a check was weakened.
An agent shouldn't reach green by weakening the test. Make that a failing check.
Gates only mean something if the agent can't get to green by changing the gate. The common shortcuts are the same everywhere: skip the failing test, delete or soften the assertion, loosen a type to any, lower a threshold, or add a suppression comment. Each is legitimate sometimes. None is legitimate silently.
why?
If a gate can be edited by the actor it constrains, it isn't a gate. Layers 1 to 3 make weakening a check visible and reviewable instead of silent.
Fits: Anywhere an agent can change the evidence used to accept its own work.
Owner: The test owner approves legitimate test and config changes.
Check: A known defect in a disposable fixture makes the relevant test fail. An attempted skip is flagged.
Limit: Assertion counts are a weak signal. Protected config needs platform policy, not just a CODEOWNERS file.
Layer 1Ask first
An ask rule prompts a human before the agent edits lint, type and test config or workflows.
Layer 2Diff check in CI
Flags newly skipped tests or fewer assertions for review. CI is below the session only when required checks and gate changes are independently protected; the regex is a heuristic, not a proof of test strength.
Layer 3Human-owned config
CODEOWNERS (the file that maps paths to required reviewers) on the gate paths, agent identity absent.
scripts/no-test-weakening.sh22 lines
#!/usr/bin/env bash
# A change must not reach green by weakening the tests. Stops at the first finding.
base="${1:-origin/main}"
git rev-parse --verify -q "$base" >/dev/null || { echo "Base ref $base not found. Run: git fetch origin main" >&2; exit 1; }
# Same test-file pattern as scripts/pr-size.sh: keep both in sync.
tests=(':(glob)**/*.test.*' ':(glob)**/*.spec.*' ':(glob)**/*_test.*' ':(glob)**/test_*.py' ':(glob)**/tests/**' ':(glob)**/__tests__/**')
diff=$(git diff "$base"...HEAD -U0 -- "${tests[@]}")
# 1. Tests newly skipped or focused.
if grep -m1 -nE '^\+[^+].*(\.skip\(|\.only\(|\bxit\(|\bxdescribe\(|@pytest\.mark\.skip|@Disabled|t\.Skip\(|#\[ignore\])' <<<"$diff"; then
echo "A test was skipped or focused in this diff. Fix the test or explain in the PR." >&2
exit 1
fi
# 2. Fewer assertions than before.
assert='(expect\(|assert|\.should)'
removed=$(grep -cE "^-[^-].*${assert}" <<<"$diff")
added=$(grep -cE "^\+[^+].*${assert}" <<<"$diff")
if (( removed > added )); then
echo "Assertions went down ($removed removed, $added added). Explain it in the PR." >&2
exit 1
fi
To run it in validate, uncomment its line in scripts/validate.sh. It reads the diff against the target branch, so it needs origin/main and fails with a clear message when that ref is missing.
Make the test the contract
Practice
Why it matters for agents
Write the test from the acceptance criteria and watch it fail for the reason you expect
A test written after the code can pass tautologically: it asserts what the code does, not what was required. A test that fails on a fixture typo proves nothing.
Verify by running the thing
Lint and unit tests can be green while the feature is broken. Give the agent a way to observe behavior: a smoke script or curl for an API, Playwright or a browser tool for UI.
Quarantine flaky tests before running agents unattended
A human sees a flake and hits retry. An agent sees a failure, forms a theory, and changes correct code to fix a bug that doesn't exist.
Mutation testing on changed code optional
Checks that tests fail when the code breaks: Stryker (JS), mutmut (Python), PIT (JVM). Slow, so run it nightly rather than per commit.
The tautological-test and flaky-retry rows are this guide's own reasoning, not a cited finding.
Clean Code & Comments
GoalComments explain why the code is the way it is, and nothing in the code depends on a ticket tracker.
Comments say why, never what, and never carry ticket IDs.
Code comments must earn their place, on top of clear types and interfaces for input and output. A comment that explains what the code does is a refactor candidate. Exceptions exist. When one does, an ADR or another artifact can record the decision that made the code the way it is. This rule is this guide's own proposal, not a cited practice.
why?
A comment that explains what the code does drifts out of sync with the code; one that explains why doesn't. A ticket ID rots the moment the tracker moves it.
Fits: Code should make sense without anyone's private session history. Keep domain, legal and public-contract comments.
Owner: The code owner judges clarity.
Check: Behavior tests pass after a sample cleanup, and decision links resolve. A reviewer can explain the remaining constraint from the code and its decision.
Limit: Comment counts and ticket patterns cannot judge readability or equivalence.
Before
// loop through users and check
// if they are over 18 then add
// to eligible list
for (const u of users) {
if (u.age >= 18) eligible.push(u);
}
Reference to working items (issue and ticket names) is fine in a working session. It must never reach the code — the PR itself may carry the ticket reference, in the issue link.
Before: ticket ref left in
// fix for JIRA-4821, see comment
// from @asmith on 2024-03-02
if (retries > 3) return null;
After: reasoning moved to an ADR
// Caps retries at 3. See
// docs/decisions/0031-retry-cap.md
if (retries > 3) return null;
JIRA-4821 and a colleague's name mean nothing to the codebase in a year. The rule, and why it exists, belongs in the code and the ADR, not in a ticket ID only the working session understood.
Comments that earn their place
Keep
A non-obvious constraint. A workaround with a link to its ADR. A public API contract the types can't express.
Cut
Narration of the next line. Commented-out code. Ticket IDs, names and dates. Anything a better name would say.
scripts/no-ticket-refs.sh: make the rule a gate9 lines
#!/usr/bin/env bash
# Replace ENG|PROJ with your tracker's project keys.
base="${1:-origin/main}"
git rev-parse --verify -q "$base" >/dev/null || { echo "Base ref $base not found. Run: git fetch origin main" >&2; exit 1; }
if git diff "$base"...HEAD -U0 | grep -m1 -E '^\+[^+].*\b(ENG|PROJ)-[0-9]+\b'; then
echo "Ticket reference found in the diff. Move it to the commit footer or the PR description." >&2
exit 1
fi
A change's effect on the system is shown by evidence in the PR (see the PR template), not by comments in the code. The commit says what changed; the three questions about any piece of code say where the rest of its story lives.
Hacks spread: agents copy what they read
An agent learns how this codebase does things from the code around the change. A // HACK comment does not read as a warning. It reads as an example, and the next session copies the hack, not the doubt.
Before: the hack stays, with a note
// HACK: skip the cache for now,
// the API sends stale totals
const total = await getTotal({ cache: false });
After: the reason, or nothing
// The API's totals lag by a minute. See
// docs/decisions/0042-no-total-cache.md
const total = await getTotal({ cache: false });
The comment says
Instead
HACK, XXX
Fix it now, or open an issue and leave no marker
TODO, FIXME
An issue in the tracker. The code is not a backlog
The rule matches a term only at the start of a comment, so // Temporary workaround fails and "temporary files are cleaned up" in the middle of a sentence passes. Add noInlineConfig from the hooks example, so the marker cannot hide behind an eslint-disable comment. Checked by running ESLint 10.
Research backs the direction: code models complete code much worse when the code they are given contains a likely bug (Dinh et al., NeurIPS 2023). That a hack comment steers an agent the same way is this guide's own reading, not a measured result.
"Comments say why, never what, and never carry ticket IDs" is this guide's own proposal, not a cited practice. Measure it against your own review comments before treating it as settled.
Commit Conventions
GoalThe history reads clearly, and release notes come from it with no manual changelog.
Use Conventional Commits, enforced by a hook, so history and release notes write themselves.
One standard, followed consistently. It feeds change understanding, log lookup, and release-please directly. The rules are identical for humans and agents.
why?
A convention half the authors follow is a convention you cannot build on. The commit-msg hook makes it universal instead of aspirational, and that consistency is what lets release-please turn merged PR titles into a changelog and a release PR with nobody writing one by hand.
updated stuff
fix bug
WIP
feat: changes per JIRA-4821
Accept
fix(cart): stop double-charging on retry
refactor(jobs): split queue worker from scheduler
docs(adr): supersede 0015 with 0019
The first three fail commitlint. The last, feat: changes per JIRA-4821, parses fine — commitlint's conventional config accepts it — so it's a style reject, not one the hook catches: vague, and it puts the ticket in the subject. Say what changed in the subject, and move the ticket to a footer.
A TICKET NUMBER, IN THE FOOTER
fix(cart): stop double-charging on retry
The retry re-sent the charge before the first response arrived.
It now reuses the original idempotency key.
Refs: PROJ-123
The subject stays about the change, and the ticket rides along as a footer. The spec allows any token: value footer, and its own example is Refs: #123. A footer joins this history to the issue that explains why, without putting a ticket ID in the code, where it goes stale (see clean code).
Type
Per the spec
This release-please config
feat
minor
minor, under Features
fix
patch
patch, under Bug Fixes
feat! / BREAKING CHANGE:
major
major, under its own section
chore · docs · refactor · test
no bump implied
no release, hidden from the changelog
This matches the spec: only feat, fix and breaking changes cut a release. Types hidden by default (chore, docs, refactor, test, build, ci, style) stay out of the changelog unless they are breaking. perf and revert do appear in it. Change that with changelog-sections in the config.
Use the .mjs extension. export default in a plain .js file fails unless package.json has "type": "module"; the error you get, "please add rules" (observed by the authors on commitlint's current release), doesn't say why.
Setup: create .release-please-manifest.json next to the config with { ".": "0.0.0" } (or your current version); release-please records the last release there. The node type also bumps package.json; pick another type for other stacks.
How it runs: it keeps one open release PR that updates CHANGELOG.md and the version from the Conventional Commits on main. Merging it creates the tag and the GitHub Release, so a person approves each release once. Squash-merge (one commit per PR, titled with the PR title) with a conventional title.
Watch out: pushes made with the default GITHUB_TOKEN trigger no other workflows, so the release PR skips your CI unless you pass a personal access token or GitHub App token as the token input. The config was not run here: try it on a test PR.
Because squash-merge turns the PR title into the commit on main, the convention has to hold on the title too, not just on each commit. Lint it on every push and edit:
The commit-msg hook that runs commitlint is in the lefthook config above. Wrap the standard in a create-commit skill so agents follow it without being reminded.
Skills
GoalPRs and commits come out the same way every time, from a few small skills that need no constant upkeep.
Four small skills are enough. Add another only if it won't need constant upkeep.
This guide's own proposal, not a finding: four skills are a workable minimum, and models keep getting better at raw coding, so lock in as little as possible. Before adding a fifth, ask whether it will need constant human upkeep.
why?
A skill that restates what the model already does well is upkeep with no return. The ones worth keeping encode this repo's own conventions, not general coding ability.
Fits: Recurring repo-specific workflows the base model does not already handle. A template or command may be enough.
Owner: The workflow owner approves the convention.
Check: On a draft PR and a failing-gate case, the agent fills the required evidence and refuses to submit on failure.
Limit: A skill is an instruction, not an enforcement boundary. Keep it only while it saves more than it costs to maintain.
Skill
What it does
Create PR
Checks the change's size first, then follows the PR template: impact of the change, how the system is affected, ADR (Architecture Decision Record) links, a reading order for the diff, and notes for reviewers (bots and humans) and for future reference.
Writes the next numbered ADR from the template, adds its INDEX line with path globs, and marks any superseded ADR.
Project-specific
How to use this repo's CLI tools, MCPs and coding style. Not library documentation: fetch that by version.
.claude/skills/create-pr/SKILL.md12 lines
---
name: create-pr
description: Open a pull request that follows the repo's PR template. Use when the user asks to open, create or submit a PR.
---
1. Run `pnpm validate`. Stop and report if it fails.
2. Run `bash scripts/pr-size.sh`. Over the warning level, look for a slice that can merge on its own and propose the split. Over the limit, draft a `Size exception:` line in the PR body explaining why it can't be split, and open the PR anyway.
3. Diff against `origin/main`. Classify the impact: docs, ui, schema, security.
4. Fill every section of `.github/pull_request_template.md`. Link the issue and any ADR the change touches.
5. Confirm the commit history follows Conventional Commits.
6. `gh pr create --title "<conventional title>" --body-file <filled template>`
7. Don't set the impact label — [the labeler](#bots) applies it from the changed paths, not this skill.
.github/pull_request_template.md22 lines
## What and why
One paragraph. Link the issue: Closes #
## Impact
- [ ] docs - [ ] ui - [ ] schema - [ ] security
How the system is affected, and what could break.
Evidence: link the test run, screenshot, benchmark or query result.
## Decisions
ADRs touched or created:
## Reviewer notes
Read first: the files that carry the change, in the order to read them.
Mechanical (skim): renames, moves, generated files.
Left out on purpose:
<!-- Over the size limit? Add a line starting "Size exception:" that says why this cannot be split. -->
## Rollback
How this is undone. "Low risk, internal only" is a valid answer.
## Validation
`pnpm validate` passed. Manual checks:
The commit says what changed. The PR shows what that did to the system: the link under Impact gives a reviewer, person or bot, something to check instead of a claim. The reading order and the mechanical list tell someone facing a large diff where to start. In Cisco's data, changes the author annotated first had fewer defects, though that may only mean careful authors annotate.
Before you write a skill
Will a newer model do this well without the skill? If so, skip it.
Will it need human hours every month to keep current? If so, it will rot. Skip it or shrink it.
Does it encode this repo's convention, or a general tutorial? Keep the first, drop the second.
GoalAnyone, human or agent, gets a trustworthy green or red from one command, fast enough that nobody skips it.
One command, validate, runs every gate in parallel and reports the first red as soon as any gate finds it.
Lint, type checks, unit tests, and any project-specific check: automated, and required before a PR can merge, via required status checks on the branch. A package runner (pnpm, yarn, bun) reads one script from package.json: validate. That name is what everything else calls.
why?
Local and remote must never disagree. When pre-push and CI call the same script, "it passed on my machine" becomes rare — an observation from running this setup, not a guarantee, since OS, Node version and caches can still differ. Keep validate fast enough that nobody, human or agent, is tempted to skip it: run the gates in parallel, so the wait for a red is the time of the fastest failing gate rather than the sum of the ones before it. Hearing about a red early and stopping the run are separate choices — a script that prints each gate as it lands gives you the first red immediately and the rest anyway. Stop early for the reader who pays context for every line, which is the agent; report in full for the reader who pays nothing, which is CI.
packageManager pins the pnpm version. pnpm/action-setup in CI/CD needs either this field or an explicit version: input — without one, the action fails.
.nvmrc1 line
24
actions/setup-node in CI/CD reads this file via node-version-file. One file, read by CI and by any local version manager (nvm use).
scripts/validate.sh46 lines
#!/usr/bin/env bash
# Runs every gate in parallel. The first one to fail stops the rest.
set -uo pipefail
set -m # job control: each gate gets its own process group, so it can be stopped whole
MAX_LINES="${MAX_LINES:-20}"
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
names=(); pids=()
gate() { # gate <name> <command...>
local name=$1; shift
( "$@" >"$tmp/$name.log" 2>&1; echo $? >"$tmp/$name.rc" ) &
names+=("$name"); pids+=($!)
}
gate steering bash scripts/steering-drift.sh
gate adr bash scripts/adr-drift.sh
gate tickets bash scripts/no-ticket-refs.sh
# gate tests-kept bash scripts/no-test-weakening.sh
# gate permsdrift bash scripts/permissions-drift.sh
# gate codeowners bash scripts/check-codeowners.sh
# gate arch pnpm --silent check:arch
# gate flags bash scripts/flag-expiry.sh
# gate size bash scripts/pr-size.sh
gate lint pnpm --silent lint
gate typecheck pnpm --silent typecheck
gate test pnpm --silent test
# Poll for the first failure. (macOS ships bash 3.2, which has no `wait -n`.)
while :; do
pending=0
for i in "${!names[@]}"; do
n=${names[$i]}
if [[ ! -s $tmp/$n.rc ]]; then pending=1; continue; fi
[[ $(<"$tmp/$n.rc") == 0 ]] && continue
set +m # stop bash printing "Terminated" job notices into the report
stopped=""
for j in "${!names[@]}"; do
[[ -s $tmp/${names[$j]}.rc ]] || { kill -TERM -- "-${pids[$j]}" 2>/dev/null; wait "${pids[$j]}" 2>/dev/null; stopped="$stopped ${names[$j]}"; }
done
echo "validate: '$n' failed.${stopped:+ Stopped before finishing:$stopped.}" >&2
head -n "$MAX_LINES" "$tmp/$n.log" >&2
exit 1
done
(( pending )) || exit 0
sleep 0.1
done
validate is the only name anyone needs to remember. It starts every gate at once. At the first failure it stops the rest, prints that gate's first 20 lines, and names the gates it stopped.
To adapt it, change the gate lines; the six commented lines are optional checks from later sections. It polls for the first failure because the bash on macOS (3.2) has no wait -n. Tested on that bash: all green, an early failure with slower gates still running (stopped, no processes left behind), two gates failing together, and a missing command.
Stop early, or report in full
Two questions get run together here: when do you hear about a red, and does the run stop. Parallel gates answer the first on their own — the wait for a red is the time of the fastest failing gate, not the sum of every gate before it. Whether the run then stops is a separate choice, and it depends on which of the three callers above is reading.
An agent pays context for every line it reads, so a long report is a real cost and invites fixing five things at once. For the agent's own call, the Stop hook, stop at the first failure and cap the output: the price is one fix per run, and that is the right price when the reader is paying by the line. validate.sh above is that variant.
Nobody pays context for a CI log, or for a terminal a person is watching. There, a run that reports every gate is worth more: five reds in one pass is five fixes, not five runs.
To adapt the script that way, drop the kill loop and print each gate as its .rc file appears. You get the first red at once and the rest anyway. Keep the per-gate output cap: one runaway gate should not drown the other nine.
Between stages the answer is always stop, because a stage that runs after a failed one wastes minutes and reviewer attention — that is CI/CD's "needs" edges, and the same reasoning applies to a local script that builds before it tests. Stop between stages; inside one stage, report.
Tool
Stop at the first failure
Vitest
--bail 1
pytest
-x
go test
-failfast: no new tests start after the first failure
Gradle
--fail-fast
cargo test
The default. It stops after the first failing test binary; tests inside one binary still finish
ESLint, ruff, mypy, tsc
No such option. validate.sh caps the output instead
commitlint
No such option. It checks one short message
ESLint's row cites its CLI docs. The ruff, mypy and tsc cells come from running --help on each, not from their docs. Tools not listed weren't checked.
With gates in parallel, "first" means first in time. If two go red at once, the one listed earlier in validate.sh is reported, and a rerun may name the other. Both are real failures.
Keep it under ten minutes
A gate nobody runs is not a gate, and people skip slow ones. Fowler's answer is a deployment pipeline: "multiple builds done in sequence". The first, the commit build, "has to be done quickly", taking shortcuts that catch fewer bugs, with a target of "the XP guideline of a ten minute build".
validate is this project's commit build: everything required before a change becomes someone else's problem, and nothing more.
One name does not mean one process. Inside validate, stages run in sequence and stop between each other; inside a stage, gates run at once and all report. Four ways to break it up, with what each one costs:
Break it up
How
What it costs
Stages, cheapest first
Source-only checks, then the build, then whatever needs a server or a browser
Another script name — but not another source of truth, because validate is what calls it
Scope to the diff
vitest --changed, jest --changedSince, nx affected -t test, turbo --filter, lint-staged over staged files
The gate starts trusting a dependency graph to tell it what cannot have broken
Shard one slow gate
--shard=k/n in Vitest, Jest or Playwright: one shard per core locally, one per runner in CI
Nothing, as long as the script hands out the split instead of a CI file naming the pieces — see CI/CD
Cache what did not change
Task caching in Nx or Turborepo, the dependency cache in setup-node
A stale cache returns a green that means nothing, and it fails silently
Only the first two are free of judgment. Scoping and caching both answer "this cannot have broken" from a model of the code instead of by running it, so the honest home for them is the loop you run every few minutes, not the gate that decides a merge. Run the full set before code leaves the machine and again in CI; let the scoped run be the thing that saves you the wait. That split is this guide's own position, not Fowler's.
The first stage pays for itself. Any check that reads only source — a schema, a naming rule, a steering-doc drift check — can answer before the first file is compiled. Leave it in the slow stage and a sub-second answer arrives behind the build and the browser work, so you wait a minute to be told something that was knowable at the start. Split those out under their own name, preflight, and run them first.
That subset is worth naming because it is the only one an agent can usefully run mid-task. It needs no build, so a hook can call it after a batch of edits and answer in under a second. The Stop hook still runs all of validate.
A subset named in a CI file will drift. A subset that validate itself calls first is a stage.
The quotes are from "Keep the Build Fast" in Fowler's Continuous Integration, which points to Humble and Farley's Continuous Delivery for the full pipeline pattern. Each tool flag is from that tool's own docs.
Two lessons from building this, documented in neither: don't stop in-flight work on the first failure. Playwright handles SIGTERM by closing the browser, so a healthy test still running reports an error that never happened. Stop starting work instead. And shard flat: a sharded gate's pieces go in the one pool as sibling tasks, never forked inside a task the pool already started.
Same gate, any stack
Stack
Lint
Types
Tests
Runner
TypeScript
eslint
tsc --noEmit
vitest run --bail 1
pnpm / bun
Python
ruff check
mypy or pyright
pytest -x
uv / make
Go
golangci-lint run
go vet ./...
go test -failfast ./...
make / just
Rust
cargo clippy -- -D warnings
cargo check
cargo test
cargo / just
JVM
checkstyle / spotless
compiler
gradle test --fail-fast
gradle / maven
One script, three callers
AgentStop hook
Runs before the agent says "done", so it hears about red while it can still fix it. See hooks.
DeveloperPre-push
Runs before code leaves the machine. Configured below with lefthook. Skips the size gate — it needs the PR body, which doesn't exist yet — and lets CI/CD run it instead.
RemoteCI
Runs before merge. Same script, so the same result. See CI/CD.
lefthook.yml — local gates for humans and agents alike9 lines
GoalNothing merges that the same validate you run locally would reject.
CI runs the same validate as your laptop, in stages that stop at the first red.
Sequential stages, each requiring the previous one to exit green before it runs. Different rules for PR validation, build pipelines, branch previews and release drafting, all calling the same validate your developers run locally. That validate runs its own gates in parallel and stops at the first red, so the first stage fails as fast as it can.
why?
A stage that runs after a failed one wastes minutes, money and reviewer attention. "Needs" edges make the failure cheap and the cause obvious — GitHub skips every job that needs a failed or skipped one.
Fits: A shared integration boundary needs repeatable evidence. A small project can start with a simpler hosted gate.
Owner: The repository admin owns the required checks.
Check: A failing fixture PR on an approved test branch fails CI and cannot merge. Local and CI checks match.
Limit: A green workflow does not prove required checks or bypass policy. Query authorized APIs or ask the admin.
PIPELINE
validategates
✓→
build
✓→
bot reviewby impact
✓→
previewlabel-gated
✓→
releasedrafted
A red result halts the pipeline before the next stage runs: no build off broken validation, no deploy off a broken build.
Preview waits on bot review. Any blocking finding halts it there, before a preview environment is even built. That also saves the infrastructure cost of standing up a preview for a change already known to be broken.
A label (for example preview) can gate the preview build itself. Not every PR needs one spun up automatically.
Split validate across CI jobs only if the script hands out the split. A job running a subset named in YAML runs something your laptop never does, and the two drift as soon as a gate is added.
Instead, have the script print the job matrix (--plan) and run one group per job (--group). CI runs the same gates, chunked, and a new gate joins the next run with no YAML edit. Worth it when the runner has fewer cores than your laptop, which is usual. Stages stay sequential, each waiting for the one before to go green. Other ways to speed up validate (stages, scoping to the diff, caching) are in Validation gates.
GitHub's default pull_request types are opened, synchronize and reopened. This workflow adds labeled, so applying the preview label runs the job without waiting for the next push, and edited, so editing the PR body re-runs the size gate it feeds. pnpm/action-setup@v6 needs a version: input or the packageManager field in package.json; actions/setup-node@v7 reads .nvmrc for the Node version. Both are defined once, under validation gates.
setup-node@v7 caches npm downloads by default. pnpm isn't cached unless you set cache: pnpm, which the workflow above does.
release-please (configured under commit conventions) reads the Conventional Commits merged to trunk and keeps one open release PR that updates CHANGELOG.md and the version. Merging that PR tags the release and publishes the GitHub Release. No manual release notes, and one human approval per release.
PR Review & Agent Autonomy, by Impact
GoalReviewers' attention goes where the impact is, and an agent's autonomy is set by that impact.
Cheap review rounds filter first, and how much an agent may do depends on the change's impact.
Since a lot of code is now generated quickly, run rounds of review with different criteria before a human looks at it. Which rounds run, and how much the agent may do on its own, depends on the tech stack and on the impact of the change, not on a blanket rule.
why?
Bots are cheap and tireless, humans are neither. Sequence them so the cheap rounds filter first and the human sees only what survives. Keep each bot to one job, and remove any bot whose comments the team has learned to ignore.
Fits: Review rounds that cut real review load. A human-only path may fit low volume.
Owner: The risk owner approves autonomy.
Check: Fixture PRs on docs and sensitive paths pick the intended rounds. A failed required round blocks merge on a test branch.
Limit: Labels, line counts and a flat fix rate cannot justify auto-merge on their own. People decide exceptions and promotions.
Level
The agent may
The human
L0 Suggest
Propose changes. Nothing is written.
Applies them
L1 Plan-approved
Post a plan on the issue, then implement once it is approved.
Approves the plan, reviews the PR
L2 Open PR
Implement and open a PR.
Reviews and merges
L3 Auto-merge
Merge after every required check and bot round passes.
Is notified, audits afterward
Change
Detected by
Review rounds
Human
Max level
Docs only
docs/**
Lint bot
One reviewer
L2
UI component
src/web/**
Style + accessibility bot, stack bot, visual diff on the preview
One reviewer
L2
API surface
src/api/**
Correctness bot, contract check
One reviewer
L2
Schema / migration
db/migrations/**
Schema bot, reversibility check
Required, data owner
L1
Auth / security
src/auth/**
Security scan plus correctness bot
Required, security owner
L1
Dependencies
package.json, lockfile
Licence + advisory scan
Required, ask first
L1
Over the size limit
scripts/pr-size.sh
Size check before any other round
Required, and the written exception
L2
Promote on evidence, by human decision. Consider a narrow autonomy increase only with comparable fix-rate cohorts, review effort, delivery outcomes and verified protections. A flat rate alone, especially with few PRs, is insufficient. Reassess or lower autonomy after an incident.
Size counts as impact. This guide's proposal: a change over the size limit can't auto-merge, whatever its paths say. It stops at L2, or lower if a path row says so. The table above is about what a change touches, and size is a second way a change is risky: more of it goes unread. A docs-only change of 3,000 generated lines is still not one to merge on a bot's word.
Agent-complete is not done. The agent moves work to review. A human or a gate closes it.
A named human owns every merge. Assign the issue to the person running the agents. This guide's own position: the agent's own identity already provides the audit trail, so commit trailers and attribution footers add nothing on top of it.
Size comes first
The cheapest round needs no reading: count the lines. With the size check on in validate, and in the CI template build needing validate and bot_review needing build, an oversized change reaches no bot and no person until it is split or has a written exception.
That protects the reviewer, not the code:
In Cisco's data, reviewers found fewer defects as diffs grew and as they hurried.
Faros found review took 91% longer as teams went from their lowest to their highest AI-adoption quarters (vendor data, correlational).
A bot round filters what a person has to read. It does not make an unreadable diff readable.
Examples of what fills a round: a Claude-based review job (claude-code-action) with your rubric; stack-specific checks such as React Doctor for React (GitHub Actions setup); a dependency and licence scanner; a visual-diff round against the PR's preview deployment. The dependency bot's own PRs run these same rounds; unattended scheduled upgrades still require a human-approved scope and verified protections, not just green bot results.
.github/labeler.yml: turn paths into an impact label12 lines
pull_request_target runs with write access, so this workflow must only read file paths. Never check out or run the PR's code in it. The labeler owns these impact labels: it applies impact:docs, impact:ui, impact:schema and impact:security from the paths above on every run, and no skill sets them by hand.
.github/workflows/bot-review.yml: the reusable workflow ci.yml calls17 lines
name: bot-review
on:
workflow_call:
permissions:
contents: read
jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/dependency-review-action@v5
with:
fail-on-severity: moderate
# One job per review round. Add yours here: a Claude review job,
# a stack-specific check. Each stops the pipeline when it fails.
This is a real first round, not a placeholder. On private repositories the dependency review needs GitHub Code Security or GitHub Advanced Security (GitHub split the two in 2025); without either, replace that job with your own round.
.github/CODEOWNERS: make the human review depend on impact3 lines
Two more rounds, both this guide's own proposals rather than sourced practice. Like the other cheap rounds, they filter and ask for a human look; they do not give verdicts.
Evidence check: flags a PR whose Impact is more than docs and has no evidence link.
Intent check: compares what the issue, the PR description or a handoff says was done against the diff. Every claim has a change, every change has a claim, and every "ADR: y" has an ADR in the diff.
Dedicated Agents & an Orchestrator
GoalEach agent works inside one domain, and no context window carries more than its job needs.
Give each agent a domain, and let an orchestrator keep the main context small.
Give each agent a domain, and put an orchestrator in front that dispatches subagents. The point is to protect the main context window: exploration, test output and search noise stay inside a subagent, and only a short summary comes back.
why?
A shared context window is a scarce resource, and exploration, test output and search noise fill it fast. Anthropic's own multi-agent research system keeps that noise inside each subagent and returns only a condensed report to the lead agent, which is the trade this pillar makes at repo scale.
Fits: Separable work, where splitting saves more than coordinating costs. One agent is fine for a small task.
Owner: The task owner approves delegation and scope.
Check: Two disposable tasks that do not overlap are done apart, then integrated and validated together. A shared-file conflict is serialized or escalated.
Limit: Prompts name ownership but do not enforce file isolation or grant permission to spawn agents.
orchestratorplans · dispatches · merges summaries · never edits code
↓ ↓ ↓
api-agentsrc/api, src/services, src/repos
exploretests
ui-agentsrc/web, design tokens, a11y
explorereview
infra-agentmigrations, workflows, config
exploreplan
Each agent's context stays small. The orchestrator's stays small too, because it only reads summaries.
.claude/agents/api-agent.md13 lines
---
name: api-agent
description: Owns everything under src/api, src/services and src/repos. Use for endpoint, service and repository work.
tools: Read, Grep, Glob, Edit, Bash
model: sonnet
---
You own the API domain and nothing else.
Before editing, load the ADR lines in docs/decisions/INDEX.md that govern the paths you touch.
Run `pnpm validate` before reporting done.
Report back in under 200 words: files changed, gate result, open questions.
Do not paste diffs or command output into your report.
Do
Split by domain boundary, not by task type. Give every agent an explicit file scope and a short report format. Match the model to the job.
Don't
Switch agents mid-conversation (see sessions). Create an agent per ticket. Split work so small the coordination costs more than the context it saves.
Deploy Approval & Kill Switches
GoalNo agent changes production alone, and the team has rehearsed how to stop both the change and the agent.
A human approves production deploys, and there is a rehearsed way to stop both the change and the agent.
Merging is not deploying, and neither should be something an agent does alone in production. Two ideas: a human approves every production deploy, and there is a way to stop both the change and the agent, rehearsed before it is needed.
why?
A kill switch you have never used is a hypothesis. Rehearse step 1 on a test agent account and you learn whether it works, and how long it takes, on a quiet day instead of during the incident. Automatic triggers help too: loop detection in the metrics can page a human before the damage compounds.
Fits: Production changes need a release and a stop. Without production, the deploy can wait; access limits cannot.
Owner: The release or on-call owner authorizes deploys, rollbacks and emergency action.
Check: In staging with disposable data, an unapproved deploy is blocked, then approval and rollback work.
Limit: Never deploy or revoke live credentials to test the guide. A manual trigger is not enough if the agent can press it.
Human-approved deploys
CI publishes from a tagged release. Agents don't deploy production by hand. Use your platform's deployment environments so production waits for a person.
.github/workflows/deploy.yml20 lines
name: deploy
on:
push:
tags: ['v*']
jobs:
staging:
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v7
- run: ./scripts/deploy.sh staging
production:
needs: staging
runs-on: ubuntu-latest
environment: production # reviewers are set in repository settings, not here
steps:
- uses: actions/checkout@v7
- run: ./scripts/deploy.sh production
Set on the production environment
Why
Required reviewers (up to 6 people or teams; one approval releases the job)
A human is in the loop. Configured in repository settings, not in the YAML.
Prevent self-review
Whoever triggered the deploy can't also approve it. The agent identity is never a reviewer.
Deployment branches and tags limited to v*
Only a release can reach production.
Production credentials stored as environment secrets
They exist only for jobs that reference the environment, so they stay off the agent's filesystem.
Required reviewers and prevent-self-review are only available for public repositories on GitHub Free, Pro and Team; a private repo needs GitHub Enterprise for this table. Without Enterprise, use a fallback instead: protect the release tag, and gate the production job behind a manual workflow_dispatch run that only a human triggers. On another platform, look for the same three properties: approval gates, no self-approval, scoped secrets.
Every PR states its rollback. The PR template has a Rollback section. For anything irreversible, say how it is undone; for the rest, "low risk, internal only" is a legitimate answer. It is short on purpose.
Two kinds of kill switch
ProductStop the change
Ship high-impact changes behind a flag that is off by default. The flag is the kill switch. Test it works with the flag off, and remove it in the same issue once the change is proven.
AgentStop the actor
Because agents have their own identity, you can cut them off without touching anyone else's credentials: revoke the token, lock the branch, disable the workflow.
docs/PERMISSIONS.md (add this section)15 lines
## Stopping agents
Owner: your platform team. Rehearse it before you need it.
Pull it when any of these is true, without waiting for a second opinion:
- a loop or runaway alarm fires (see Metrics), or the on-call is paged by one
- a gate, branch protection or review requirement was bypassed
- an agent reached credentials, production or customer data
- nobody can say what a running agent is doing
1. Stop new work: revoke the agent identity's token. Human credentials are untouched.
2. Stop merges: lock the default branch, and remove the agent from any bypass list.
3. Stop automation: `gh workflow disable "<agent workflow>"` for agent-triggered workflows.
4. Stop sessions fleet-wide: push a managed-settings deny rule for Bash, Edit and Write. Not immediate — treat it as a follow-up, not step 1.
5. Undo the product change: turn the flag off, or follow the PR's Rollback section.
6. Record what happened on the issue. Write an ADR if a control has to change.
Anyone on the team may pull it, with no approval needed: a needless stop costs an afternoon of re-runs, and a late one costs the incident. Steps 1 to 3 are immediate. Step 4 is not: a managed-settings deny rule reaches sessions on a delay (hourly for server-managed settings, every 30 minutes under MDM), so it is a fleet-wide follow-up, not the first move.
Of the triggers above, only loop detection can be instrumented today, and it needs custom tooling: Claude Code's OTel export has no per-file or loop metric. This guide proposes wiring that alarm to page the on-call instead of relying on someone noticing. Step 6 turns a false alarm into a better threshold instead of a story.
Step 5 assumes the flag still exists. Ops flags are kept on purpose for exactly this; release flags are removed on schedule (see flag hygiene), so check that the one you need to turn off has not already been deleted.
Metrics & Evals
GoalYou can tell whether the setup earns its keep, starting with how much work has to be redone.
Track attributable follow-up fix rate in a fixed window alongside review effort and delivery outcomes, this guide's own proposal.
Without measurement you can't tell which parts of this setup earn their keep. Key everything by actor, which is one more reason agents need their own identity: "the agent's PRs" is a query, "some of these were probably the agent's" is not.
why?
This guide's own proposal, not DORA's "deployment rework rate" (unplanned deployments resulting from an incident). Attributed defects reveal rework, but no one number proves effectiveness; use complete observation windows and comparable cohorts, paired with review effort and delivery.
Fits: Measures tied to a decision. At low volume, review cases instead of a rate.
Owner: The team owner chooses cohorts, windows and attribution rules.
Check: On a fixture with an attributable defect, an unrelated edit and an immature PR, only the first counts.
Limit: People settle disputed attribution. API gaps are unknown, not zero. Read quality beside review effort and delivery.
Metric
What it tells you (the authors' experience, not a measured finding)
Starting alarm
Follow-up fix rateproposal
Share of eligible merged PRs with a defect-attributed revert, reopen or corrective fix in a fixed window; definition below. Not DORA's "deployment rework rate". Pair with review effort and delivery outcomes.
Trending up in comparable cohorts
Approval latency vs diff size
A fast approval of a large diff warrants checking review depth; timing alone does not prove failure.
Large diff approved in under 2 min
Gate failures by gate
No failures may mean a good baseline, a missing check or weak coverage; exercise a known negative case.
Any gate at 0% or above 60%
Flake rate per test
Agents "fix" flakes by changing correct code, in the authors' experience.
Any test above 1%
Loop detection
The same file edited many times in a session, or the same gate failing repeatedly.
Edit >5x, or gate fail >3x in a row
Bot comment resolution
Dismissed comments train everyone to ignore the bot.
Below 40%
PR open to merge, split by review wait
Locates the real bottleneck.
Review wait trending up
Cost per merged PR
Compare tooling and human review cost alongside quality and delivered value.
None: compare over time
Define follow-up fix rate before counting
Declare eligible PRs up front: merged changes in a named repo/path/change-type cohort, with known actor identity and a full observation window. For example, use seven days after merge for every PR in that cohort; recent PRs without seven days of observation remain pending, not defect-free.
How to count it:
Numerator: eligible PRs with at least one defect attributable to that PR, shown by a linked revert, defect reopen or corrective fix inside the window. Count each PR once.
Denominator: all eligible PRs with a complete window.
Not attribution: a later edit to the same file. Exclude unrelated features, cleanup and fixes to older defects.
Record the link and the reason for the attribution. People settle disputed cases.
Gaps: report missing evidence and open cases separately, never as zero defects, and publish no precise rate from incomplete attribution. With no eligible PRs, the rate is unknown, not zero.
Keep cohort, window and attribution rules stable across comparisons, and report sample size. Pair the rate with human review minutes, review wait, delivery lead time and useful outcomes delivered; a lower rate bought by stalled delivery is not a win. These are local decision aids, not universal safety or autonomy thresholds.
Those alarms are local hypotheses, not findings or universal thresholds. Calibrate them against your codebase, risk and sample size, recording the method and date. Line, assertion and diff-size budgets are review/context signals, never evidence that code is safe. The 200-line steering cap, for example, is Claude Code's recommended target, not something measured on your repo.
Evals for the setup itself emerging
Changing AGENTS.md, a skill, a hook or the model changes agent behavior, usually without any test failing. Keep a small replay set: five to ten real, closed issues with mechanically checkable criteria. Re-run them when the setup changes and compare first-pass gate results, follow-up fixes, and tokens or cost. There is no standard tooling yet, so a script and a spreadsheet are enough to start.
Claude Code exports OpenTelemetry metrics when CLAUDE_CODE_ENABLE_TELEMETRY=1 is set, including claude_code.cost.usage and claude_code.token.usage.
Tag every agent PR and commit by identity so follow-up fix rate can be computed, not estimated.
Review the metrics on a schedule, the same way the drift check runs.
Meta Framework & Drift Checks
GoalThe setup itself does not rot: drift is caught on a schedule, not by accident.
A scheduled check keeps the setup itself from rotting.
A meta framework validates this whole configuration and keeps the project repo true to these core values. It is a template, a checker and a schedule, and the checker matters most: configuration rots silently, and prose can't tell you it has.
why?
The same "flaggable staleness" idea used for ADR globs, applied to the setup itself. Without it, this guide describes a repo that stopped existing three months ago.
Fits: The setup can drift. A scheduled manual review can come before automation.
Owner: The maintainer owns the schedule, the fixes and any auto-merge band.
Check: A seeded stale path or missing prerequisite gives a failure or an unknown, never a green from a skipped check.
Limit: A drift report proposes; it does not authorize weaker gates or production privileges.
A checker should verify
What it catches
The steering doc is under budget and every path it names exists
Bloat and dangling references
The ADR index and records agree, and each governed path still exists
Stale decisions
validate is what CI runs, in both directions
Local and remote quietly diverging
Gate paths are human-owned, and the agent identity isn't in CODEOWNERS
An agent able to edit its own gates
No secrets in tracked files; specs have one shared canonical home
Leaks, private plans and competing copies; shared repo specs are valid
Have every check report one of four outcomes, and treat only pass as green: fail, skip (preconditions absent) and unverifiable (preconditions present, no verdict reachable) are not. A check that didn't run must never render as one that passed.
Files referenced from AGENTS.md or CLAUDE.md rot with time, so make sure an automated check runs every so often. A skill that detects this drift is a good starting point: rules-check-drift. scripts/steering-drift.sh below is a no-dependency starter for the first check; the second, adr-drift.sh, lives with ADRs; the fourth, check-codeowners.sh, lives with permissions.
scripts/steering-drift.sh17 lines
#!/usr/bin/env bash
f="${1:-AGENTS.md}"
[[ -f "$f" ]] || { echo "$f not found." >&2; exit 1; }
lines=$(wc -l <"$f" | tr -d " ")
if (( lines > 200 )); then
echo "$f is $lines lines (budget: 200)" >&2
exit 1
fi
# Every `path/like/this` in backticks must exist.
for p in $(grep -oE '`[A-Za-z0-9_./-]+/[A-Za-z0-9_./-]*`' "$f" | tr -d '`' | sort -u); do
if [[ ! -e "$p" ]]; then
echo "Dangling reference in $f: $p" >&2
exit 1
fi
done
✓ AGENTS.md 118 / 200 lines
✗ AGENTS.md 2 dangling references: docs/api.md, scripts/seed.sh
✓ validate defined, called by CI and pre-push
✓ hooks PreToolUse, Stop
✗ ADR index 0012 governs src/jobs/** but nothing matches
✓ skills create-pr, create-commit
✗ PR template missing "Impact" section
Scheduled upkeep that resolves, not just reports
A drift check tells you the setup has rotted. The same schedule can also fix some rot with nobody in the loop: a dependency bot proposes the upgrade, the PR runs the same validate and review rounds as any change, and it merges itself when all is green.
Treat the bot as one more actor under the rules already here, not a special case with its own pipeline.
Scheduled job
Cadence
What it opens
Who closes it
Drift check
Weekly
A failing run, or an issue
A human. Drift is usually a decision, not a fix
Dependency bot
Weekly, off-hours, grouped
One PR per group
Itself, inside the promoted band (the only updates allowed to merge themselves). Otherwise a human
Security advisory
On advisory, ungrouped
One PR, immediately
A human, ask first. Never inside the band
Preview QA round
Per PR on UI paths
A preview URL and a visual diff
A human, when pixels changed
A bot's PR is an agent-authored change, so the impact table already sets its autonomy: dependencies sit at L1, ask first. Promote one narrow band to L3 on purpose:
dev-only dependencies, patch and minor,
after a minimum release age (days unpulled, so the ecosystem can flag a bad release),
grouped into a single PR.
Leave production dependencies, majors and wholesale lockfile rewrites (most pinned versions regenerated at once) where they are. That band is worth an ADR: it is the one place where code reaches main with no person in the path.
The band is the first packageRules entry, and nothing else.
minimumReleaseAge stops the bot shipping a release the ecosystem has not had time to yank.
The vulnerabilityAlerts override drops that wait for security fixes, which must not sit for a week, but still requires a person.
automerge merges only when your required checks pass, so branch protection, not the bot, decides what "green" means.
If you use Dependabot instead. Grouping and the schedule go in .github/dependabot.yml, but auto-merge is not a Dependabot feature: a workflow enables it on the PR with gh pr merge --auto, usually gated on dependabot/fetch-metadata output so only the update types you chose qualify, and it does nothing unless branch protection requires the checks. Two details that cost an afternoon each: secrets for Dependabot-triggered runs come from Dependabot secrets, not Actions secrets, and on a branch with a merge queue the built-in GITHUB_TOKEN cannot enqueue a PR, so that path needs an app or personal token.
Preview QA: a round that looks at the page
Agents change UI confidently, and unit tests never see a pixel. If CI already builds a preview deployment per PR, a visual-diff round is the cheapest bot round left to add: it screenshots the routes you name, compares them against a baseline, and posts the difference on the PR for the reviewer.
In-repo. Playwright's expect(page).toHaveScreenshot(), with baselines committed and refreshed by --update-snapshots. Free, and it runs inside validate. The catch is that browser rendering varies with OS, headless mode and hardware, so baselines have to be generated in the same environment CI uses: a container, not somebody's laptop.
Hosted. A visual-review service keeps the baselines and turns approval into a review step. It costs money and takes the baseline-environment problem away.
Make it evidence, not a verdict. A visual diff is supposed to go red on a UI change, so a round that blocks on any difference gets muted within a week.
Block only on routes declared stable, such as a checkout flow or a print stylesheet. Elsewhere, post the diff and let the reviewer look. The bot comment resolution row in the metrics table watches for exactly this.
Onboarding & Contributors
GoalA newcomer, or another team, gets productive from two short files.
Two short files make the repo legible to newcomers and other teams.
This guide's own proposal: two small files, written for people. An agent may read either one, but neither loads into a session the way the steering doc does.
why?
These are for people, so they don't load into every agent session. They also double as a test: if a new joiner can't get productive from them, the steering doc and the ADRs are missing something too.
Fits: New contributors or fresh agent sessions. One short entry point may replace several documents.
Owner: The maintainer owns onboarding.
Check: In a clean workspace the steps reach a running app and a passing validation, with no undocumented command. A new person finds owners and decisions.
Limit: A green setup script does not prove understanding. Onboarding must never need shared personal credentials.
CONTRIBUTING.mdRules of engagement
Written as if the repo were an open-source project or a library: how to propose a change, branch, commit, test, and get reviewed. What agents may and may not do on their own. CONTRIBUTING.md is the file GitHub surfaces to contributors by name; CONTRIBUTORS.md conventionally lists people, not rules.
ONBOARDING.mdEnough to understand the codebase
For other teams and new developers: how to run the app, an architecture map, where decisions and specs live, who owns what, and a short glossary.
CONTRIBUTING.md (skeleton)8 lines
## Propose a change
Open an issue first for anything non-trivial. See [tracker](#tracker).
## Branch, commit, test
Trunk-based, [Conventional Commits](#commits), `pnpm validate` before every PR.
## What agents may do alone
See the [impact table](#bots): autonomy is set by what a change touches.
ONBOARDING.md (skeleton)8 lines
## Run the app
One command, or a link to it. Nothing implicit.
## Architecture map
Two or three sentences, plus a link to the [ADR index](#adrs).
## Who owns what
Point at CODEOWNERS. Add a short glossary for terms unique to this repo.