← Agentic engineering

Module 4 · Guardrails

Stop each repeated agent mistake from coming back: a short rule file, a check whose error tells the agent the fix, a required check nobody can skip, a set of golden tasks you rerun when the model or the rules change, and limits on what an agent in CI can reach.

Facts checked

By the end of this module you can take a mistake an agent has made twice and set things up so that a third attempt is stopped by a machine, with nobody watching. You can also say which guardrail a given mistake calls for, and which ones your team should delete.

Mitchell Hashimoto described the working habit on 5 February 2026: "anytime you find an agent makes a mistake, you take the time to engineer a solution such that the agent never makes that mistake again." The solution he means is a change to the setup. Telling the agent again, more firmly, lasts until the session ends.

Most of this module is about where in the setup a rule should live, because some places stop a mistake far more reliably than others. The agent can ignore a line in a rule file, but a failing check at a gate stops the change.

Before you read
1.

For the third time, an agent has done price arithmetic in floating-point in a quote service that must be exact to the cent. What is the best response?

2.

In your own words: what is the difference between a rule in the rule file and a check?

3.

A pre-commit hook that runs the tests fails. The agent proposes committing with --no-verify to get past it. What do you say?

Every repeated mistake moves up the ladder

Picture a team whose quote service returns a line item of $19.99 as 1998.9999999999998 cents. The agent multiplied dollars by 100 in JavaScript, whose Number type is a double-precision binary floating-point value, and binary floating-point cannot hold most decimal fractions exactly. The team has told the agent this twice, in two sessions. Each session began with no memory of the last.

The ladder has four rungs. A rule said in the chat is gone when the session ends. A rule in the project's rule file is read at the start of every session. A check written as code catches the mistake whether or not the rule was read. A gate runs that check at a fixed moment and stops the change when it fails. Each rung costs a little more to build than the one before, and lets the mistake through much less often.

One team found out how much more reliable a check is than a rule file. After an incident it wrote the lesson down where its agents would read it, and the note described the mechanism accurately. The same bug came back anyway. A check stops the change whether or not the note was read.

So each time you find something wrong in agent work, ask which rung it belongs on and put it there before you ask for the next change. Separate from the ladder are limits on what the agent may touch at all, which Security of the code and the agent covers.

flowchart LR
  M[Mistake seen twice] --> R[Rule file: read every session]
  R --> C[Check: test, type, lint with a fix message]
  C --> G[Gate: hook, then required check before merge]
  G --> E[Golden tasks: rerun on model or rule change]

The rule file: which file, and how short

Each tool reads project instructions from a file at the start of a session. As of December 2026, from each tool's own documentation:

ToolReadsWorth knowing
Claude CodeCLAUDE.md, .claude/CLAUDE.md, CLAUDE.local.md, and files in .claude/rules/Reads AGENTS.md by default only when there is no CLAUDE.md in the working directory or above it. The docs say to "target under 200 lines" per file.
CodexAGENTS.md, from the project root down to the working directory; an AGENTS.override.md in a directory wins over the AGENTS.md beside itStops adding files once the combined size reaches 32 KiB, by default.
Cursor.mdc files in .cursor/rules, and AGENTS.mdCursor's site now carries the banner "Cursor is now Grok Build" and its docs have moved to the Grok Build name. Its terminal reads .md files in .grok/rules/ and ignores .mdc, so AGENTS.md is the one file both surfaces read. The docs say to keep rules under 500 lines.
GitHub Copilot.github/copilot-instructions.md, NAME.instructions.md files under .github/instructions, and the nearest AGENTS.mdAlso accepts a single CLAUDE.md or GEMINI.md in the repository root.

All four read AGENTS.md, so a team on mixed tools can keep one file. Check the table against the docs before you rely on it, because tools add and rename these files.

Three kinds of line belong in the file. How to run the checks: the exact commands, and the sentence "run these before you say you are done". What never to do, with each line added because of a mistake you have seen. And the invariants the code cannot show, such as "money is integer cents". Every line should be something the agent could be caught breaking. You cannot catch an agent breaking "Write clean code", but you can catch it breaking "No floating-point arithmetic under src/pricing/".

Keep it short, and expect to cut. The Thoughtworks Technology Radar of November 2026 lists agent instruction bloat under Caution: each new rule looks useful alone, and the pile ends up contradicting itself and going stale. A preprint by Gloaguen and colleagues, first posted in February 2026 and revised that September, measured it. Across several agents and models, context files did "not generally improve task success rates, while increasing inference cost by over 20% on average". The agents did follow the instructions. What failed to help was the repository overview, and what did help was a note of non-standard practices. OpenAI's Codex team came to a similar answer through its own work and reported on 11 February 2026 that it keeps AGENTS.md to roughly 100 lines: "a map, not a 1,000-page instruction manual".

Expect to prune the file regularly. One team's rule file fell from 4,248 words to 2,238 over four months of it.

Checks whose errors tell the agent the fix

A check reads the result and says pass or fail without a person. Birgitta Böckeler's April 2026 article on martinfowler.com names the two halves: guides steer the agent before it acts, and sensors observe after it acts and help it correct itself. A rule file is a guide. Tests, type checks and lints are sensors.

You already have tests. The next cheapest check is a type: if money has its own type, Cents, then a bare number where cents belong is rejected before the code runs. A lint can be a script of a dozen lines that fails when parseFloat(, toFixed( or a number with a decimal point appears under src/pricing/.

The agent reads the error, so write the error for the agent. Böckeler's article recommends "custom linter messages that include instructions for the self-correction". OpenAI's team does the same: "Because the lints are custom, we write the error messages to inject remediation instructions into agent context." Compare two messages for one failure:

check-money: forbidden pattern in src/pricing/surcharge.ts:14
check-money: src/pricing/surcharge.ts:14 multiplies money by a floating-point rate.
Money is integer cents. Use applyRate(cents, rate) from src/pricing/cents.ts,
which rounds half up. Do not edit this check or the tests under test/pricing/.

With the first message the agent has to guess what is wrong. The second gives it the rule at the moment it breaks it, in words it can act on.

Before you trust a check, watch it fail: put a violation in by hand and run it. Then order your checks by speed and run the fast ones most often. Stripe reported on 9 February 2026 that its agents get selected lints on every push in under five seconds, with more than three million tests behind that in CI.

Gates: hooks, and required checks before merge

A check that runs only when someone remembers to run it will sometimes be missed. A gate is a fixed moment at which the check runs and a failure stops the change.

The local gate is a hook. Git runs a pre-commit hook before every commit, and the agent tools have hooks around the agent's own actions: Claude Code's documentation says that to block an action "regardless of what Claude decides" you use a PreToolUse hook, Codex has a hook of the same name that can deny a tool call, and Cursor's hooks can block an action too. Local gates give fast feedback. They can be bypassed, because git commit --no-verify exists and its documentation is one line: "Bypass the pre-commit and commit-msg hooks." One team found that every commit in a long unattended run had been made that way.

The gate to rely on is on the server. On GitHub it is a required status check: once enabled, "all required status checks must pass before collaborators can merge changes into the protected branch". To be protected by it, get two details right. Turn on "Do not allow bypassing the above settings", because by default the rule does not apply to people with admin permissions. And require a job that cannot quietly skip, because a job skipped by a conditional reports success.

Tell the agent about the gate in the rule file: which checks are required, and that a failing check is fixed at its cause. An agent that knows the server will refuse the merge stops spending effort on getting past the local hook.

Re-test when the model or the rules change

Your agent setup is software too, so write tests for it. A new model version, a pruned rule file or a new hook each change how the agent behaves in your repository, and a benchmark on someone else's code will not tell you how.

Keep a fixed set of golden tasks: five to ten real changes from your own history, each with a brief, a starting commit and a way to score the result (the tests that must pass, the files that must not change, the check that must fire). Include the mistakes your guardrails exist to stop, so that one task is "add a surcharge" and passing it means the floating-point attempt was caught. Rerun the set whenever the model or the rules change, and record pass or fail, the number of correction rounds, and the cost.

The set tells you two things. It shows when a change made things worse. It also shows which rules the new model no longer needs, and those can go. The Radar entry on instruction bloat calls this "progression testing, rather than regression testing", and cites Anthropic removing over 80% of Claude Code's system prompt for its latest models "with no measurable loss".

Keep earlier fixes from being undone

An agent starts every session knowing nothing of the last one, so it cannot follow a decision that is only in someone's memory. One team's record names an earlier fix reverted by a later change as its most expensive failure mode.

Two habits prevent most of this. Keep a decisions file in the repository, one dated line per ruling with its reason, and have the rule file tell the agent to read it and to read a file's history before editing. And ship every fix with the test that fails without it. The note tells a reader why the code looks odd, and the test fails if a change removes the fix.

Some rules will conflict. "The newest instruction wins" and "never reverse a recorded decision" are both reasonable, and an agent holding both will pick one. Claude Code's documentation says as much: when two instructions contradict each other, the agent "may pick one arbitrarily". Write down which rule wins, in the same file.

Agents in CI

Agents now run in the pipeline as well as on the laptop. Three uses are common, and each needs a limit.

Fixing a failing check, under a cap. When CI fails on an agent's change, the failure can go straight back to the agent. Cap the rounds. Stripe's rule is "often one, at most two, CI runs", on the reasoning that each run costs tokens and compute time, and that further rounds return less. Claude Ship's PR Steward, in beta since 23 November 2026, does this work on a pull request. Its documentation states no limit on rounds, so set your own, and treat a change that fails twice as one for a person.

Running on a schedule. Claude Code's scheduled tasks can start a cloud session on a timer, on an API call or on a GitHub event. OpenAI's Codex team runs a recurring agent that looks for documentation that no longer matches the code and opens pull requests to fix it. Give a scheduled agent a narrow job, a cap on what it can spend, and an owner who reads what it opened. Many agents and what they cost covers what happens without those.

Reading what strangers wrote. An agent that triages issues or reviews pull requests from forks is reading text anyone can write. In December 2025 the Cline project added an issue-triage workflow that put each new issue's title into the agent's prompt and allowed the agent a shell. Adnan Khan's write-up of 9 February 2026 shows the result: an instruction planted in an issue title could run commands in the workflow, poison the build cache it shared with the nightly release jobs, and reach the publishing tokens. Someone else used his proof of concept to publish an unauthorised version of the Cline CLI to npm. The project removed the workflow about thirty minutes after disclosure.

The rule from that incident: an agent that reads untrusted text gets no shell, no write token and no secrets, and shares no cache with a job that has them. Security of the code and the agent goes further into it.

Stop the floating-point money mistake for good

The quote service, third occurrence. Predict what you would put on each rung before reading it.

  1. 1 · Name the mistake precisely

    "The agent gets money wrong" cannot be checked. This can: "Prices are multiplied and added as floating-point numbers. $19.99 becomes 1998.9999999999998 cents, and a surcharge of half a cent rounds the wrong way." State the mistake this precisely before you write the rule.

  2. 2 · Rule file: four sentences under a Money heading

    "Money is integer cents, everywhere. Never floating-point. A quote of $12.50 is stored as 1250. formatMoney is the only place cents become dollars." Each sentence could be broken, so each can be checked.

  3. 3 · Check: a test, and a lint whose message carries the fix

    The test: three items at $0.10 with a 12.5% surcharge total exactly 34 cents (33.75 rounded half up, the firm's rule). The lint: a script that fails when parseFloat(, toFixed( or a number with a decimal point, such as 1.08, appears under src/pricing/ (rates are whole basis points, so 8% is 800), with a message that names applyRate in src/pricing/cents.ts as the replacement. Ask the agent to write both. Then put a parseFloat into a pricing file yourself and run the lint. It fails, with the message. Take it out again.

  4. 4 · Gate: a hook locally, a required check on the server

    A pre-commit hook runs the lint and the tests. The CI workflow runs the same two commands in one job with no conditional on it, and the branch rule makes that job a required status check that administrators cannot bypass. The rule file gets one more line: these checks are required, and a failure is fixed at its cause.

  5. 5 · Prove it with a re-run

    Ask for a new change in the same area: "Add a peak-season surcharge of 8% to the quote." The agent writes total * 1.08 and tries to commit. The hook fails with the lint's message. The agent reads it, rewrites the surcharge as total + applyRate(total, 800), and the commit goes through. The mistake was attempted and stopped with nobody watching, which is the evidence that the guardrail works.

  6. 6 · Make it a golden task

    Save that request as a golden task: the brief, the starting commit, and the score (lint fires on the first attempt or the attempt is never made; tests pass; no file under test/pricing/ changes). When the team moves to a new model next quarter, the task is rerun. If the new model never reaches for floating-point, the rule file line is a candidate to delete. The lint stays either way, since it costs nothing to keep.

Try it

Fill the gaps in this rule file for the quote service. Every gap is a rule the agent has already broken once, or the name of the gate that now enforces it.

# Rules for agents in this repository

## Before you say you are done
- Run `node --test` and `node scripts/check-money.js`. Both must pass.
- Never commit with ______. If a hook fails, fix the cause.
- Both commands are ______ status checks on the main branch. A change cannot merge past them.

## Money
- Money is stored and calculated as ______ cents, never floating-point.
- A quote total of $12.50 is stored as ______.
- `formatMoney` is the only place cents become dollars.

## Tests
- Never modify or delete an existing test to make a change pass.
- If a test looks wrong, ______ instead.

## Decisions
- Read `docs/decisions.md` and the file's history before editing a file.
- If two rules here conflict, the recorded ______ wins over a newer instruction in chat.
The misconception

A thorough rule file is enough. If the rule is written down, the agent will follow it.

Why it’s wrong

Claude Code's documentation describes its rule files as "context, not enforced configuration". The agent follows a rule with no check behind it most of the time, and you may only hear about the other times from a customer. The team in this module had its rule written down, accurately, when the bug came back.

A thorough rule file is also the wrong aim. Each added rule looks useful alone, and together they leave the agent less attention for the task. The preprint cited above found the extra context raised cost by over 20% without raising success in general.

The correct model

Write the rule, then the check, then the gate, and keep the rule file short enough to be read. The file tells the agent what you want. The check catches the mistake when the file was not enough, and its message tells the agent the fix. The required check makes sure nothing merges without it. A rule no machine can check still goes in the file, marked as something a person confirms at review, so you know which rules a check enforces and which you enforce.

Check yourself
  • What are the four rungs of the ladder, and how reliably does each stop a mistake?

  • Which single file does every tool in this module's table read, and what is the catch with Claude Code?

  • What makes a lint message useful to an agent?

  • Why is a pre-commit hook not enough, and what should you rely on instead?

  • What are golden tasks, and when do you rerun them?

  • What must an agent that reads issue or pull-request text from strangers never have?

Before the check

You can now deal with a repeated mistake so that it stays fixed: a line in a short rule file, a check whose error names the fix, a required check on the server, and a golden task that tells you whether you still need the guardrail when the model changes. You also know what to refuse an agent in CI.

Check yourself, without scrolling up:

  • Which file does your agent read in this repository, and how many lines is it today?
  • Name one line in it that no machine checks. Could one?
  • Is any check on your main branch required, and can an administrator merge past it?
  • If your team changed model tomorrow, what would you rerun to find out what changed?
  • Does any workflow in your pipeline hand a shell to an agent that reads issue or pull-request text?
Sources
1 lab

Labs

Lab 1

Practise this: Stop a repeated mistake with a check

Clone the starter linked below. It is the pricing code of a camping-gear shop's quote service, in Node, with nothing to install. Money is meant to be integer cents and rates whole basis points, with applyRate in src/pricing/cents.js doing the rounding. Read INCIDENTS.md first: twice an agent has handled money as floating-point numbers, twice someone told it not to in the chat, and the second one is still in src/pricing/card-fee.js. The next change on the list is a weekend delivery surcharge. Your job is to make sure there is no third time, by moving the mistake up the ladder.

  1. The rule file. Add a ## Money section to AGENTS.md (the file every agent here reads; CLAUDE.md imports it). Say that money is integer cents and never floating-point, that rates are applied with applyRate, and that node scripts/check-money.js must pass.

  2. The check. Write scripts/check-money.js. It exports checkSource(file, text), which returns a list of findings, each { file, line, message }, for pricing code that uses parseFloat(, toFixed( or a number with a decimal point. Each message names the file and line and tells the agent the fix: use applyRate from src/pricing/cents.js. Run as node scripts/check-money.js [folder], it checks every .js file under the folder (src/pricing when none is given), prints each finding, and exits 1 if there are any and 0 if there are none. Importing the file must not run the check. Watch it fail before you trust it: put a violation in by hand, run it, read the message, take it out. And make sure it raises no false alarm on pricing code that is already integer cents.

  3. Fix the card fee. 1.4% is 140 basis points. Put a test on an amount where half a cent decides the answer (a $17.50 quote has a fee of 25 cents).

  4. The gates. Add .githooks/pre-commit running the check and node --test (make it executable with chmod +x .githooks/pre-commit, then turn it on with git config core.hooksPath .githooks; git silently skips a hook that is not executable). In .github/workflows/checks.yml, the checks job must run both commands, and nothing may let it skip: the starter's job has an if: that skips agent branches, and a skipped job reports success. On a hosted repository you would then make checks a required status check on main, with bypassing turned off for administrators. The hidden tests cannot check that setting, but write it into the Money section so the agent knows.

  5. The re-run. Ask for the next change: a weekend delivery surcharge of 2.5% of the goods, added before GST, returned as weekendCents on the quote (0 when not asked for) when the quote's options include weekendDelivery: true. If an agent does it, give it the request as written and see whether it reaches for floating point. If you do it by hand, write the floating-point version first. Either way, let the hook or the check stop it, then finish it with applyRate, with a test. Record it in RERUN.md: the request, the first attempt, the command you ran and the check's message exactly as printed, and the change that passed.

Get node scripts/check-money.js and node --test both passing on what you upload, with the output in front of you. Then upload the repository folder. The .git folder is left out for you, so the hidden tests mark what is in your files: fees and quotes on amounts where floating point is a cent out, your check run on code it has never seen (with faults and without), the workflow, the hook, the rule file, your tests and RERUN.md.

Open the lab · needs a free Tarmac account to have your work marked