Rules That Enforce Themselves¶
Summary¶
Turns lessons into linters, pre-commit hooks and CI checks so a fix cannot quietly come undone, and shows how professional guardrails let an agent work fast inside safe limits.
Concepts Covered¶
This chapter covers the following 18 concepts from the learning graph:
| Concept | Concept Impact Score |
|---|---|
| Automated Check | 44 |
| Enforcement Over Memory | 13 |
| Linter | 9 |
| Formatter | 4 |
| Pre-Commit Hook | 9 |
| Pre-Commit Secret Scan | 4 |
| Opt-In Hook Gap | 4 |
| CI Pipeline | 11 |
| Schema Drift Check | 4 |
| Continuous Deployment | 1 |
| GitHub Actions | 1 |
| One-Line CI Gate | 4 |
| ID Uniqueness Check | 1 |
| Lesson to Rule | 9 |
| Fix Without a Rule | 1 |
| Regression Guard | 4 |
| Reflect and Capture | 3 |
| Professional Guardrails | 3 |
Prerequisites¶
This chapter builds on concepts from:
- Chapter 1: Good Enough as an Engineering Idea
- Chapter 3: The Code Under Your App
- Chapter 4: How AI Coding Agents Work and Fail
- Chapter 5: Version Control as a Safety Net
- Chapter 6: Secrets and Configuration
- Chapter 10: Testing That Pays for Itself
- Chapter 11: Databases and Changing a Live Schema
- Chapter 14: Environments, Deploys and Rollbacks
- Chapter 15: Technical Debt and Keeping Docs True
- Chapter 16: Security as a Habit
A Sign on the Door¶
Most office buildings have a door like this one. It leads from the lobby to the loading dock, and in winter the cold comes through it if anyone leaves it open. One day somebody tapes a sheet of paper to it: "Please close the door." It works for a week. Then a delivery driver props it open with a box, and the lobby gets cold again.
The sign gets replaced with a bigger one. This one is in red and says "PLEASE CLOSE THIS DOOR!!" A month later there is a third sign underneath, laminated, with the building manager's name on it. People still leave the door open. They aren't careless. They have their arms full, or they're new, or they're thinking about something else, and the sign is just one more piece of paper on a wall full of paper.
Make the fixes stay fixed
Every fix in this book can come undone the next time an agent touches that code, and nobody notices until a member does. This chapter shows you how to make each fix hold without anyone having to remember it. By the end you'll know which checks to ask your agent for and where each one has to run.
Then a maintenance worker spends twenty minutes bolting a hydraulic closer to the top of the door. Now the door closes itself, every time, slowly enough that nobody gets their fingers caught. The signs come down a week later because nobody needs them. Nothing about the people changed. The door changed, so the rule stopped depending on anyone's memory.
This chapter is about putting closers on the doors of your app. Every chapter so far has ended with a lesson: rotate the leaked key, check access on the server, mark a failed check "not checked," test the money path. Each lesson is a sign on the door. Someone has to remember it, every time, forever, and the someone is usually an AI agent that has never read the sign. The habits in this chapter turn those lessons into checks that run by themselves and refuse a change that breaks them.
A Rule That Has to Be Remembered Is Not a Rule¶
Chapter 4 showed how a coding agent works. It reads what fits in its context window, follows its instruction file most of the time, and starts each new session knowing nothing about the last one. That makes an agent a fast builder and a poor keeper of rules. A note in the instruction file that says "never let a vendor error read as no results" is a sign on the door. The agent will usually read it. On a long task, with the context window full, it may not.
People are no better at this. A builder who fixed a bug in March won't remember the details in September, when the agent rewrites the same adapter for a new vendor.
Enforcement over memory is the principle that any rule worth keeping should be checked by a program that runs on its own and fails loudly, instead of depending on a person or an agent to remember it. A rule held only in memory, in a document or in an instruction file can be forgotten. A rule held in a check is tested on every change, by a machine that never gets tired or busy.
A quick test for any rule
Picture the agent breaking the rule on a busy afternoon, deep in a long task. If nothing would turn red, the rule is still a sign on the door.
Here is what that looks like for one of the gaps found in the dating-safety app. A search vendor's failed call was being read as "no results," so a photo that was never checked looked clean. Chapter 9 covered the fix: the adapter throws an error on a failed call, and the scan marks that check "not checked." Now picture two versions of what happens next. This is a hypothetical, built from that one fix.
| The fix alone | The fix plus a rule | |
|---|---|---|
| March | The adapter is fixed. A note goes in the instruction file. | The adapter is fixed. A test calls the adapter with the vendor returning an error and expects "not checked." |
| September | The agent writes a second image-search adapter and copies an older adapter as its starting point. The old error handling comes back. | Same new adapter, same copied code. |
| The next push | Nothing happens. | The test fails. The agent reads the failure and fixes the new adapter in minutes. |
| What members see | Some scans quietly read as clean when the vendor is down. | Nothing changes for members. |
The left column shows a fix without a rule: a bug fixed once with nothing in place to stop it from coming back. That fix will hold only as long as nobody touches that code again, and in an app built with an agent, somebody always touches it again. The bug comes back silently, because the code that brings it back looks perfectly reasonable.
The rest of this chapter is a toolbox of closers. Some run in your editor, some run when you commit, and some run on a server that nobody can skip.
Tell your agent
"Read the instruction file for this project and list every rule in it. For each rule, tell me whether any test or automated check would fail if the rule were broken. Mark each one 'enforced' or 'memory only.' Don't change anything yet."
Automated Checks¶
An automated check is a program that inspects your code or your app and passes or fails on its own, without a person looking. Chapter 10 introduced the most familiar kind, the automated test, which runs part of your app and compares what happens to what should happen. Tests are one kind of check among several. Some checks never run your app at all. They read the code as text and look for patterns, such as a password typed into a file, an empty error handler, or a debt ID that appears twice.
Every automated check has the same three parts.
- What it looks at. Your code as text, your app as it runs, your database schema, or a document such as the debt register.
- The rule it applies. "No line looks like a live API key." "Every catch block does something with the error." "No two rows in the debt register share an ID."
- What happens when it fails. A message, a blocked commit, a red mark on a pull request, or a deploy that never starts.
Checks differ most in the third part. A check that prints a warning and lets the change through is still a sign on the door. A check that blocks the change is a closer.
This table sorts the checks this chapter covers by what each one looks at and what it catches. You already know some of them from earlier chapters. The rest are defined in the sections that follow.
| Check | Looks at | Catches | Covered in |
|---|---|---|---|
| Automated test | The app as it runs | Behavior that breaks a rule, such as a score of 100 when nothing ran | Chapter 10 |
| Type check | Code as text | A value of the wrong kind passed to a function | Chapter 3 |
| Dependency audit | The list of packages | A package with a known security hole | Chapter 16 |
| Secret scan | Code and commits as text | An API key or password written into a file | Chapter 6 and below |
| Linter | Code as text | Patterns known to cause bugs | Below |
| Formatter | Code as text | Inconsistent layout that clutters a diff | Below |
| Schema drift check | Migrations and schema | A database that won't match what the code expects | Below |
| ID uniqueness check | The debt register | The same ID given to two different items | Below |
A Worked Check: No Location in the Output¶
The dating-safety app has a product rule that must never break. The app never returns a home address, a workplace or a location, even when an outside service supplies one. Chapter 8 explained why. Here is how that rule becomes a check.
The agent writes a test that builds a fake people-search response containing a street address, a city and a workplace. It runs the scan's code with that response and inspects everything the app would send back to the member. The test fails if any of those three values appear anywhere in the output. In plain words, the check says: "Feed the app a location. If the location comes out the other side, stop."
Look at what this check gives the builder. The no-locate rule used to live in the builder's head, in a design document and in a line of the instruction file. Now it also lives in a program that runs on every change. A new vendor adapter, a new results-page field or a cleanup that passes the whole vendor response through for convenience will all fail that test before a member sees anything. The builder doesn't have to remember to look, and neither does the agent.
The check is small, about twenty lines. Most good checks are. Their value comes from where they run and whether a failure can stop the change, which is what the next three sections are about.
Tell your agent
"Write one automated test for our no-locate rule. Build a fake vendor response that contains a street address, a city and a workplace, run it through the scan, and fail the test if any of those values appear in what we send back to the member. Show me the test failing on purpose first, by temporarily passing the address through, then put the code back and show it passing."
Linters and Formatters¶
A linter is a program that reads your source code without running it and flags patterns that are known to cause bugs or confusion. The name comes from a 1978 tool called lint, which picked small bits of fluff out of C programs the way a lint brush picks fluff off a sweater. For JavaScript and TypeScript apps like the dating-safety app, the common linter is ESLint. A linter comes with hundreds of built-in rules, and you can switch each one on or off in a config file. You can also write your own rules for patterns that matter to your app.
A linter reads code the way a careful reviewer does, looking for shapes that usually mean trouble. Unlike a reviewer, it reads every line of every file on every change in a few seconds.
A Worked Lint Rule: Errors That Disappear¶
The dating-safety app had about 24 bare catch blocks. A catch block is the part of the code that runs when something goes wrong. A bare one catches the error and does nothing useful with it, so the failure disappears. Chapter 12 explained why that's dangerous: a vendor failure that vanishes can turn into a clean-looking result.
Two lint rules turn that lesson into a check.
- ESLint's built-in
no-emptyrule flags any block with nothing inside it, including an empty catch block. - A short custom rule, which an agent can write in a few minutes, flags a catch block whose only action is to print the error and carry on.
Once both rules are on and set to "error," the linter fails when it finds either pattern. The first run will report all 24. The builder and the agent fix them, a few at a time, and from then on a new bare catch block can't get in. The lesson from Chapter 12 no longer depends on the agent having read Chapter 12.
A custom lint rule works for other lessons too. The dating-safety app copied model prices into ten files, which Chapter 13 fixed with one price table. A lint rule that flags a price figure written anywhere outside that table keeps the ten copies from growing back.
Some rules come ready-made. Chapter 10 warned that an agent stuck on a failing test may switch the test off with .skip and report success. The ESLint plugins for Vitest and Jest both include a rule called no-disabled-tests that flags any skipped test. Set it to "error" and a quietly disabled test fails the lint like any other problem. When a test really does need to be off for a while, the agent has to say so and turn the rule off for that one line, where you'll see it in the diff.
Formatters¶
A formatter is a program that rewrites code into one consistent layout: the same indentation, the same quote marks, the same line breaks, every time. For JavaScript and TypeScript the common one is Prettier. A linter tells you about a problem. A formatter fixes the layout itself and doesn't ask.
A formatter sounds cosmetic, but it changes what you can see when you review a change. Chapter 5 taught you to read a diff, the list of lines a change added and removed. Without a formatter, an agent that reformats a file while fixing one line produces a diff of three hundred changed lines, and the one that matters is lost among them. With a formatter that runs on every file, layout never changes by accident.
Here is the worked case. Say the agent fixes the scoring rule for "not checked" results, and it also re-indents the whole scoring file. Without a formatter, the pull request shows 212 changed lines, and the builder approves it after a quick skim. With a formatter, the file's layout was already fixed, so the agent's re-indent changes nothing, and the pull request shows four changed lines. The builder can read all four and see that the fix is correct. The formatter didn't find a bug. It made the change small enough for a person to check.
To enforce a formatter, you usually run it in check mode. Instead of rewriting files, the formatter reports whether any file is out of format, and fails if one is. That check goes in the same places as the linter.
Tell your agent
"Set up ESLint and Prettier for this project if they aren't already set up. Turn on the no-empty rule and the test plugin's no-disabled-tests rule as errors, and write a custom rule that flags any catch block whose only action is to log the error. Run the linter and give me the count of problems by rule, without fixing them yet. Then add 'lint' and 'format:check' scripts to package.json."
Pre-Commit Hooks¶
Git can run a program for you at certain moments, such as just before it saves a commit or just before it pushes to GitHub. These programs are called hooks. A pre-commit hook is a script that git runs every time you try to make a commit, and that can stop the commit if the script fails. Chapter 5 described a commit as a save point. A pre-commit hook is a check at the door of the save point. If it fails, the save doesn't happen, and you get a message saying why.
Pre-commit hooks should be fast, because they run on every commit. A good one finishes in a few seconds. Formatting the changed files, linting them and scanning them for secrets fit well. A full test run that takes five minutes usually doesn't; it belongs in CI, which comes next. Some teams add a pre-push hook as well, which runs just before code goes to GitHub and can afford to take a little longer.
The Pre-Commit Secret Scan¶
Chapter 6 covered secrets and the many ways they leak, and it introduced the secret scanner, a tool that looks for text shaped like an API key or password. The dating-safety app had three secret leaks: a live token committed to git, a whole .env file committed, and a production .env sent by email. The first two passed through a commit.
A pre-commit secret scan runs a secret scanner on the files in each commit before the commit is saved. Gitleaks is a common free choice. If the scanner finds something shaped like a Stripe live key or a cloud access token, the commit stops.
Here is how that plays out. The agent is wiring up a new SMS vendor. To test quickly, it pastes the vendor's live key straight into the adapter file, meaning to move it to an environment variable later. It runs git commit. The hook runs gitleaks, which finds a string matching the vendor's key format, and the commit is refused with the file name and line number. The agent moves the key to the .env file, which the gitignore file already keeps out of git, and commits again. The key never entered git history, so there is nothing to rotate.
Compare that with the same mistake and no hook. The key goes into a commit and then to GitHub. Chapter 6 explained what follows: rotating the key, checking the vendor's logs, and accepting that the key now sits in git history for good. The hook turns an afternoon of cleanup into a ten-second retry.
The Opt-In Hook Gap¶
Pre-commit hooks have a weakness, and the dating-safety app ran into it. Git keeps its hooks in a hidden folder inside each copy of the repository, and that folder isn't saved to GitHub. So when someone clones the repo, they get the code but none of the hooks. The usual workaround is to keep hook scripts in a normal folder that is committed, and have each person run a one-time setup command that tells git to use that folder. Tools such as Husky try to run that command automatically when packages are installed, which narrows the gap without closing it.
The dating-safety app had a pre-push hook that ran its checks before every push. It needed exactly that one-time opt-in on each clone. On any copy where someone had run the setup command, the hook ran every time. On any copy where nobody had, it was skipped without a word.
The opt-in hook gap is the gap between the checks a project's hooks are meant to run and the checks that actually run, caused by hooks that each copy of the repository has to switch on by hand. The gap is invisible from the builder's own laptop, which is the one place the hooks always work. Here are the ways a change can go around a hook:
- A fresh clone on a new laptop, before anyone runs the setup command.
- A cloud coding agent that works in its own copy of the repository.
- A contractor who clones the repo to fix one bug.
- An edit made in GitHub's web editor, where no local git runs at all.
- Anyone, person or agent, who adds
--no-verifyto a commit or push, which tells git to skip hooks.
So stop relying on hooks for enforcement. Keep the hooks, because a fast warning on your own machine saves a round trip. But run the same checks again in CI, on a server that every change must pass through, no matter where it came from. The hook becomes the early warning, and CI does the enforcing.
Don't test the hooks on your own laptop
Your laptop is the one place the hooks always run, so it will tell you they work. Try a fresh clone with no setup, or a commit with --no-verify, and see what gets through.
Before trying the diagram below, here is the setup it assumes. The repository keeps a pre-push hook that needs a one-time opt-in, and it has a CI check that runs on GitHub for every push. Main is protected, which means a change can reach it only through a pull request whose CI check has passed. One scenario shows the same repository before that protection was turned on.
Diagram: Does the Check Run?¶
Run the Does the Check Run? MicroSim Fullscreen
Does the Check Run?
Type: microsim
sim-id: opt-in-hook-gap-predictor
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: differentiate
Learning Objective: The learner will differentiate, for seven ways a change can reach a repository, whether a local pre-push hook runs and whether a CI check stops a bad change before it reaches the main branch.
Prerequisites: commit, push, main branch, pull request (Chapter 5); pre-commit hook, pre-push hook, opt-in hook gap, CI check, --no-verify (defined in the sections above and in "CI: Checks Nobody Can Skip").
Evidence of Mastery: For each of seven scenarios, the learner commits two predictions before the answer is shown: (A) does the pre-push hook run, yes or no; (B) is a change that breaks the secret scan stopped before it reaches main, yes or no. A scenario is correct when both predictions match the answer table. Mastery is 6 of 7 scenarios correct on the first attempt. Reading the scenario explanation after the reveal is exploration, not evidence.
Misconceptions: (1) A hook committed to the repository runs for everyone who clones it. (2) If the hook runs on my laptop, the check is enforced. (3) A CI check that runs is the same as a CI check that blocks a merge.
Instructional Rationale: Analyze-level differentiation needs the learner to separate two things that look alike: a check that exists and a check that is enforced. Predicting both answers for each scenario before seeing the result makes the learner trace where each change goes, rather than recall a slogan.
Content:
Shown above every scenario: "The repository has a pre-push hook that runs a secret scan. The hook works only on copies where someone has run the one-time setup command. The repository also has a CI check that runs the same secret scan on GitHub for every push."
| # | Scenario | A: Hook runs? | B: Bad change stopped before main? | Why (shown as feedback) |
|---|---|---|---|---|
| 1 | The builder pushes from her main laptop, where she ran the setup command months ago. Main is protected. | Yes | Yes | The hook was switched on here, and CI blocks the merge as well. |
| 2 | The builder pushes from a new laptop with a fresh clone. She hasn't run the setup command. Main is protected. | No | Yes | A fresh clone has no hooks until someone opts in. CI still runs on GitHub and blocks the merge. |
| 3 | A cloud coding agent works in its own copy of the repository and pushes a branch. Main is protected. | No | Yes | The agent's copy never ran the setup command. CI doesn't care where the push came from. |
| 4 | On the builder's main laptop, the agent pushes with --no-verify to save time. Main is protected. | No | Yes | --no-verify tells git to skip hooks. CI can't be skipped that way. |
| 5 | A contractor clones the repository to fix one bug and pushes a branch. Main is protected. | No | Yes | The contractor never opted in. CI catches the change at the pull request. |
| 6 | The builder edits a file in GitHub's web editor and opens a pull request. Main is protected. | No | Yes | No local git runs, so no hook runs. CI runs on GitHub. |
| 7 | The same repository before main was protected. A cloud agent pushes straight to main. | No | No | CI runs and turns red, but nothing requires it to pass, so the change is already on main. A check must be required before it can block anything. |
Provenance: The pre-push hook that needed a manual opt-in per clone is from the dating-safety app (research/seed-notes.md, Hygiene row). Scenarios 1 to 7 are illustrative and must be labeled "illustrative scenario." The behavior of hooks, fresh clones, --no-verify and GitHub's web editor is standard git and GitHub behavior.
Rules: The hook runs only when the change is pushed from a local copy where the setup command was run and --no-verify was not used. A bad change is stopped before main when main is protected by a required CI check. In scenario 7 the change is not stopped, because the check is not required. Both predictions must match for a scenario to count as correct.
Learner Activity:
- The learner reads scenario 1 and makes predictions A and B.
- The learner presses Reveal. Each prediction shows as correct or incorrect, the Why text appears, and a picture of the change's path shows whether it passed through the hook, through CI, and whether it was stopped.
- The learner moves to the next scenario. Scenarios come in the fixed order 1 to 7.
- After scenario 7, a summary shows two counts: in how many scenarios the hook ran (1 of 7) and in how many the bad change was stopped (6 of 7). The learner should notice that the hook ran in only one scenario, and that the one failure of CI came from the missing protection on main, not from CI itself.
Feedback: Seven scenarios, fixed order, one attempt each; a revealed scenario can't be re-answered. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. " followed by the Why text. A running count "Scenarios correct: n of 7" is shown.
Starting State: Scenario 1 is shown with both predictions blank. The question reads "Will the check run, and will it stop the change?"
Chapter Anchors: The dating-safety app's pre-push hook needed a one-time opt-in on each clone. Hooks can be skipped with --no-verify. The fix is to keep the hook as an early warning and enforce the same check in CI. The hook runs in 1 of 7 scenarios; the bad change is stopped in 6 of 7.
Tell your agent
"Add a pre-commit hook that runs the formatter in check mode, the linter on changed files, and gitleaks on the files being committed. Keep it under ten seconds. Show me the hook before you install it. Then list every check our hooks run today and tell me which of them also run in CI. Any check that runs only in a hook goes on a list for the next step."
CI: Checks Nobody Can Skip¶
A CI pipeline is a set of checks that run automatically on a server every time code is pushed to the shared repository, and that report pass or fail on that change. CI stands for continuous integration, an old name for the habit of merging everyone's work often and checking it each time. The important word in that definition is "server." CI doesn't run on anyone's laptop, so it doesn't depend on anyone's setup, and it runs the same way for the builder, the agent, a contractor and a cloud agent.
The dating-safety app already had CI running its unit tests and browser tests on every push. That was one of the things the agent got right. The gaps were in what CI didn't check yet: secrets, the schema, the debt register, and the hook-only checks.
GitHub Actions¶
GitHub Actions is GitHub's built-in service for running CI pipelines. You describe the pipeline in a short text file saved in the repository under .github/workflows/, and GitHub runs it on its own servers for every push and pull request. Because the file lives in the repository, it is versioned like everything else: you can see who changed the pipeline and when, and roll back a bad change. Other hosts have their own versions, such as GitLab CI, but the idea is the same.
The file below is a small but complete GitHub Actions pipeline for an app like the dating-safety app. Before reading it, here is what each part means. on says when the pipeline runs: on every push and every pull request. runs-on picks the kind of server. Each uses line pulls in a ready-made step, and each run line is a command. They run in order, and if any command fails, the pipeline stops and the change gets a red mark.
name: ci
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0 # full history, so the secret scan sees every commit
- uses: actions/setup-node@v5
with:
node-version: 24 # a current long-term-support Node release
- run: npm ci # install the exact packages in the lockfile
- run: npm run typecheck && npm audit --audit-level=high && npm run lint
- run: npm run format:check
- uses: gitleaks/gitleaks-action@v2 # scans every commit for secrets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# a repo owned by an organization also needs a free GITLEAKS_LICENSE secret
- run: npm test
You don't have to write this file
Read it once so you know what each line is for. Your agent will write yours, and you'll be able to check it against this one.
The One-Line CI Gate¶
The fourth step is one line, and it runs three checks.
A one-line CI gate is a single command in the CI pipeline that runs the type check, the dependency audit and the linter together and fails if any one of them fails. Each part was covered elsewhere. The type check (Chapter 3) catches values of the wrong kind. The dependency audit (Chapter 16) catches packages with known security holes; --audit-level=high fails only on serious ones, so the gate doesn't turn red over every minor warning. The linter, from this chapter, catches known bug patterns. The && between them means "run the next one only if this one passed."
One line is easy to add and hard to argue with. It takes an agent two minutes to put in place, it runs in under a minute on a small app, and it closes three kinds of gap at once. Most larger CI setups started with a line like this one.
Making a Red Mark Mean Stop¶
A CI pipeline that fails and reports red can still be ignored. The change can be merged anyway. To make CI a closer and not just a louder sign, turn on branch protection for the main branch in GitHub's settings and mark the CI check as required. From then on, a pull request can't be merged into main until the check passes. One more setting matters for a solo builder. By default GitHub lets a repository's admins bypass the rule, and on your own repository you are the admin, and so is an agent using your login. Turn on the option that applies the rule to admins too. This is the step that scenario 7 in the diagram above was missing.
The workflow diagram below follows a change from the agent's edit to production and shows which checks run at each step, and which steps can be skipped.
Diagram: From Edit to Production¶
Run the From Edit to Production MicroSim Fullscreen
From Edit to Production
Type: workflow
sim-id: edit-to-production-checks
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: interpret
Learning Objective: The learner will interpret a change's path from an agent's edit to production, identifying at which step each check runs, which steps can be skipped, and which step turns a failing check into a blocked change.
Prerequisites: commit, push, pull request, main branch, deploy (Chapters 5 and 14); formatter, linter, pre-commit hook, pre-commit secret scan, CI pipeline, one-line CI gate, branch protection, continuous deployment (defined in this chapter above and in the "Continuous Deployment" section).
Evidence of Mastery: After exploring, the learner answers four multiple-choice questions. An answer is correct when it matches the answer key in Content. Mastery is 4 of 4. Clicking steps to read their infoboxes is exploration, not evidence.
Misconceptions: (1) A hook in the repository protects every copy. (2) A CI check that fails stops a merge by itself. (3) The secret scan only needs to run once, in one place.
Instructional Rationale: Interpreting a process means reading what each step does and what it depends on. Clickable steps let the learner gather that information, and the four questions require them to use it to explain where enforcement actually happens.
Content:
The steps, in order, each a clickable node with this infobox text:
| # | Step | Infobox: what runs here | Infobox: can it be skipped? |
|---|---|---|---|
| 1 | Agent edits a file | The formatter may run on save, if the editor is set up for it. | Yes. It depends on each editor's settings. |
| 2 | Commit | Pre-commit hook: formatter in check mode, linter on changed files, secret scan on the files being committed. | Yes. A fresh clone without the opt-in, a cloud agent's copy, or --no-verify all skip it. |
| 3 | Push to GitHub | Pre-push hook, if one exists and was switched on. | Yes, for the same reasons as step 2. |
| 4 | Pull request opened | CI pipeline: one-line gate (type check, dependency audit, linter), format check, secret scan, tests, schema drift check, ID uniqueness check. | No. CI runs on GitHub's servers for every push and pull request. |
| 5 | Merge into main | Branch protection: the merge is allowed only if the required CI check passed. | Only by an admin, unless the setting that also holds admins to the rule is on. |
| 6 | Continuous deployment | The host deploys main automatically after the merge. | Not needed: only changes that passed step 5 get here. |
| 7 | Production | Members use the app. | (Final step.) |
Edges: 1 → 2 → 3 → 4 → 5 → 6 → 7. A labeled edge from 4 back to 1 reads "check failed: fix and push again." A labeled edge from 2 back to 1 reads "hook failed: fix and commit again."
Questions, in this order:
| # | Question | Options | Correct | Why (feedback) |
|---|---|---|---|---|
| 1 | Which step runs on every change, no matter who made it or from where? | A. Commit; B. Push to GitHub; C. Pull request opened; D. Agent edits a file | C | CI runs on GitHub's servers, so it doesn't depend on anyone's laptop setup. |
| 2 | Which step can a single command-line flag skip? | A. Commit; B. Pull request opened; C. Merge into main; D. Continuous deployment | A | --no-verify skips hooks. CI and branch protection can't be skipped with a flag. |
| 3 | Where should the secret scan run? | A. Only in the pre-commit hook; B. Only in CI; C. In both the pre-commit hook and CI; D. After deployment | C | The hook catches the key before it enters git history. CI catches anything that went around the hook. |
| 4 | What turns a failing CI check into a blocked merge? | A. The CI pipeline itself; B. Branch protection with a required check; C. The pre-push hook; D. Continuous deployment | B | A failing check only reports red. Branch protection is what refuses the merge. |
Provenance: The steps and checks are from this chapter's sections. The dating-safety app's CI ran unit and browser tests (research/seed-notes.md, "what worked"); the other checks are the chapter's recommended additions.
Rules: Steps 1 to 3 are skippable; steps 4 and 5 are not skippable by a contributor. The questions are answered in order. Each question has exactly one correct option.
Learner Activity:
- The learner clicks each of the seven steps and reads what runs there and whether it can be skipped.
- The learner notices that every step before step 4 can be skipped.
- The learner answers the four questions in order.
- After each answer, the Why text appears and the step the question is about is highlighted in the diagram.
Feedback: Four questions, fixed order, two attempts each. Correct: "Right. " followed by the Why text. Incorrect on first attempt: "Not quite. Look again at the infobox for each step." After a second wrong attempt, the correct option and Why text are shown. A count "Questions correct: n of 4" is shown.
Starting State: The seven steps are shown in order with no step selected. The prompt reads "Click each step to see what checks it. Where can a change slip past?"
Chapter Anchors: The one-line CI gate runs the type check, the dependency audit and the linter. Branch protection with a required check is what blocks a merge. The dating-safety app's CI already ran unit and browser tests.
The Schema Drift Check¶
Chapter 11 described a gap in the dating-safety app's database setup. There were two competing ways of changing the schema: a set of migration files, and SQL that ran when the server started up. On top of that, an early return in the migration code meant that later migrations were quietly skipped. Production could end up with a database that didn't match what the code expected, and nothing would say so until a query failed.
Chapter 11 fixed the cause by choosing one migration path. A schema drift check keeps it fixed. It is a CI step that builds a database from scratch using the project's one migration path, then compares the result with the schema the code expects, and fails if they differ. "Drift" is the slow, silent separation between two things that are supposed to match.
Here is how the check works for an app on Postgres and Drizzle. CI starts an empty, throwaway Postgres database. It runs every migration in order, exactly as production would. Then it compares that database with the schema written in the code, using Drizzle's own tools or a short script. If the comparison finds a single table, column or index that one side has and the other lacks, the check fails and names the difference. On the old code, the early return would have left the later tables missing, and the check would have failed on its first run. On the fixed code it passes. If anyone later adds a column to the schema and forgets the migration, or adds SQL to the startup code, it fails again.
The ID Uniqueness Check¶
Chapter 15 introduced the debt register, a list of known shortcuts and gaps, each with its own ID so that commits, tests and notes can point to it. In the dating-safety app, one debt ID was used for two different items. Every reference to that ID became ambiguous: a commit that said it fixed the item might have fixed either one.
An ID uniqueness check is a small CI script that reads every ID defined in a list such as the debt register and fails if any ID appears as the definition of more than one item. It takes a few lines of code. It pulls out the ID at the start of each row, counts them, and prints any that appear twice. The same check works for any list where IDs must be unique, such as product rules or runbook steps. It is a good example of a check that has nothing to do with running the app. It keeps a document consistent with itself, which matters because agents read those documents and act on them.
Continuous Deployment¶
Continuous deployment is the practice of deploying every change automatically as soon as it is merged into main and passes CI, with no manual deploy step. Chapter 14 covered deploys, staging and rollbacks. Continuous deployment ties them to this chapter: if the only way into production is through main, and the only way into main is through a required CI check, then every check in CI now guards production too.
That is also its risk. Continuous deployment is only as safe as the gate in front of it. With a thin CI pipeline, it sends untested changes to members faster. With the checks in this chapter in place, along with the staging environment and committed deploy config from Chapter 14, it removes a manual step that people tend to rush or skip.
Tell your agent
"Create a GitHub Actions workflow in .github/workflows/ci.yml that runs on every push and pull request. Include one line that runs the type check, npm audit at the high level, and the linter. Add the format check, a gitleaks scan of the full history, our tests, a schema drift check that runs every migration on an empty Postgres and compares it with the Drizzle schema, and a script that fails if any debt register ID is defined twice. Show me the file before you commit it. If a step fails on today's code, tell me what fails instead of switching the step off. Then tell me the exact steps to make this check required for merging into main, with admins held to it too. I'll change the GitHub setting myself."
From Lesson to Rule¶
Every chapter of this book has found gaps in the dating-safety app and named the fix. Lesson to rule is the habit of turning each lesson learned from a bug, an incident or a review into an automated check, in the same piece of work as the fix, so the lesson is enforced from then on. It is the habit that keeps the fixes from Chapters 5 to 16 from coming undone.
It takes five steps.
- Find the root cause. Chapter 10 showed how. The rule has to guard the cause, not the symptom.
- Ask what cheapest check would have failed. A test, a lint rule, a CI script or a hook. Pick the one that runs earliest and costs least while still being impossible to skip.
- Write the check and watch it fail on the old code. This is Chapter 10's failing-test-first rule: a check that has never failed may not be checking anything.
- Apply the fix and watch the check pass.
- Commit the fix and the check together, with a message that names the lesson.
Regression Guards¶
A regression guard is any automated check that exists to stop one specific, already-fixed bug from coming back. Chapter 10 introduced the regression test, which is one kind. A regression guard can also be a lint rule, a CI script or a hook. What makes it a guard is its job: it is pinned to a bug that already happened once.
The dating-safety app's scheduler bug shows the five steps in a few lines. Chapter 11 walks through the bug itself: one send used <= where it needed = and marked many rows as sent.
- Root cause: a comparison that matched every ID up to the target instead of the target alone.
- Cheapest check: a test with three unsent rows that sends the middle one and checks that exactly one row is marked sent. On the old code, two rows are marked, and the test fails. With
=, it passes. - Commit: "Fix scheduler marking many rows sent; add regression guard."
This guard costs about fifteen lines. If a future rewrite gets that comparison wrong again, the guard fails before the change reaches main, and the message names the bug it protects against.
The diagram below gives you twelve lessons from this book and asks you to pick the cheapest check that enforces each one.
Diagram: Which Check Keeps the Lesson?¶
Run the Which Check Keeps the Lesson? MicroSim Fullscreen
Which Check Keeps the Lesson?
Type: microsim
sim-id: lesson-to-rule-sorter
Library: p5.js
Status: Specified
Bloom Level: Evaluate
Bloom Verb: recommend
Learning Objective: The learner will recommend, for each of twelve lessons from the dating-safety app, the cheapest kind of automated check that would enforce it, or recognize that it can only be kept in the instruction file.
Prerequisites: automated check, automated test, regression guard, linter, formatter, pre-commit secret scan, CI pipeline, schema drift check, ID uniqueness check, project instruction file (Chapter 4 and the sections above).
Evidence of Mastery: The learner assigns each of twelve lessons to one of six check types. An assignment is correct when it is in the "Accepted" column for that lesson. Mastery is 10 of 12 correct on the first attempt. Reading the lesson's chapter link is exploration, not evidence.
Misconceptions: (1) Every lesson needs a test. (2) A line in the instruction file is as strong as a check. (3) Some lessons are too small or too odd to enforce, such as a duplicate ID in a document.
Instructional Rationale: Evaluate-level recommendation needs the learner to weigh options against a criterion, here "cheapest check that can't be skipped." Each lesson has a plausible wrong answer, so the learner must judge what the check needs to look at (code as text, running behavior, schema, a document) before choosing.
Content:
The six check types the learner chooses from: Formatter; Linter rule; Secret scan (pre-commit and CI); CI check script; Automated test (regression guard); Instruction file only.
| # | Lesson shown to the learner | Accepted | Why (shown as feedback) |
|---|---|---|---|
| 1 | A live API token was committed to git. | Secret scan (pre-commit and CI) | The scanner finds key-shaped text before the commit is saved, and again in CI for anything that went around the hook. |
| 2 | About 24 catch blocks swallowed errors with no handling. | Linter rule | A linter reads code as text and can flag empty catch blocks and ones that only log. |
| 3 | A scheduler used <= instead of = on IDs, so one send marked many rows sent. | Automated test (regression guard) | Only running the code shows how many rows get marked; a test checks exactly one. |
| 4 | Two migration mechanisms disagreed, and an early return skipped later migrations. | CI check script | A schema drift check builds the database from migrations and compares it with the code's schema. |
| 5 | One debt ID was used for two different items. | CI check script | An ID uniqueness check reads the register and fails on any repeated ID. |
| 6 | Model prices were copied into ten files. | Linter rule; CI check script | Either a custom lint rule or a CI script can flag a price figure written outside the one price table. |
| 7 | The app must never return an address, workplace or location. | Automated test (regression guard) | The rule is about output, so a test feeds in a location and checks it never comes out. |
| 8 | A failed vendor search was read as "no results." | Automated test (regression guard) | A test makes the vendor fail and expects "not checked," which requires running the adapter. |
| 9 | The error screen showed stack traces to members. | Automated test (regression guard) | A test triggers an error in production mode and checks the page holds no stack trace. |
| 10 | Dev-only plugins were shipped to members. | CI check script | CI builds the production bundle and fails if any dev-only plugin is in it. |
| 11 | Pull requests were full of layout-only changes that hid the meaningful ones. | Formatter | A formatter in check mode keeps layout fixed, so diffs show only changes in meaning. |
| 12 | Ask the builder before adding a new paid outside service. | Instruction file only | Whether a new vendor is worth its cost is a judgment call no program can make. The instruction file is the right home. |
Provenance: Lessons 1 to 10 are from the dating-safety app's gaps in research/seed-notes.md (Secrets, Errors, Correctness, Schema, Docs, Cost, product rules, Vendors, Hygiene rows). The count of about 24 catch blocks and ten price files are from the same file. Lessons 11 and 12 are illustrative and must be labeled "illustrative."
Rules: Each lesson is correct when the chosen check type is in its Accepted list. Lesson 6 accepts two answers. Choosing "Instruction file only" for lessons 1 to 11 is incorrect; the feedback adds "This one can be checked by a program, so memory alone isn't enough."
Learner Activity:
- The learner sees lesson 1 and the six check types.
- The learner picks one check type and presses Check.
- The sim marks the choice correct or incorrect and shows the Why text. On an incorrect first choice, the learner may pick once more.
- The learner moves to the next lesson. Lessons come in the fixed order 1 to 12.
- After lesson 12, a summary shows how many lessons ended in each check type. The learner should notice that only one of twelve lessons had to stay in the instruction file.
Feedback: Twelve lessons, fixed order, two attempts each; a lesson can't be re-answered after its second attempt. First-attempt correctness counts toward mastery. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. " followed by the Why text. After a second wrong attempt, the accepted answer is shown. A running count "Correct on first try: n of 12" is shown.
Starting State: Lesson 1 is shown with no check type selected. The prompt reads "What is the cheapest check that would keep this lesson from coming undone?"
Chapter Anchors: About 24 bare catch blocks; model prices copied into ten files; one debt ID used twice; the scheduler used <= instead of =. Only one of the twelve lessons stays in the instruction file.
Tell your agent
"From now on, whenever you fix a bug in this project, do these steps in the same piece of work: name the root cause, write the cheapest automated check that would have caught it, show me that check failing on the old code, apply the fix, show it passing, and commit both together. Add this rule to our instruction file. Then go back through the last month of commits that say 'fix' and list any fix that has no check guarding it."
Reflect and Capture¶
Some lessons can't become checks. "Ask before adding a paid vendor" is one. "The founder decides anything about what members see" is another. And even a lesson that does become a check needs its reason written down somewhere, or the next agent may delete the check as clutter.
Reflect and capture is the habit of pausing at the end of each piece of work, listing what was learned, and recording each lesson in every place it belongs: a check if a program can enforce it, the project instruction file if it is a working rule for the agent, the docs or the debt register if it is a fact about the app, and the agent's memory only as a pointer to one of those. Chapter 4 covered project instruction files such as CLAUDE.md and AGENTS.md, and agent memory.
An event triggers it, not a clock. Good moments are when a pull request merges, when a bug's root cause is found, when you correct the agent's judgment, and before you end a long session. Take the scheduler fix as an example. The agent adds the regression guard, which is a check. It adds a line to the instruction file saying "Compare IDs with = when selecting a single row; see the scheduler guard test," which is a working rule that points at the check. And it closes the item in the debt register, which records a fact. Agent memory is the weakest of these places, because it lives on one machine and the builder can't easily see or search it, so it should never be a lesson's only home.
Tell your agent
"Before we finish today, list everything we learned in this session: bugs found, root causes, rules you were corrected on, and surprises. For each one, say where it belongs: a check, the instruction file, the docs or debt register. Show me that list, make the changes I agree to, and show me any lesson that has no check and explain why a program can't enforce it."
Professional Guardrails¶
Businesses have let non-engineers build their own software for decades. The finance analyst with a spreadsheet that runs the quarterly forecast and the operations lead with a database app that tracks shipments are both examples. The usual name is citizen development. It has a long record of working well in some companies and turning into a mess in others.
Again and again, what decided it was whether professionals built the boundaries. Where an IT team set up shared data sources, access rules, backups and a review step for anything touching money, citizen developers moved fast and safely inside those limits. Where nobody did, the same people built the same tools, and the company ended up with sensitive data in personal files and critical processes nobody could fix.
Building with an AI agent is citizen development with a much faster engine. Professional guardrails are the enforced limits, set up with an engineer's knowledge, inside which a builder and an agent can move fast without being able to break the must-be-right parts. Most of them are in this chapter, and the list is short:
- The project instruction file, for the rules a program can't check.
- A formatter, so every diff can be read.
- A pre-commit secret scan, as the early warning.
- The same checks in CI, to close the opt-in hook gap.
- A one-line CI gate for types, dependencies and lint.
- A schema drift check.
- A regression guard for every bug that has been fixed.
- Branch protection, so that a failing check means stop.
Here is how guardrails change the agent's work. Without them, every change is a small gamble, and the builder must read every diff to stay safe, which defeats the speed. With them, the agent can try something, run the checks, see what failed and fix it, often before the builder looks. Chapter 1 described Gary Klein's finding that judgment grows only where feedback is fast and clear. Guardrails give the agent and the builder that feedback in minutes, on every change. Setting them up is a day of work for an experienced engineer, and Chapter 18 covers how to ask one for it.
Tell your agent
"Audit this project against this list of guardrails: instruction file, formatter, pre-commit secret scan, the same checks in CI, a one-line gate for types, audit and lint, a schema drift check, a regression guard for each fixed bug, and branch protection on main. Make a table with each guardrail, whether it exists, whether it can be skipped, and the smallest change that would put it in place. Don't change any settings on GitHub. List those for me to do."
Back to the Door¶
The closer on the loading-dock door didn't make anyone more careful. The delivery driver still comes through with a box in both arms, and the new hire still doesn't know about the cold. The door closes anyway.
A lesson in your app holds the same way once it has a check: a test, a lint rule, a hook, a CI step, and a branch setting that makes a red mark mean stop. Chapter 18 asks how ready the app is for real users. That question is much easier to answer about an app whose rules enforce themselves.
Closers on the doors
Every fix from the earlier chapters can now have a check that holds it in place, whoever touches the code next. Good enough for now, and you know why.
Key Takeaways¶
- Enforcement over memory: a rule that has to be remembered will be forgotten, by a person or an agent. A fix without a rule comes back the next time someone touches that code.
- Keep fast checks (linter, formatter, pre-commit secret scan) in hooks as an early warning. Because of the opt-in hook gap, enforce the same checks in a CI pipeline, and use branch protection so a failing check blocks the merge.
- Start CI with the one-line CI gate, then add a schema drift check and an ID uniqueness check. Continuous deployment is only as safe as that gate.
- Lesson to rule: commit each fix with a regression guard that fails on the old code.
- Reflect and capture puts each lesson in every place it belongs, checks first and agent memory last.
- Professional guardrails let a builder and an agent move fast without breaking the must-be-right parts.