Lean · Agile · Agentic way of working

Twenty-six pillars, read at walking pace

The minimum viable agentic engineering setup: the baseline every AI-assisted project needs, what each piece is, why it earns its place, and copy-ready templates your team can adapt.

choose your own way in →
Tell me a storyFollow one changeFrom idea to production, one safeguard at a time
Tier 0Groundwork

Day one. Five small pieces that make every later piece cheaper.

start here — everything else assumes these
01
Steering

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.

For the team
One short file everyone can read and agree on.
For the agent
It starts each session with the few rules that matter, not a manual it skims.
You'll notice
AGENTS.md stays short. Rules that can be scripts move out of it.
Without it
A long steering file the agent half-follows, and nobody knows which half.

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.

Worked case A new rule lands in a 400-line AGENTS.md invented example
Without itWith it
Where the rule goesLine 380, under a heading nobody readsA hook, or one line in a short file
Next sessionThe agent skims and misses itThe agent reads every line
A month laterThree rules contradict each otherThe drift check flags the stale one
the file itself
Template · AGENTS.md skeleton

Fit, owner & acceptance

  • 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.

02
Enforcement

Validation Gates

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.

For the team
One shared answer to "is it ready?", the same on every laptop and in CI.
For the agent
It can check its own work before it asks anyone, and fix the first red it sees.
You'll notice
Fewer PRs that fail in CI after passing locally. Nobody argues about which checks count.
Without it
Each person, and each agent, runs a different subset of checks, and CI finds the rest.

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.

Worked case An agent says the change is done invented example
Without itWith it
How it checksRuns the tests it remembersRuns validate, every gate
What it missesTypes fail; only CI notices, an hour laterThe first red comes back in seconds
The PROpens red, waits for a human to spot itOpens green, or does not open
the wiring itself
Template · wiring validate to git and to the agent

Fit, owner & acceptance

  • Fits: Repeatable checks the stack supports, behind one command people can find.
  • Owner: The quality owner chooses the required checks.
  • Check: A clean fixture passes. A deliberately broken one exits nonzero and names the failed check.
  • Limit: This proves only the checks you ran. Merge enforcement needs platform evidence, not a script.
package.json9 lines
{
  "packageManager": "pnpm@10.15.0",
  "scripts": {
    "lint": "eslint . --max-warnings 0",
    "typecheck": "tsc --noEmit",
    "test": "vitest run --bail 1",
    "validate": "bash scripts/validate.sh"
  }
}

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.

ToolStop at the first failure
Vitest--bail 1
pytest-x
go test-failfast: no new tests start after the first failure
Gradle--fail-fast
cargo testThe default. It stops after the first failing test binary; tests inside one binary still finish
ESLint, ruff, mypy, tscNo such option. validate.sh caps the output instead
commitlintNo 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 upHowWhat it costs
Stages, cheapest firstSource-only checks, then the build, then whatever needs a server or a browserAnother script name — but not another source of truth, because validate is what calls it
Scope to the diffvitest --changed, jest --changedSince, nx affected -t test, turbo --filter, lint-staged over staged filesThe 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 CINothing, as long as the script hands out the split instead of a CI file naming the pieces — see CI/CD
Cache what did not changeTask caching in Nx or Turborepo, the dependency cache in setup-nodeA 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

StackLintTypesTestsRunner
TypeScripteslinttsc --noEmitvitest run --bail 1pnpm / bun
Pythonruff checkmypy or pyrightpytest -xuv / make
Gogolangci-lint rungo vet ./...go test -failfast ./...make / just
Rustcargo clippy -- -D warningscargo checkcargo testcargo / just
JVMcheckstyle / spotlesscompilergradle test --fail-fastgradle / 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
commit-msg:
  commands:
    commitlint:
      run: pnpm commitlint --edit {1}

pre-push:
  commands:
    validate:
      run: pnpm validate
03
Hygiene

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.

For the team
A history anyone can read, and release notes nobody has to write.
For the agent
It can rebuild why the code changed from git log, instead of guessing from the diff.
You'll notice
Every commit says its type and scope. The changelog appears on its own when you release.
Without it
fix 2 and try again, and someone writing release notes by hand from memory.

One standard, followed consistently. It feeds change understanding, log lookup, and release-please directly. The rules are identical for humans and agents.

Worked case Release day for version 2.4 invented example
Without itWith it
The historywip, fix 2, try againfeat(invoice): …, fix(cart): …
Release notesSomeone writes them from memoryrelease-please drafts them from the titles
A breaking changeFound by a customerMarked with !, bumps the major version
config + rejected examples
Template · commitlint, and what the hook rejects

Fit, owner & acceptance

  • Fits: Structured history helps review or releases. Another consistent convention may fit as well.
  • Owner: The maintainer chooses the convention and how it maps to releases.
  • Check: The checker accepts a valid message and rejects an invalid one. A breaking-change release previews without publishing.
  • Limit: A message's shape cannot prove that its intent, attribution or version bump is right.
CONVENTIONAL COMMITS
feat(auth): add refresh token rotation
fix(billing): correct proration on downgrade
chore(deps): bump build tooling
feat(api)!: drop v1 invoice endpoints          ← breaking change
Reject
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).

TypePer the specThis release-please config
featminorminor, under Features
fixpatchpatch, under Bug Fixes
feat! / BREAKING CHANGE:majormajor, under its own section
chore · docs · refactor · testno bump impliedno 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.

commitlint.config.mjs7 lines
export default {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'subject-case': [2, 'never', ['upper-case', 'pascal-case']],
    'header-max-length': [2, 'always', 72],
  },
}

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.

release-please-config.json7 lines
{
  "packages": {
    ".": {
      "release-type": "node"
    }
  }
}
.github/workflows/release-please.yml14 lines
name: release-please
on:
  push:
    branches: [main]

permissions:
  contents: write
  pull-requests: write

jobs:
  release-please:
    runs-on: ubuntu-latest
    steps:
      - uses: googleapis/release-please-action@v5

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:

.github/workflows/pr-title.yml12 lines
name: pr-title
on:
  pull_request:
    types: [opened, edited, synchronize, reopened]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: amannn/action-semantic-pull-request@v6
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

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.

04
Enforcement

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.

For the team
Rules that hold every time, without a reviewer having to catch them.
For the agent
It gets told at the moment it breaks a rule, with the reason, and can correct course.
You'll notice
The same review comment stops coming back. Rules leave AGENTS.md and become scripts.
Without it
A rule written in the steering doc, followed most of the time, and skipped the time it mattered.

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.
block-env.sh
  path matches *.env
  echo "Blocked: ..." >&2
  exit 2
Step 3 of 5
Worked case "Never edit generated files" is written in AGENTS.md invented example
Without itWith it
The rule lives inA sentence the agent may skipA PreToolUse hook on generated/**
The agent edits oneNobody notices until the next codegen wipes itBlocked, with the reason, before the write
In reviewThe same comment, againNothing to say
the whole block
Template · the .env block, end to end

Fit, owner & acceptance

  • 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.mdTypeBecause
Route calls service, service calls repolint gateLayer boundaries are import rules: a boundary linter enforces them, so delete the line
After implementing, run the testsStop hookNames an event: the agent finishing
Migrations must be reversibleruleNeeds judgment; back it with a CI check if you can
Never read the env filedeny rule + hookA 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 -rfPreToolUse hookNames an event: a Bash call matching a pattern. Best effort: branch protection is the real control
Format files after editingPostToolUse hookNames an event; runs after the tool, so it can log or fix but can't undo it
Load the ADR index at the startSessionStart hookNames an event: session begins
Reject prompts that paste API keysUserPromptSubmit hookNames 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.

EventRoleTypical use
PreToolUsecan blockDeny secrets, destructive commands, edits to generated files
UserPromptSubmitcan blockReject prompts with credentials. Plain stdout is added to context, so it can also add branch and issue details
Stop / SubagentStopcan blockRun validate before the agent claims it is done
PreCompactcan blockSave handoff notes before compaction — Claude Code summarizing and trimming the conversation to free context, see sessions — or hold it until they are saved
ConfigChangecan blockAudit or block settings changes mid-session. It is still a hook
PostToolUseobserveAuto-format the edited file, log tool usage. The tool already ran, so exit 2 only shows stderr to Claude
SessionStart / SessionEndobserveSessionStart's plain stdout is added to context: load the ADR index, start the code-graph watcher. Errors show to you, not the agent
NotificationobservePing you when the agent is waiting for input

Wire it up

.claude/settings.json19 lines
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Bash",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-env.sh" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-validate.sh" }
        ]
      }
    ]
  }
}

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.

.claude/hooks/block-env.sh20 lines
#!/usr/bin/env bash
# Hooks receive the tool call as JSON on stdin.
in=$(cat)
path=$(jq -r '.tool_input.file_path // empty' <<<"$in")
cmd=$(jq -r '.tool_input.command // empty' <<<"$in")

block() {
  echo "Blocked: .env holds secrets. Read .env.example instead." >&2
  exit 2
}

# Read tool: check the path.
[[ "$path" == *.env.example ]] && exit 0
[[ "$path" == *.env || "$path" == *.env.* ]] && block

# Bash tool: check the command for .env / .env.local / ... (but not .env.example).
grep -oE '(^|[[:space:]/])\.env(\.[a-z]+)?([[:space:]]|$)' <<<"$cmd" \
  | grep -qv 'example' && block

exit 0
.claude/hooks/stop-validate.sh11 lines
#!/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
LayerWhen it firesWho can skip it
ESLint ruleIn the editor, on saveAnyone: there it is advice
PreToolUse hookBefore the agent writes the fileAn agent that edits the hook
Pre-commit (lefthook)On git commitAnyone, with --no-verify
validate in CIBefore mergeNobody: 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
lefthook.yml5 lines
pre-commit:
  commands:
    lint:
      glob: "*.{ts,tsx}"
      run: pnpm eslint {staged_files}

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 hookPortable 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
SessionStartSteering doc plus ADR index, by convention
StopRequired status checks, merge queue
UserPromptSubmitNone: 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.

05
Blast radius

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.

For the team
Everyone knows what an agent may do alone, and where a person must say yes.
For the agent
Clear limits it cannot widen, so it can work fast inside them.
You'll notice
Risky paths ask first. The agent's actions show up under its own identity.
Without it
An agent with your credentials, able to touch anything you can.

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.

Worked case An agent decides a migration needs a new table invented example
Without itWith it
Who may run itWhoever holds the shell, the agent includedThe migration path is ask-first
CredentialsThe developer's own, full accessThe agent's own identity, scoped
Afterwards"Who dropped that column?"The audit log names the agent and the approver
the three tiers
Table · three tiers of blast radius

Fit, owner & acceptance

  • 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.

LayerExampleCan the agent get around it?
ProseA rule in AGENTS.mdYes. It can skip it or misjudge it.
Permission rules and hookspermissions.deny, a PreToolUse hookPartly. Deny rules cover built-in file tools and recognised Bash commands (cat, sed, redirects), not a script that opens the file itself.
OS sandboxsandbox in settingsNo, 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.
Managed settingsmanaged-settings.json, server-managed or MDMNo. Highest precedence: user, project and CLI values can't loosen them.
Outside the agentBranch protection, CODEOWNERS (GitHub's file mapping a path to its required reviewers), agent identity, egress policy, secrets brokerNo. 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

TierMechanismWhat to know
Autonomousallow rules, and the Bash sandbox's auto-allowOnly what you list runs without a prompt
Ask firstask rulesA prompt every time. In dontAsk mode, anything that would prompt is denied, so unattended runs fail closed
Neverdeny rules, delivered as managed settings so they can't be loosenedBash 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
{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(!.env.example)",
      "Read(./secrets/**)",
      "Bash(npm publish *)",
      "Bash(pnpm publish *)"
    ],
    "ask": [
      "Edit(package.json)",
      "Edit(.github/workflows/**)",
      "Edit(.github/CODEOWNERS)",
      "Edit(.claude/**)",
      "Edit(AGENTS.md)",
      "Edit(scripts/**)",
      "Edit(eslint.config.*)",
      "Edit(tsconfig*.json)",
      "Edit(vitest.config.*)",
      "Edit(playwright.config.*)",
      "Edit(pytest.ini)",
      "Edit(pyproject.toml)",
      "Edit(commitlint.config.*)",
      "Edit(lefthook.yml)",
      "Bash(pnpm add *)",
      "Bash(yarn add *)",
      "Bash(bun add *)"
    ]
  },
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "filesystem": { "denyRead": ["~/"], "allowRead": ["."] },
    "network": { "allowedDomains": ["github.com", "*.npmjs.org"] }
  }
}

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
{
  "permissions": {
    "deny": ["Read(./.env)", "Read(./secrets/**)"],
    "disableBypassPermissionsMode": "disable"
  }
}

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.

.github/CODEOWNERS (gate paths)15 lines
/package.json          @your-org/platform
/.github/workflows/    @your-org/platform
/.github/CODEOWNERS    @your-org/platform
/.claude/              @your-org/platform
/scripts/              @your-org/platform
/lefthook.yml          @your-org/platform
/eslint.config.*       @your-org/platform
/tsconfig*.json        @your-org/platform
/vitest.config.*       @your-org/platform
/playwright.config.*   @your-org/platform
/pytest.ini            @your-org/platform
/pyproject.toml        @your-org/platform
/commitlint.config.*   @your-org/platform
/AGENTS.md             @your-org/architects
/docs/decisions/       @your-org/architects
Tier 1Guardrails

Make bad output hard to ship: remote checks that mirror the local ones, a branching model agents can reason about, skills that turn the conventions into one-step actions, and controls that stop an agent reaching green by changing the check.

seven pillars, one page each
06
Delivery

CI/CD: A Fail-Closed Pipeline

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.

For the team
Nothing merges that the shared check would reject, whoever wrote it.
For the agent
It gets the same verdict remotely that it got locally, so there are no surprises.
You'll notice
CI and laptops agree. A red stage stops the pipeline instead of being ignored.
Without it
A green badge that means less than the local run, and merges nobody verified.

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.

Worked case A PR passes locally and fails in CI invented example
Without itWith it
WhyCI runs different commands from the laptopCI runs the same validate
A stage goes redLater stages run anyway; the log is noiseThe pipeline stops at the first red
MergeSomeone merges "just this once"Branch protection refuses it
the stage graph
Template · stages that stop at the first red

Fit, owner & acceptance

  • 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.

.github/workflows/ci.yml (excerpt)39 lines
name: ci
on:
  pull_request:
    branches: [main]
    types: [opened, synchronize, reopened, labeled, edited]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with: { fetch-depth: 0 }
      - uses: pnpm/action-setup@v6
      - uses: actions/setup-node@v7
        with: { node-version-file: .nvmrc, cache: pnpm }
      - run: pnpm install --frozen-lockfile
      - run: pnpm validate

  build:
    needs: validate
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: pnpm/action-setup@v6
      - uses: actions/setup-node@v7
        with: { node-version-file: .nvmrc, cache: pnpm }
      - run: pnpm install --frozen-lockfile
      - run: pnpm build

  bot_review:
    needs: build
    uses: ./.github/workflows/bot-review.yml   # defined under "PR review & autonomy"

  preview:
    needs: bot_review
    if: contains(github.event.pull_request.labels.*.name, 'preview')
    runs-on: ubuntu-latest
    steps:
      - run: echo "deploy preview here"

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.

07
Delivery

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.

For the team
Reviews small enough to actually read, and no end-of-sprint merge to untangle.
For the agent
It reads the code that is shipping today, not a fork that drifted last week.
You'll notice
PRs merge within a couple of days. Unfinished work hides behind a flag. A release is a tag.
Without it
The agent edits a function that main renamed days ago, and the review is one giant diff.

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.

Worked case One two-week feature, carried two ways invented example
Without itWith it
MergesOne, on day 14Five, as each slice is done
Lines per reviewAbout 1,800About 350
A rename on mainMissed until reviewPicked up in the next slice
the limits and the gate
Reference · what “short-lived” means, size limits, flags

Fit, owner & acceptance

  • 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 branchesTrunk-based
Merge targetDays to weeks awayA couple of days
Unfinished workHeld on the branchCarried on trunk behind a flag
What the agent seesCode that diverges from productionCode that matches production
Merge costGrows with every day of driftSmall, and reviewable
Before a releaseStabilisation branchNothing. 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

open 9d · 1,845 lines waiting

Trunk-based⚑ newCheckoutFlow

open 1d · 205 lines waiting

Long-lived branchTrunk-based
Merge cost16 commits on main it has not seen0 commits on main it has not seen
What the agent seesCode that diverges from productionCode that matches production
To release todayCut a stabilisation branch, then mergeNothing. Tag the commit that is already green
Day 9 of 14

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.

SourceWhat it saysHow much weight
Google Engineering PracticesAbout 100 lines is a reasonable change and 1,000 is usually too large. A 200-line change in one file can be fine; spread over 50 files it is too largeThe team's own convention, not a study
Cisco and SmartBear, 2006Reviewers 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 density2,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
A practitioner's articleKeep a pull request to around 300 to 400 lines, and review it within hoursExperience, 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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
      - run: pnpm validate
        env:
          PR_BODY: ${{ github.event.pull_request.body }}

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.

KindLives forRemoved?
ReleaseDays to weeksYes, as soon as the feature is fully on
ExperimentHours to weeksYes, when the experiment ends
OpsDays to weeksYes, once the condition it guards against has passed
Kill switchLong-livedNo. Kept on purpose: see deploy
PermissionMonths to yearsNo. It gates a feature by user tier

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
{
  "newCheckoutFlow": { "type": "release", "owner": "payments", "expires": "2026-11-01" },
  "paymentsV2Rollout": { "type": "ops", "owner": "payments", "expires": "2026-10-15" },
  "killPaymentsV2": { "type": "kill_switch", "owner": "payments" }
}
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
FlagKindExpiresRemaining
newCheckoutFlowRelease2026-11-0117 days left
paymentsV2RolloutOps2026-10-15expires today
killPaymentsV2Kill 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.

08
Tooling

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.

For the team
PRs and commits look the same, whoever or whatever wrote them.
For the agent
It follows a short recipe for the routine jobs instead of improvising each time.
You'll notice
PR descriptions read in the same order. Reviewers know where to look.
Without it
Every PR shaped differently, and a pile of skills nobody keeps up to date.

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.

Worked case Ten agents open PRs in one week invented example
Without itWith it
PR descriptionsTen shapes, some emptyOne order: what, why, impact, rollback
CommitsMixed stylesThe commit skill writes them the same way
Skills folderThirty skills, half staleFour, each one small
the skeleton
Template · the shape of a skill

Fit, owner & acceptance

  • 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.
SkillWhat it does
Create PRChecks 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.
Create commitFollows the commit conventions and any project-specific requirement.
Record a decision proposedWrites the next numbered ADR from the template, adds its INDEX line with path globs, and marks any superseded ADR.
Project-specificHow 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.
  • Does it restate a public library's docs? Don't write it. It goes stale at the next version bump. Retrieve docs for the installed version instead.
09
Hygiene

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.

For the team
Code that explains why it is the way it is, without a trip to the tracker.
For the agent
Comments it can trust, because they say why and not what.
You'll notice
Fewer comments, and the ones left are worth reading. No ticket IDs in code.
Without it
Comments that restate the code and rot, and links to tickets that no longer exist.

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.

Worked case An agent fixes a rounding bug invented example
Without itWith it
The comment it adds// round the total// banks round half-even; see ADR 0011
Ticket reference// PROJ-482 in the codeIn the commit footer
Six months onThe ticket is archived; the comment points nowhereThe reason is still right there
before / after
Template · the same line, twice

Fit, owner & acceptance

  • 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);
}
After
const eligible = users.filter(isAdult);

function isAdult(u: User) {
  return u.age >= 18;
}

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 saysInstead
HACK, XXXFix it now, or open an issue and leave no marker
TODO, FIXMEAn issue in the tracker. The code is not a backlog
"temporary", "for now"An issue with the check that proves it is gone
A real workaroundKeep it, with the reason and its ADR
eslint.config.js (add to rules)3 lines
'no-warning-comments': ['error', {
  terms: ['hack', 'todo', 'fixme', 'xxx', 'temporary', 'for now'],
}],

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.

10
Enforcement

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.

For the team
Green means the real checks passed.
For the agent
It cannot reach green by loosening a test, so it fixes the code instead.
You'll notice
A change that weakens a test fails on its own, before review.
Without it
A test quietly rewritten to pass, and a bug that ships with a green badge.

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.

Worked case A test fails and the agent wants green invented example
Without itWith it
Easiest moveLoosen the assertionFix the code
What stops itNothing; review mightA check fails when a test is weakened
The bugShips with a green badgeNever leaves the branch
shortcut → what catches it
Three layers, one script

Fit, owner & acceptance

  • 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

PracticeWhy it matters for agents
Write the test from the acceptance criteria and watch it fail for the reason you expectA 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 thingLint 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 unattendedA 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 optionalChecks 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.

11
Enforcement

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.

For the team
The architecture holds without someone policing every import.
For the agent
It learns the boundary the moment it crosses it, not in review.
You'll notice
Layer rules live in a linter. Boundary arguments leave code review.
Without it
A shortcut import here and there, until the layers exist only in the diagram.

"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.

Worked case The UI layer imports the database client invented example
Without itWith it
Who noticesA reviewer, if they lookThe linter, on save
WhenDays later, in reviewBefore the commit
After a yearLayers exist only in the diagramLayers still hold
the rule, in config
Template · one layer contract

Fit, owner & acceptance

  • Fits: The architecture has boundaries a machine can check. A tiny single-layer app can wait.
  • Owner: The architecture owner defines the allowed dependencies.
  • Check: A forbidden import in a fixture is rejected; an allowed one passes. Existing violations start from a named baseline.
  • Limit: Import checks do not prove runtime isolation, or that the architecture is the right one.
StackToolRun
TypeScript / JavaScriptdependency-cruiser (or eslint-plugin-boundaries)depcruise src --config .dependency-cruiser.js
Pythonimport-linterlint-imports
JVMArchUnit, as a normal testgradle test
Godepguard, through golangci-lintgolangci-lint run
.dependency-cruiser.js18 lines
module.exports = {
  forbidden: [
    {
      name: 'routes-not-to-repos',
      comment: 'Routes call services. Only services call repos.',
      severity: 'error',
      from: { path: '^src/routes/' },
      to: { path: '^src/repos/' },
    },
    {
      name: 'repos-not-to-services',
      severity: 'error',
      from: { path: '^src/repos/' },
      to: { path: '^src/services/' },
    },
    { name: 'no-circular', severity: 'error', from: {}, to: { circular: true } },
  ],
}
pyproject.toml (import-linter)18 lines
[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.

StepChecksExample ruleCovers
Text in AGENTS.mdnothingroutes call serviceswhat the agent remembers
Linterstructureroutes never import reposevery import
Testsbehaviora refunded order stays refundedthe cases you wrote
Proof in Lean 4behaviora forbid always beats a permitevery 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.

12
Environment

Devcontainer

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.

For the team
Everyone, person or agent, works in the same environment.
For the agent
A clean box to work in, away from the host's secrets.
You'll notice
"Works on my machine" stops coming up. A new setup is one command.
Without it
An agent running on a laptop with every credential its owner has.

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.

Worked case A new joiner and an agent both start on Monday invented example
Without itWith it
SetupA day of README steps, three versions of NodeOne command, the same image
SecretsThe agent sees the host's ~/.awsNothing from the host is mounted
"Works for me"WeeklyGone
minimal config
Template · a minimal devcontainer

Fit, owner & acceptance

  • Fits: Reproducible setup or isolation. An approved VM, remote workspace or sandbox can do the same.
  • Owner: The platform owner approves mounts, network policy and credentials.
  • Check: A clean rebuild passes validation. In an approved test setup, a read-only mount and a disallowed endpoint both refuse.
  • Limit: A devcontainer alone proves neither secret isolation nor blocked egress. Controls you cannot inspect stay unknown.
.devcontainer/devcontainer.json14 lines
{
  "image": "mcr.microsoft.com/devcontainers/typescript-node:24",
  "features": {
    "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {}
  },
  "remoteUser": "node",
  "mounts": [
    "source=claude-code-config-${devcontainerId},target=/home/node/.claude,type=volume"
  ],
  "containerEnv": {
    "CLAUDE_CONFIG_DIR": "/home/node/.claude"
  },
  "postCreateCommand": "corepack enable && pnpm install --frozen-lockfile"
}

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

ControlHow the container helps
No host secretsDon't mount ~/.ssh or cloud credential files. Pass repository-scoped or short-lived tokens through containerEnv or your platform's secrets.
Egress allowlistThe 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 mountsMount 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 toolchainA 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.

Tier 2Memory & context

Sessions forget. These pillars decide what gets remembered, where it lives, how little of it needs to be loaded to be useful, and where the trust boundary sits for what comes in from outside.

seven pillars on what to remember, and where
13
Memory

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.

For the team
A decision is made once. The reasoning outlives the people who were in the room.
For the agent
It loads only the decisions that govern the files it touches, and sees what was rejected.
You'll notice
Fewer "why don't we just…" threads. New joiners read the index instead of asking around.
Without it
A rejected idea comes back next quarter, and the team argues it again from scratch.

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.

Worked case Someone proposes replacing the queue with cron invented example
Without itWith it
What they findNothing written; the debate restartsADR 0012, with cron listed as rejected
The agent's contextEvery doc in the wikiOnly the index lines for src/jobs/**
OutcomeA week of meetingsA five-minute read
the index, then the record
Template · the index, one record, and the drift check

Fit, owner & acceptance

  • 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.

docs/decisions/0019-event-stream.md (template)17 lines
# 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 honestHow
Append-onlyStatus transitions (accepted → superseded by NNNN) are the only edits. The body is never rewritten, so the reasoning history survives.
Mechanical drift detectionThe 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"
14
Session hygiene

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.

For the team
Work survives a closed tab, a new day or a new person.
For the agent
A fresh session picks up the work and its reasons from the issue.
You'll notice
Handoffs are a short note on the issue, not a pasted transcript.
Without it
Long conversations nobody can resume, and decisions lost when the window closes.

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.

Worked case A session runs out of context mid-task invented example
Without itWith it
What survivesA long transcript nobody readsThe plan and the reasons on the issue
The next sessionReplays the conversationReads the issue and continues
DecisionsLost with the windowRecorded where the work lives
the template, and the hooks
Template · the handoff, saved before compaction and handed back after

Fit, owner & acceptance

  • 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> · &lt;date&gt;

**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
{
  "hooks": {
    "PreCompact": [
      { "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/save-handoff.sh" } ] }
    ],
    "SessionStart": [
      { "matcher": "compact", "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/load-handoff.sh" } ] }
    ]
  }
}
.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.

15
Context

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.

For the team
Faster, cheaper sessions on a large codebase.
For the agent
It asks who calls what and gets a short answer, instead of reading whole files.
You'll notice
Less context spent on searching. Answers point at the exact symbol.
Without it
An agent reading file after file to find one caller, and paying for every line.

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.

Worked case "Who calls applyDiscount?" in a large repo invented example
Without itWith it
How the agent answersReads 40 files with grep hitsOne query to the index
Context spentMost of the windowA short list of call sites
AccuracyMisses the dynamic importFinds every reference the index knows
five questions, four ways
Reference · the questions an index answers, and four ways to answer them

Fit, owner & acceptance

  • 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.
QuestionWithout an indexWith a graph
Where is chargeInvoice defined?Grep, open candidatesSymbol lookup, one result
Who calls it?Grep, read every hitCallers list
What breaks if I change it?Guess, then run testsImpact query before editing
What's in this 900-line file?Read all 900 linesOutline: symbols and signatures
Is this export dead?Grep and hopeDead-code query with consumers

Four ways to answer those questions

SourceWhat it givesCostExamples
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 indexIt must be built and kept freshGitNexus (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 keepOne server per language, set up per repositoryThe 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 structureA budgeted summary of a repository's important symbols, or a search on code structure instead of textLess exact than an index, but no server to runAider's repository map. ast-grep (open source)
Plain searchGrep and globFree, but it reads whole filesWhatever your shell has

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.

16
Context

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.

For the team
Fewer bugs from advice written for a different version.
For the agent
It reads the docs for the version you run, not the one it remembers.
You'll notice
Fewer calls to methods that were renamed or removed.
Without it
Confident code against an API that changed two releases ago.

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.

Worked case The agent writes a router for a library you upgraded invented example
Without itWith it
Where its facts come fromIts memory of an older versionThe docs for the installed version
The codeCalls a method that was removedUses the current API
Who finds outThe build, or a userNobody has to
four sources, and two lines
Reference · where to fetch from, and the two lines that say so

Fit, owner & acceptance

  • 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.

SourceUse 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 siteThe 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 itselfTypes (.d.ts), bundled README and changelog are exactly the version you run. Cheapest source for a small question.
The CLI's own helpFor 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.

17
Memory

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.

For the team
A fact learned once is found again, with its date and its source.
For the agent
It can look up what an earlier session learned instead of rediscovering it.
You'll notice
Recurring notes get promoted into the repo, where they belong.
Without it
The same environment quirk rediscovered every week, at full cost.

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.

Worked case The staging database only accepts connections over a VPN invented example
Without itWith it
Where the fact livesIn one person's headA dated memory note, with its source
Next sessionRediscovers it after an hourFinds the note
Third time it comes upStill a notePromoted into the repo docs
entries, and when to promote
Template · what an entry looks like, and when it graduates

Fit, owner & acceptance

  • 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.
18
Trust boundary

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.

For the team
Control over what enters the codebase and what leaves it.
For the agent
Untrusted text stays data, so a web page cannot give it orders.
You'll notice
New dependencies get a check. Outbound calls go to known places.
Without it
A package nobody chose, or a prompt hidden in an issue that sends data 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.

Worked case An issue body says "also add package X and post the logs here" invented example
Without itWith it
The agent reads it asInstructionsUntrusted data
The new packageInstalledBlocked until someone approves it
The logsPosted to a public URLEgress to unknown hosts is denied
five threats, five controls
Table · five threats, the control for each, and the layer it sits in

Fit, owner & acceptance

  • 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.
ThreatControlLayer
A hallucinated or typosquatted (look-alike) package nameAdding a dependency is ask first. Egress (outbound network traffic) limited to your registry. The lockfile diff is reviewed.Hook + structural
A vulnerable or disallowed dependencyDependency review on every PR, failing on severity and licence.CI
Instructions hidden in an issue, PR comment, web page or tool outputTreat 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 machineDefault-deny egress with an allowlist. No plaintext secrets on disk.Structural
An untrusted MCP serverProject 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.

.github/workflows/dependency-review.yml15 lines
name: dependency-review
on: [pull_request]

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
          allow-licenses: MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC

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.

19
Decision guide

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.

For the team
One place to look for each kind of fact, and no duplicates to drift.
For the agent
It loads only what a task needs, from where it is cheapest to load.
You'll notice
Fewer "where is that written?" questions. Steering files stay small.
Without it
The same fact in three places, each a little different.

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.

Worked case "What is our retry policy?" invented example
Without itWith it
Where it is writtenAGENTS.md, a wiki page and a Slack threadOne ADR, linked from the index
Which one is rightThey disagreeThere is only one
Cost to every sessionLoaded whether needed or notLoaded only when src/cart/** is touched
the table, then three questions
Table · eleven facts, their homes, and the three questions that file a new one

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.
FactHomeLoaded
Route calls service, service calls repoAGENTS.mdEvery session
Never read the env fileHookNever: it runs
Why we chose row-level securityADR + index lineOn path match
Invoice API needs PATCH; acceptance criteria; where we left offIssue in the trackerWhen the task starts
Staging is frozen until FridayMemory bankOn recall, dated
Who calls billing.charge()?Code graphOn query
How to open a PR hereSkillWhen invoked
How does React 19's use() behave?Versioned docs retrievalOn query, for the installed version
May the agent add this package?Ask first + dependency reviewEnforced: never loaded
How to get the app runningONBOARDING.mdOn demand
How did this code get this way?Git history and the PR, with the ticket in the commit footerOn query: git log, blame, the PR description

What each layer costs

Always loadedPay every session
  • AGENTS.md, under 200 lines
  • ADR INDEX.md, one line each
  • Skill names and descriptions
Loaded on matchPay when relevant
  • Full ADR text for a governed path
  • A skill's body, when invoked
  • An agent definition, when dispatched
Fetched by queryPay per question
  • Code graph results
  • Library docs for the installed version
  • Memory recall
  • An issue via tracker CLI or MCP
  • Git log, blame and a PR's description

Three questions about any piece of code

  • What is in there? The code and its lean comments (clean code).
  • What decision took us there? The issue tracker, the docs and the ADRs (tracker, ADRs).
  • How did it evolve? The git log and the PRs (commit conventions).

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.

Tier 3Scale

Once the floor holds, these pieces let a team and its agents work in parallel without losing coherence: domain agents, tiered review, a shared plan, a production gate with a kill switch, whether the setup earns its keep, a check that keeps the setup itself honest, and a fast ramp for the next person.

seven more, for when you scale
20
Agents

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.

For the team
Large jobs split into pieces that each have a clear owner.
For the agent
Each agent sees only its own domain, so its context stays small and sharp.
You'll notice
The main session stays short. Specialist agents report back with summaries.
Without it
One agent holding everything at once, and losing track halfway.

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.

Worked case A change touches the API, the UI and the docs invented example
Without itWith it
Who holds itOne session with all three in contextAn orchestrator and three domain agents
Main contextFills up halfway throughHolds summaries only
ResultThe docs step gets rushedEach part done by an agent that knows it
one agent, defined
Template · one domain agent, start to finish

Fit, owner & acceptance

  • 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.

21
Review

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.

For the team
Reviewer attention goes to the changes that can hurt.
For the agent
Low-risk changes move fast. High-risk ones get a person, by rule.
You'll notice
Bots take the cheap review rounds. People read the diffs that matter.
Without it
Every PR reviewed the same way, so the risky ones get the same quick look.

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.

Worked case Two PRs arrive: a typo fix and an auth change invented example
Without itWith it
Review effortSame quick look for bothBots clear the typo; a person reads auth
Agent autonomySame for bothHigh on docs, ask-first on auth
Where attention goesSpread thinTo the change that can hurt
four levels, then the matrix
Table · four autonomy levels, and the rounds each kind of change earns

Fit, owner & acceptance

  • 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.
LevelThe agent mayThe human
L0 SuggestPropose changes. Nothing is written.Applies them
L1 Plan-approvedPost a plan on the issue, then implement once it is approved.Approves the plan, reviews the PR
L2 Open PRImplement and open a PR.Reviews and merges
L3 Auto-mergeMerge after every required check and bot round passes.Is notified, audits afterward
ChangeDetected byReview roundsHumanMax level
Docs onlydocs/**Lint botOne reviewerL2
UI componentsrc/web/**Style + accessibility bot, stack bot, visual diff on the previewOne reviewerL2
API surfacesrc/api/**Correctness bot, contract checkOne reviewerL2
Schema / migrationdb/migrations/**Schema bot, reversibility checkRequired, data ownerL1
Auth / securitysrc/auth/**Security scan plus correctness botRequired, security ownerL1
Dependenciespackage.json, lockfileLicence + advisory scanRequired, ask firstL1
Over the size limitscripts/pr-size.shSize check before any other roundRequired, and the written exceptionL2
  • 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
impact:schema:
  - changed-files:
      - any-glob-to-any-file: ['db/migrations/**', 'src/db/**']
impact:security:
  - changed-files:
      - any-glob-to-any-file: ['src/auth/**']
impact:ui:
  - changed-files:
      - any-glob-to-any-file: ['src/web/**']
impact:docs:
  - changed-files:
      - all-globs-to-all-files: ['docs/**', '**/*.md']
.github/workflows/label-impact.yml12 lines
name: label-impact
on: pull_request_target

permissions:
  contents: read
  pull-requests: write

jobs:
  label:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/labeler@v6

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
/db/migrations/   @your-org/data-owners
/src/auth/        @your-org/security
/src/api/         @your-org/backend

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.
22
Planning

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.

For the team
Everyone can see what is in flight, why, and who closes it, in one place.
For the agent
It starts from a spec with checks it can run, not from a paragraph in a chat window.
You'll notice
Each PR links to its issue. Scope creep shows up as a new issue, not a bigger diff.
Without it
The spec lives on one laptop, and the review argues about what was asked for.

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.

Worked case "Add usage-based invoices" invented example
Without itWith it
Where the spec isA chat message and a local notes fileOne issue, linked from every PR
Acceptance"Looks right"Checks an agent can run
SizeOne huge PRThree issues under a milestone
the mapping, then the issue
Template · the same concepts in any tracker, and an issue an agent can pick up

Fit, owner & acceptance

  • 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.
EXAMPLE
Roadmap     Self-serve billing
└ Project   Usage-based invoicing
  ├ Milestone Invoice API
  │   ├ GET   /invoices     issue
  │   ├ POST  /invoices     issue
  │   └ PATCH /invoices/:id issue
  └ Milestone Invoice UI
      └ list, detail, download    issues
ConceptGitHubLinearAny tracker
IssueIssueIssueStory, task, bug
MilestoneMilestoneProject milestoneEpic or release slice
ProjectProject (board)ProjectA deliverable group
RoadmapProject roadmap viewInitiativeRoadmap or portfolio view

Make an issue agent-ready

  • 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.

23
Delivery

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.

For the team
Production never changes without a person saying yes.
For the agent
It can prepare a release, but it cannot ship one alone.
You'll notice
Deploys wait for an approval. Stopping one is a drill, not an improvisation.
Without it
An agent deploying at night, and nobody sure how to stop it.

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.

Worked case A bad release goes out at 18:00 invented example
Without itWith it
Who shipped itAn agent, on mergeAn agent prepared it; a person approved it
Stopping itSearch for the right runbookA rehearsed kill switch, one command
Stopping the agentUnclearIts token is revoked the same way
the workflow, then the switches
Template · the approving workflow, and two kinds of kill switch

Fit, owner & acceptance

  • 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 environmentWhy
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-reviewWhoever 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 secretsThey 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.

24
Measurement

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.

For the team
Evidence for whether the setup is worth what it costs.
For the agent
Its autonomy can grow on a path where its work rarely needs redoing.
You'll notice
Follow-up fixes get counted. Debates about the agents start from data.
Without it
Opinions about whether the agents help, and no way to settle them.

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.

Worked case Leadership asks whether the agents are worth it invented example
Without itWith it
The answerAnecdotesFollow-up fix rate over a fixed window
Autonomy decisionsGut feelingEarned per path, on the record
Next quarterThe same debateA trend to compare against
eight rows, plus the counting rules
Table · eight metrics, local alarms and the fix-rate definition

Fit, owner & acceptance

  • 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.
MetricWhat it tells you (the authors' experience, not a measured finding)Starting alarm
Follow-up fix rate proposalShare 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 sizeA 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 gateNo 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 testAgents "fix" flakes by changing correct code, in the authors' experience.Any test above 1%
Loop detectionThe 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 resolutionDismissed comments train everyone to ignore the bot.Below 40%
PR open to merge, split by review waitLocates the real bottleneck.Review wait trending up
Cost per merged PRCompare 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.
25
Upkeep

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.

For the team
A setup that stays true as the code changes around it.
For the agent
Its instructions keep matching the repo, so it is not misled by stale files.
You'll notice
A scheduled check flags drift. Stale rules get fixed, not discovered.
Without it
Steering files that describe last year's repo, followed faithfully.

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.

Worked case A script referenced in AGENTS.md was deleted invented example
Without itWith it
Who noticesAn agent, by failingThe weekly drift check
WhenWeeks laterWithin a week
The fixWhoever trips on itA PR the check opens
what to check, and who closes it
Template · what a checker verifies, and the schedule that resolves it

Fit, owner & acceptance

  • 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 verifyWhat it catches
The steering doc is under budget and every path it names existsBloat and dangling references
The ADR index and records agree, and each governed path still existsStale decisions
validate is what CI runs, in both directionsLocal and remote quietly diverging
Gate paths are human-owned, and the agent identity isn't in CODEOWNERSAn agent able to edit its own gates
No secrets in tracked files; specs have one shared canonical homeLeaks, 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
.github/workflows/drift.yml14 lines
name: drift
on:
  schedule:
    - cron: '0 6 * * 1'      # every Monday
  workflow_dispatch:

jobs:
  steering:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: bash scripts/steering-drift.sh
      - run: bash scripts/adr-drift.sh
      - run: bash scripts/check-codeowners.sh
baseline-check (illustrative output)7 lines
✓ 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 jobCadenceWhat it opensWho closes it
Drift checkWeeklyA failing run, or an issueA human. Drift is usually a decision, not a fix
Dependency botWeekly, off-hours, groupedOne PR per groupItself, inside the promoted band (the only updates allowed to merge themselves). Otherwise a human
Security advisoryOn advisory, ungroupedOne PR, immediatelyA human, ask first. Never inside the band
Preview QA roundPer PR on UI pathsA preview URL and a visual diffA 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.

renovate.json26 lines
{
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
  "extends": ["config:recommended"],
  "schedule": ["before 6am on monday"],
  "minimumReleaseAge": "7 days",
  "dependencyDashboard": true,
  "osvVulnerabilityAlerts": true,
  "packageRules": [
    {
      "matchDepTypes": ["devDependencies"],
      "matchUpdateTypes": ["patch", "minor"],
      "groupName": "dev dependencies",
      "automerge": true,
      "automergeType": "pr"
    },
    {
      "matchUpdateTypes": ["major"],
      "automerge": false,
      "addLabels": ["impact:deps"]
    }
  ],
  "vulnerabilityAlerts": {
    "minimumReleaseAge": null,
    "automerge": false
  }
}

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.

26
People

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.

For the team
Newcomers and other teams get productive without a guided tour.
For the agent
The same two files that orient a person orient an agent.
You'll notice
Fewer onboarding calls. Outside contributions arrive in the right shape.
Without it
Knowledge that lives in people, and a repo only insiders can work in.

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.

Worked case Another team wants to send a small fix invented example
Without itWith it
How they startAsk around for a dayRead CONTRIBUTING and ONBOARDING
Their PRWrong branch, wrong formatRight shape on the first try
Their agentHas no idea where to beginReads the same two files
both skeletons
Template · both files, as skeletons

Fit, owner & acceptance

  • 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.
Adoption

Making it stick

None of this is final. Models and tools will keep moving. The goal is to stop reinventing the baseline on every project.

Assess the goals that fit your repo before ticking controls. A tick is a personal note, not proof of achievement; use the rollout assessment below to record applicability, ownership and behavioral evidence separately. Equivalent controls count when they preserve the goal. The scorecard suggests an order, not an all-26 mandate; its Stop hook and CODEOWNERS gate sit in step 1 because they depend on groundwork. The state below is a sample; your ticks stay in this browser only.

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
Rollout order, what to measure & 13 anti-patterns

Assess the goal before choosing the control

The 26 pillars are a menu of goals, not a mandate to install 26 artifacts. For each relevant goal, keep a short assessment in the team's shared decision home:

  1. Fit: applicable, deferred (name the prerequisite and revisit trigger), or not applicable (explain why). Team size, stack, risk, platform plan and existing controls matter; tiers suggest an order, not universal prerequisites.
  2. Feasibility and authority: what tools, access, platform features and human approval are needed? An equivalent control is fine if it preserves the goal; name what it covers and what it cannot enforce. Do not grant privileges just to complete the list.
  3. Owner and acceptance: name the human decision owner and the agent's permitted checks. Define one observable positive or safe negative test, with expected result, scope, date and evidence link. Use disposable fixtures or an approved test environment, never live secrets or an unauthorized production probe.
  4. Evidence, separately from fit: missing (no control found), configured (present, not exercised), verified (expected behavior observed), failed (observed mismatch), or unknown (cannot inspect or test). File presence is not achievement. Agents inspect local behavior or authorized APIs; unavailable policy or infrastructure checks stay unknown until the human owner supplies evidence. A human decision cannot be replaced by a green check.
  5. Cost and outcome: estimate upkeep and review effort; record the current outcome and a fixed review window. Compare defect/rework, review effort and delivery outcomes, not just configuration counts.
  6. Exit: name the revisit trigger and the condition to remove, replace or simplify the control. The human owner approves changes to required protections; never remove a safety boundary merely because it has not fired.

The fit/owner/acceptance notes in each pillar's details are suggested tests, not claims that those tests have been run in your environment.

A suggested rollout

  1. Start with one hook and one gate. Prove the pattern on a single repo before scaling it.
  2. Assess the Tier 0 goals first: steering, validate, commit conventions, hooks, and permissions. Reuse verified equivalents; add only the missing applicable controls in reviewable changes. Protect authority boundaries before unattended work.
  3. Adopting into an existing repo? Ratchet it. Start new quality gates in report-only mode, without weakening existing protections. Baseline identified violations, not just their count: no new violation may replace an old one. Hold new and changed code to the standard; require the check after proving it rejects a new violation and accepts the baseline. Quarantine known flaky tests with an owner, repair date and recorded coverage gap; do not silently call them green.
  4. Adopt applicable Tier 1 controls once their groundwork is verified. CI mirrors the local gate; skills wrap the conventions. Use evidence and prerequisites, not a universal waiting period.
  5. Consider Tier 2 when sessions repeat themselves. First check whether a better shared home or retrieval step solves the problem before adding memory.
  6. Select Tier 3 controls when their problem exists. Parallel work may justify orchestration and impact review; deploy approval and follow-up fix rate tracking matter from the first production deploy. Do not add a team-scale mechanism solely to complete a tier.
  7. Revisit this as an ADR of its own. Supersede it when the baseline changes.

Measure what's working

Track attributable follow-up fixes alongside review effort and delivery outcomes. Metrics & evals defines the eligible cohort and observation window; alarms are local hypotheses, not universal thresholds.

Anti-patterns

A 600-line AGENTS.md
Everything loads always. Split into hooks, ADRs and skills.
Rules the model "should" follow
Anything naming an event becomes a hook.
Competing or private copies of a spec
Keep one canonical, shared and reviewable home: the tracker, versioned repo docs, or another accessible system. Link to it instead of maintaining parallel copies.
Editing ADRs in place
Destroys the reasoning history. Supersede instead.
Switching agents mid-conversation
The new agent inherits assumptions, not reasons. Hand off and restart.
Skills that teach the model to code
This guide's opinion: newer models make them obsolete, and they need constant upkeep in the meantime.
Five bots that all comment on everything
Noise gets ignored. One job per bot, allocated by impact.
Permissions written only in prose or hooks
A session can skip or edit both. Put a control below the agent.
The agent can edit its own gates
It eventually will. CODEOWNERS on gate paths, agent identity absent.
The agent commits as a person
No audit trail and no way to revoke it alone. Give it its own identity.
A kill switch nobody has rehearsed
You find out it doesn't work during the incident.
Stack skills that restate library docs
They rot at every version bump. Fetch docs for the installed version.
A validate that takes minutes
It gets skipped. Run the gates in parallel and trim slow tests.
References

Sources & further reading

Every pillar ends with the sources behind it, and every source below links back to the pillars that cite it. Each link was opened and checked when it was added: 18 September 2026 for the original set, 20 September for the entries added since, 21 September for those added in the comment review, 22 September 2026 for the entries added in the sourcing audit, 7 October 2026 for the four added with the speed section of [Validation gates](#gates), 30 November 2026 for the two Cedar entries in [Architecture as a gate](#arch), and 30 November 2026 for the ESLint, React and code-completion entries in [Hooks](#hooks) and [Clean code](#cleancode). Vendor documentation changes quickly, so re-check a detail before you rely on it, for the same reason this guide says to fetch library docs by version.

Claude Code documentation · 18 sources
Anthropic engineering · 4 sources
Standards and specifications · 14 sources
  • AGENTS.mdOpen formatThe open format for giving coding agents project instructions.Cited in: Steering docs
  • Conventional Commits 1.0.0SpecificationThe commit message format: feat, fix, the ! marker and BREAKING CHANGE.Cited in: Commit conventions
  • Semantic Versioning 2.0.0SpecificationWhat MAJOR, MINOR and PATCH mean, which the commit-type table maps onto.Cited in: Commit conventions
  • Development ContainersOpen specificationThe specification behind devcontainer.json.Cited in: Devcontainer
  • The /llms.txt fileProposalA proposal for LLM-friendly documentation indexes.Cited in: Versioned docs
  • Model Context ProtocolOpen standardThe open standard for connecting AI applications to tools and data.Cited in: Versioned docsMemory bank
  • OWASP LLM06:2025 Excessive AgencyOWASP Gen AI Security ProjectMinimise extension permissions "to the minimum necessary"; human-in-the-loop approval for high-impact actions; implement authorization in downstream systems rather than relying on the LLM to decide. The source for the three permission tiers and for enforcing below the agent.Cited in: Permissions
  • NIST glossary: least privilegeNIST / CNSSIEach entity is granted "the minimum system resources and authorizations that the entity needs to perform its function" (SP 800-53 Rev. 5 wording).Cited in: Permissions
  • NIST SP 800-53 PL-4: Rules of Behaviorcsf.tools (secondary mirror of NIST SP 800-53)Requires organizations to document the rules of expected system usage and get a documented acknowledgment before authorizing access. The source for why a written policy is a deliverable separate from its technical enforcement. Official text: https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final.Cited in: Permissions
  • ISO/IEC 27001 Annex A 5.1: Policies for information securityiseoblue (secondary, paraphrases ISO/IEC 27001)Security policies "shall be defined, approved by management, published, communicated to and acknowledged by relevant personnel [...] and reviewed at planned intervals." A second, independent source for documenting policy regardless of automated enforcement. Official standard: https://www.iso.org/standard/27001.Cited in: Permissions
  • OWASP Agentic Skills Top 10OWASPSpecifies a permission manifest an agent skill declares up front (file, network, shell access); "declare a minimal permission manifest; request only what your skill genuinely needs"; "accurately declare risk_tier, permissions, and requires; do not understate scope." The model behind making the policy machine-checkable, not just written.Cited in: Permissions
  • OWASP Top 10 for LLM ApplicationsOWASP Gen AI Security ProjectPrompt injection is listed as the first risk.Cited in: Supply chain
  • devcontainer.json referenceDevelopment Containersmounts accepts Docker --mount syntax; ${devcontainerId} is a supported variable.Cited in: Devcontainer
  • Language Server ProtocolMicrosoftThe open protocol behind go-to-definition, find-references, hover and diagnostics, answered live by a language server.Cited in: Code graph
Practitioner writing · 13 sources
Tool and platform documentation · 67 sources

The rule: sourced, or dropped. Every claim here is one of two things, and never a third. Either it cites a named source (the vendor's own documentation for tool behavior and syntax; a standard, a research finding or a shipped implementation for anything structural), or it is labelled in the text as this guide's own proposal. A claim that can be neither gets cut rather than asserted, and a value that is an assumption rather than a measurement says so where it appears.

Still labelled proposals, with no public source: the contents of the permission tiers, the agent-ready issue rules, the four-outcome check reporting, and the starting metric alarms. The shape of the permission tiers is sourced — see Where the tiers come from.