Software 3.0 and Agentic Engineering / Module 07

Module 7: Teaching the Agent Your Project

Teach a coding agent your project's rules with AGENTS.md, CLAUDE.md and skills, and enforce the ones that must hold with hooks and permission rules.

Maya opened Nina’s pull request for a route that returned a show’s seat count. Its handler ran SQL directly against the database, the third agent-written route that month to do it. Each time, Nina had typed the team’s rule into Claude Code, and the next session didn’t know it.

“Doesn’t the robot remember what you told it?” Leo asked.

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

In Module 6, the team’s decisions lived in prompts and plans, and every new session started without them. This module teaches the files and settings that reach every session. Instruction files and skills tell the agent your rules, and hooks and permission rules let Claude Code enforce them whatever the model decides. You’ll use all four to make the TinyTickets layer rule hold.

After this module, you can:

  • write a short AGENTS.md that holds only what the agent can’t learn from the code, and check that Claude Code loaded it
  • package a team procedure as a skill, and say what it costs in the context window before and after it’s used
  • tell a rule the model may skip from a rule Claude Code enforces, and pick an instruction file, a skill, a hook or a permission rule for each
  • write a PostToolUse hook, with the right exit code, and allow, ask and deny rules that keep the layer rule

A rule that lives only in chat

Start with the code the agent sees. The TinyTickets sample repo has a rule that every developer on the team knows. Route handlers never touch data; they call a function in src/repositories/. Here is a route that follows it, src/routes/shows.ts:

import express from "express";
import { listShows } from "../repositories/show-repository.ts";

export const showsRouter = express.Router();

showsRouter.get("/shows", (_req, res) => {
  res.json(listShows());
});

The team has started to move to PostgreSQL, and one older route was written before the rule. This is src/routes/reports.ts:

// Written before the team's layer rule. Needs DATABASE_URL.
import express from "express";
import { pool } from "../db.ts";

export const reportsRouter = express.Router();

reportsRouter.get("/reports/sales", async (_req, res) => {
  if (!pool) {
    res.status(503).json({ error: "reports need DATABASE_URL" });
    return;
  }
  const result = await pool.query(
    "SELECT show_id, count(*) AS tickets FROM tickets GROUP BY show_id",
  );
  res.json(result.rows);
});

pool comes from src/db.ts, a PostgreSQL connection pool that exists only when the DATABASE_URL environment variable is set. The route runs its own SQL. Figure 1 puts the two patterns side by side.

tinytickets-mini/module-07/src/
  routes/
    shows.ts    --> repositories/show-repository.ts --> [[store.ts]]
    orders.ts   --> repositories/show-repository.ts, sales/pricing.ts
    reports.ts  --> db.ts --> [[PostgreSQL]]     (runs SQL itself, older code)

Figure 1: two patterns in one repo, and nothing in the repo says which one new code should copy.

Pause and predict. A fresh Claude Code session gets this prompt: “Add GET /shows/:id/seats that returns a show’s seat count from the database.” Which file will it copy, shows.ts or reports.ts?

Answer

You can’t tell, and neither can the agent. Both patterns are in the code. reports.ts is the only route that reads from PostgreSQL, and the prompt says “from the database”, so it’s the closest example. Nina’s three sessions copied it.

The rule that decides is in Maya’s head and in old chats. The agent can’t read either.

Why did Nina’s correction last only one session? Module 2 said a model is stateless, and Module 6 showed that Claude Code saves each session to disk but starts the next one with an empty context window. The Claude Code docs put it plainly: “Each Claude Code session begins with a fresh context window” (memory, checked 2026-11-22). A rule typed in chat on Monday is gone on Tuesday.

If you give a fresh session this prompt, check which file it copies and whether it imports src/db.ts. Your run will differ, because a model’s output is sampled (Module 2).

So this module answers one question. How do you give a coding agent the knowledge it can’t see in the code, and how do you make the rules that must never break hold?

Instruction files: what the agent reads before your prompt

An instruction file is a Markdown file that the coding agent loads into the context window at the start of every session, so the model reads it before your first prompt. It’s how a fact reaches every session without you typing it.

How it works underneath

Claude Code reads the file from disk when the session starts and adds its text to the context. The docs say where it goes: “CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself” (memory). So it’s tokens, like any prompt in Module 3. Figure 2 shows where it sits, with the same rows as Module 6’s Figure 4.

Claude Code's context window, top to bottom

+--------------------------------------------+
| system prompt (Claude Code's own)          |  sent with every
| tool definitions: Read, Edit, Bash, ...    |  request, before
| environment information                    |  your prompt
| instruction files and memory               |  <-- read from disk
| skill descriptions, MCP tool names         |      at session start
|--------------------------------------------|
| user: your prompt                          |
| assistant: tool calls                      |  grows with
| user: tool results (files, test output)    |  every step
| ... more steps                             |
+--------------------------------------------+

Figure 2: the instruction file is read from disk at the start of each session and sits above your prompt, so the model sees it on every request.

Two facts follow from this. First, the file survives compaction (Module 6). After /compact, Claude Code reads the project’s root instruction file from disk again and puts it back. A rule you gave only in chat may be lost.

Second, the model reads the file and decides what to do with it. The docs say Claude “tries to follow it”. They add that “there’s no guarantee of strict compliance, especially for vague or conflicting instructions.” The section “Advisory and enforced rules” below comes back to this.

AGENTS.md: one file for many agents

AGENTS.md is an instruction file in plain Markdown at the root of a repo, read by many coding agents. Its site calls it “a README for agents” (agents.md, checked 2026-11-22). A README is for people; AGENTS.md holds the build steps, test commands and conventions an agent needs.

It has no required fields or headings. OpenAI released it in August 2025. On December 9, 2025, it moved to the Agentic AI Foundation, a new group under the Linux Foundation that also took MCP (Linux Foundation press release). The same release says more than 60,000 open source projects had adopted it.

A big repo can hold one AGENTS.md per package. The agent then reads the file nearest to the code it’s working on, as well as the one at the root.

CLAUDE.md, and how Claude Code reads AGENTS.md

CLAUDE.md is Claude Code’s own instruction file. It can live in three places that matter for a project:

  • ./CLAUDE.md in the repo, shared with the team through Git
  • ~/.claude/CLAUDE.md in your home folder, for you in every project
  • ./CLAUDE.local.md in the repo, for you in this project only, listed in .gitignore

Claude Code doesn’t let one file override another. It joins all the files it finds into the context, from the broadest to the one nearest your working folder, so the nearest file is read last. If two lines contradict each other, the docs warn that “Claude may pick one arbitrarily.”

Since v2.1.277 (September 18, 2026), Claude Code also reads AGENTS.md, but only when it finds no CLAUDE.md (changelog, checked 2026-11-22). The memory docs list three cases:

The repo has Claude Code reads
AGENTS.md, and no CLAUDE.md or CLAUDE.local.md in the folder or above it AGENTS.md
AGENTS.md and a CLAUDE.md or CLAUDE.local.md the CLAUDE.md files only
A CLAUDE.md whose first line is @AGENTS.md CLAUDE.md, with AGENTS.md inside it

Figure 3: which instruction file Claude Code v2.1.330 loads, from the memory docs.

The last row uses an import. An import is a line @path in a CLAUDE.md that tells Claude Code to load another file in its place, relative to the importing file. So a team that uses several agents writes its rules once in AGENTS.md, and adds a one-line CLAUDE.md only if it needs Claude-only lines below the import.

Other agents read AGENTS.md too: OpenAI Codex, GitHub Copilot’s agent and Cursor read it as it is, and Gemini CLI reads it once you name it in its settings. Each agent loads the files with its own rules and size limits, so the same file can reach the model in a different order.

What to write, and what to leave out

Every line in the file costs tokens on every request, and every line competes for the model’s attention. Anthropic’s best-practices page says the file “works best when it only holds what Claude couldn’t work out from the code itself” (best practices, checked 2026-11-22). It names four kinds of content:

  • how to confirm work: the exact test, typecheck and lint commands, and how to run one test file
  • places where the code is misleading, such as “an old pattern that’s everywhere but that new code must not copy”
  • decisions that aren’t in the repo
  • anything you’ve had to correct twice already

The second item is TinyTickets’ reports.ts. The fourth is Nina’s three corrections. Here is the file the lab writes:

# TinyTickets

## Commands
- Run all tests: npm test
- Run one test file: node --test test/quote.test.ts

## Layers
- Route handlers in src/routes/ never run SQL and never import src/db.ts.
  They call a function in src/repositories/.
- src/routes/reports.ts still runs SQL from before this rule. Don't copy it.

## Money
- Percent discounts round each ticket with Math.round, in integer cents.

Leave out what the agent finds by reading: the folder layout, the list of dependencies, a tour of the architecture. The same page retires two old habits. Describing your file layout is one, because “Claude reads the repo itself”. Adding IMPORTANT or capitals to a line the agent keeps missing is the other, because “piling on emphasis mostly makes Claude over-apply the rule”.

The memory docs suggest keeping each file under 200 lines. /init writes a first draft from your code, and the best-practices page says that “from there the work is mostly removing lines.”

Do instruction files make agents better? The evidence is thin, and it points both ways.

  • Gloaguen and others (arXiv:2602.11988, February 2026, revised September 2026) ran Claude Code with Sonnet 4.5, Codex with GPT-5.2 and GPT-5.1 mini, and Qwen Code on Python repositories. Files written by a model didn’t raise the share of tasks solved, and they raised the cost. Files written by developers gave a small gain, which wasn’t statistically significant. The paper’s Tables 1 and 2 give the exact figures. The agents did follow what the files said. The authors name their limits: Python only, and small samples.
  • Lulla and others (arXiv:2601.20404, January 2026) compared 124 pull requests in 10 repositories, with and without AGENTS.md. With the file, the median run took 28.64% less time and used 16.58% fewer output tokens, with comparable task completion.

So the file’s job is to pass on facts the agent can’t see. These studies give no sign that it makes the agent solve more tasks, and every line costs tokens on every request.

Rule: An instruction file holds what the code can’t tell the agent: commands, traps and decisions. Everything else costs tokens and attention for nothing.

Skills: procedures loaded only when needed

Some knowledge matters only for one kind of task. “How we add a route” is five steps the agent needs when it adds a route, and never when it fixes a typo. In the instruction file, those steps would cost tokens in every session.

A skill is a folder holding a SKILL.md file with the instructions for one task, which the agent loads only when the task needs it. The format is an open standard called Agent Skills (specification, checked 2026-11-22). Here is the lab’s skill, saved as .claude/skills/add-route/SKILL.md:

---
name: add-route
description: Adds an HTTP route to TinyTickets with its repository function and a test. Use when asked to add an endpoint, a route or an API.
---

# Add a route

1. Write a failing test in test/<area>.test.ts with node:test, using
   start() from test/helpers.ts. Run it and see it fail.
2. If the route needs data that no repository function returns yet, add a
   function to src/repositories/<area>-repository.ts. All data access lives there.
3. Write the handler in src/routes/<area>.ts, on the router <area>Router.
   It checks the input (400), calls the repository (404 when nothing is
   found), and never imports src/db.ts.
4. If the router is new, mount it in src/app.ts.
5. Run npm test. It must pass before you finish.

The block between the two --- lines is the frontmatter. Frontmatter is a short block of YAML at the top of a Markdown file that holds fields about the file. The standard requires two:

  • name: lowercase letters, digits and hyphens, the same as the folder’s name
  • description: what the skill does and when to use it, up to 1,024 characters

Progressive disclosure: three levels of loading

The agent doesn’t read every skill at the start. Progressive disclosure is loading a skill in steps, so the context window holds only a short summary until the task needs more. The standard has three levels, shown in Figure 4.

Level What the agent loads Size the standard suggests When
1 name and description about 100 tokens per skill at the start, for every skill
2 the body of SKILL.md under 5,000 tokens when the skill is used
3 files the body points to (scripts/, references/) as needed when the body says to read one

Figure 4: a skill costs a line in the catalog until it’s used; its body enters the context only then.

In Claude Code, the model sees every skill’s name and description in its context. When a request matches a description, the model calls Claude Code’s Skill tool, and Claude Code adds the skill’s body to the conversation as one message (skills, checked 2026-11-22). You can also start it yourself by typing /add-route with your request after it.

The description decides whether the model ever opens the skill. “Adds an HTTP route … Use when asked to add an endpoint” names the task in the words a request will use. A description such as “Helps with routes” gives the model little to match.

What a skill costs, and the alternatives

A skill isn’t free once it loads. The body “stays in context across turns, so every line is a recurring token cost,” say the skills docs. Keep it short, and put long examples in a references/ file the body points to.

There’s a second cost. A skill is instructions the agent follows, and a skill from outside your team can tell it to do anything. Anthropic’s skills post says: “We recommend installing skills only from trusted sources.” Module 9 picks this up.

Here is how the choice flips between the three ways to hand an agent knowledge:

  • Instruction file: loaded every session. Use it for facts nearly every task needs.
  • Skill: a description every session, the body on use. Use it for a procedure some tasks need.
  • MCP server (Module 5): tool definitions every session. Use it when the agent needs to call a live system, not read steps.

Simon Willison compared the last two when skills launched. Each skill costs “a few dozen extra tokens” until it’s used, he wrote, while GitHub’s MCP server alone used “tens of thousands of tokens” of context (Claude Skills are awesome, maybe a bigger deal than MCP, October 16, 2025).

Skills are recent. Claude Code added them in v2.0.20 on October 16, 2025. Anthropic published Agent Skills as an open standard on December 18, 2025, and gave it to the Agentic AI Foundation on October 22, 2026 (Anthropic’s announcement). The announcement says more than 70 agent platforms support the format, a vendor’s count.

Advisory and enforced rules

Suppose the instruction file and the skill both say “never import src/db.ts in a route.” Will the agent ever do it again?

It may. Both are text in the context window, and the model decides what to do with text. Anthropic’s best-practices page splits every instruction into two kinds. With a prompt, CLAUDE.md or a skill, “the model then decides what to do with this information.” With a hook or a deny rule, “Claude Code (the harness) has to execute this,” every time.

Its example is a line Claude “would follow nearly every time. But no matter how strongly you word it, whether Claude follows that line on a given turn is still Claude’s call.” A user’s prompt can also pull the other way. The AGENTS.md site says that “explicit user chat prompts override everything.”

So the rule that must never break moves out of text. Figure 5 compares the two kinds.

Advisory: the model decides Enforced: Claude Code decides
Examples your prompt, AGENTS.md, CLAUDE.md, skills, auto mode’s classifier hooks that run a command, deny and ask rules
Where it lives tokens in the context window code and settings that Claude Code runs
Context cost every request (files) or after use (skills) none, until it fires
How it fails skipped, lost in a long file, outweighed by a prompt a wrong pattern, a wrong exit code, a gap it doesn’t watch

Figure 5: text guides the model, and settings bind Claude Code; a rule with no exceptions belongs in the right-hand column.

The enforced column has a cost too. A hook or a rule has no judgment, so it blocks the rare case where breaking the rule was right. The same page warns that “if you have hooks for things that are only preferences, delete them and let Claude decide.” A rule with exceptions, such as a naming style, stays in text.

Rule: A rule that must always hold, and that a script can check, goes to Claude Code; a rule that needs judgment stays text.

Hooks: your program at a fixed point in the loop

A hook is a command you configure that Claude Code runs itself at a fixed point in the agent loop. The model can’t skip it, because the model doesn’t run it. The hooks guide says hooks give “deterministic control: certain actions always happen rather than relying on the LLM to choose to run them” (hooks guide, checked 2026-11-22). Claude Code released hooks in v1.0.38, on June 30, 2025.

Events and matchers

A hook event is the point in the loop where a hook runs. Claude Code has more than thirty, and three cover most needs:

  • PreToolUse runs before a tool call and can block it.
  • PostToolUse runs after a tool call succeeds. The tool has already run, so it can’t undo it, but it can send a message to the model.
  • Stop runs when Claude finishes its answer, and can make it keep working.

A matcher is a pattern that picks which tool calls a hook runs for, by tool name. "Edit|Write" matches the Edit tool or the Write tool, and the names are case-sensitive. The lab’s hook, in .claude/settings.json, looks like this:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/scripts/check-routes.ts"] }
        ]
      }
    ]
  }
}

Read it from the outside in. The event is PostToolUse. The matcher picks Edit and Write calls. The handler runs node with the script’s path as an argument. ${CLAUDE_PROJECT_DIR} is the project’s folder, and Claude Code fills it in. With args present, Claude Code starts node directly, without a shell, which the hooks reference advises for any path with a placeholder (hooks reference).

What the hook receives, and what its exit code means

Claude Code sends the hook a JSON object on standard input, with the event name, the tool’s name and its input. For a Write, the input holds the file’s path and content:

{
  "hook_event_name": "PostToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/home/you/tinytickets-mini/module-07/src/routes/seats.ts",
    "content": "..."
  }
}

That’s an excerpt; the real object also has the session’s ID, the working folder and the tool’s response. The lab’s script ignores this input and checks every route file, so it also works when you run it yourself or in CI.

The hook’s exit code decides what happens next. Figure 6 traces it for the lab’s hook.

[Model] --tool_use Write--> [Claude Code] --writes--> [[src/routes/seats.ts]]
                                 |
                                 | PostToolUse; "Edit|Write" matches
                                 v
                     [node scripts/check-routes.ts]
                       exit 0: nothing more happens
                       exit 2: its stderr goes to the model
                       other:  a notice for you; the model sees nothing

Figure 6: only exit code 2 puts the hook’s message in front of the model.

  • Exit 0 is success. Claude never sees what the hook printed to standard error.
  • Exit 2 is a blocking error. For PostToolUse, Claude Code “shows stderr to Claude; the tool already ran.” For PreToolUse, it blocks the call.
  • Any other code, 1 included, is a non-blocking error. The action goes ahead, and Claude Code shows you a notice. The reference is direct about it: “If your hook is meant to enforce a policy, use exit 2.”

So a hook written the usual Unix way, with exit 1 on failure, enforces nothing.

The check script

The hook runs this script, scripts/check-routes.ts:

// Fails when a file in src/routes/ talks to the database directly.
// Run it yourself (npm run check:routes) or from a Claude Code hook.
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

const root = process.env.CLAUDE_PROJECT_DIR ?? process.cwd();
const routesDir = join(root, "src", "routes");

// Old files that still hold SQL. Don't add to this list: shrink it.
const legacy = new Set(["src/routes/reports.ts"]);

const rules = [
  { what: "an SQL statement", pattern: /\b(SELECT\s[^;`'"]{1,200}?\sFROM|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM)\b/g },
  { what: "an import of src/db.ts", pattern: /from\s+["'][^"']*\/db(\.ts)?["']/g },
  { what: "a .query() call", pattern: /\.query\s*\(/g },
];

const problems: string[] = [];
for (const name of readdirSync(routesDir, { recursive: true })) {
  const file = "src/routes/" + String(name).replaceAll("\\", "/");
  if (!file.endsWith(".ts") || legacy.has(file)) continue;
  const text = readFileSync(join(root, file), "utf8");
  for (const rule of rules) {
    for (const match of text.matchAll(rule.pattern)) {
      const line = text.slice(0, match.index).split("\n").length;
      problems.push(`${file}:${line}: ${rule.what} in a route handler`);
    }
  }
}

if (problems.length > 0) {
  console.error(problems.join("\n"));
  console.error(
    "Route handlers must not touch the database. " +
      "Move the query into a function in src/repositories/ and call that function from the route.",
  );
  process.exit(2); // 2 = Claude Code shows this message to Claude
}

Notice three things. It looks for three signs of data access: an SQL keyword pair in capitals, an import of db.ts, and a .query( call. Its error message tells the model what to do next, the lesson of Module 4’s tool results. And it skips reports.ts by name, so the old route keeps working while the list says it should shrink.

The check has limits. SQL in lower case, passed through a helper that isn’t named query and isn’t imported from db.ts, would get through. A check like this is a net that catches the usual mistake, and review still catches the rest.

Limits and alternatives

The matcher has a gap. A PostToolUse hook on Edit|Write doesn’t run when a Bash command changes the file, such as sed -i or a code generator. The hooks reference suggests a Stop hook that runs the same check once at the end of each answer, and the lab’s script works there unchanged.

Hooks aren’t the only way to enforce a rule. Here is where the choice flips:

  • CI or a Git pre-commit hook runs the same script, for people and for every agent. But it runs at commit or push time, and the agent doesn’t see the failure inside its loop. Keep the script in CI too.
  • A linter rule is the usual way for a TypeScript team, such as ESLint’s no-restricted-imports. It catches imports well, and it needs ESLint in the project.
  • A PreToolUse hook can stop a write before it happens. But for an Edit it sees only the changed text, not the whole file, so it could miss an import added earlier. For “never touch this file” rules, PreToolUse is the better fit.

Hook settings belong to Claude Code. OpenAI Codex has hooks with a similar shape and adds a trust step before a repo’s hooks run (Codex hooks). Unlike AGENTS.md and skills, the files don’t move between agents.

Permission rules: allow, ask and deny

A hook checks what the agent did. A permission rule decides what the agent may do at all. A permission rule is a line in Claude Code’s settings that matches tool calls and allows them, asks you first, or denies them, whatever the permission mode (permissions, checked 2026-11-22).

Rules go in three lists in .claude/settings.json, next to the hooks:

{
  "permissions": {
    "allow": ["Bash(npm test)", "Bash(npm run check:routes)", "Bash(node --test *)"],
    "ask": ["Bash(git push *)"],
    "deny": ["Read(./.env)", "Edit(./scripts/check-routes.ts)"]
  }
}

A rule is a tool name, with an optional pattern in brackets. Bash(npm test) matches that exact command, and Bash(node --test *) matches any command that starts with node --test. Read(./.env) matches reading that file, and Edit(...) rules cover all of Claude Code’s file-editing tools, Write included.

How Claude Code applies them

“Rules are evaluated in order: deny, then ask, then allow,” say the permissions docs. The first match wins, and “an allow rule can’t carve an exception out of a deny rule.” Here is what this file does:

  • npm test, the check script and single test files run without a question, even in Manual mode.
  • A push always asks you, even in auto mode.
  • The agent can’t read .env, where a DATABASE_URL with a password would live.
  • The agent can’t edit the check script, so it can’t make the check pass by adding its own file to the legacy list.

Module 6 taught the permission modes. Rules sit in front of them. In auto mode, your own rules apply first, and the classifier judges only what they don’t settle. A deny rule holds in every mode, bypassPermissions included. The best-practices page draws the line for auto mode. Its classifier is “a classifier model judging each action rather than a hard rule.” So “your ‘never’ rules belong in deny rules or hooks.”

What rules don’t catch

“Rules match tool calls, not intent,” says the best-practices page. The Read(./.env) deny also covers cat .env and other file commands Claude Code recognizes in Bash. It doesn’t stop a script the agent writes that opens the file itself. Module 9 adds a sandbox for that gap.

One more limit protects you. A repo’s allow rules wait until you accept the workspace trust dialog, the question Claude Code asks the first time it opens a folder. Its deny and ask rules apply at once, because they only restrict.

Where each rule belongs

You now have four places to put what the agent should know or must do. Figure 7 sorts the team’s needs into them, from the most often loaded to the most strictly enforced.

What you need Put it in When it acts
A fact for almost every task: the test command, a trap like reports.ts AGENTS.md or CLAUDE.md every session, from the start
A fact for one folder an AGENTS.md in that folder when the agent works there
A procedure for some tasks: add a route, cut a release a skill its description always; its body on use
A rule with no exceptions that a script can check a hook, and the same script in CI every matching tool call, whatever the model decides
An action the agent must never take a deny rule (and a sandbox, Module 9) every matching tool call, in every mode

Figure 7: the further down the table, the less the rule depends on the model.

The memory docs give the signals for writing a line at all. One is that “Claude makes the same mistake a second time”. Another is that “you type the same correction or clarification into chat that you typed last session.” Nina’s third correction was past both.

Karpathy’s list of what an agentic engineer does, which Module 6 quoted, includes “manage permissions” (his Sequoia Ascent 2026 summary, April 30, 2026). The lab’s settings file is that work for one rule.

Rule: Put a fact where it’s loaded no more often than it’s needed, and a rule where it’s enforced as strictly as it must hold.

One edit through the hook

This trace follows one prompt from lab step 7. The repo now has AGENTS.md, the add-route skill and .claude/settings.json. You start claude --permission-mode acceptEdits, so edits run without a question and the hook is the only check on them. You type:

Add GET /shows/:id/seats in a new file, src/routes/seats.ts. Read the
seat count with pool.query from src/db.ts, the way reports.ts does.

The prompt asks for exactly what AGENTS.md forbids, which is how you test a guard. First, where the new parts sit. Figure 8 redraws the agent loop from Module 6 with instruction files and skills in the context window.

                      context window
                    +-------------------+
                    | tool definitions  |    tool_use           tools
                    | system prompt     |-->[Model]-->[check]-->[Read]
                    | instruction files | NEW            |      [Edit]
                    | skills            | NEW            |      [Write]
(Developer) task -->| user: task        |                |      [Bash]
     ^      ^       | assistant: calls  |                |      [MCP tools]
     |      |       | user: results     |<- tool_result -|-----------+
     |      |       | ... more steps    |                |           |
     +- answer -----| assistant: answer |                |           v
            |       +-------------------+                |   [[project files]]
            +----------------- "Allow?" -----------------+

instruction files: AGENTS.md or CLAUDE.md, read from disk at the start.
skills: every skill's name and description at the start; a skill's body
joins the conversation only when it's used.

Figure 8: the same loop as Module 6; the team’s rules now reach the model through files Claude Code loads at the start of every session.

Figure 9 shows the messages of this one prompt, in the order the trace assumes.

(Developer)  [Claude Code]           [Claude API]       [check-routes.ts]
    |-- prompt -->|                        |                    |
    |             |-- 1: request --------->|                    |
    |             |<- tool_use Write ------|                    |
    |             |-- writes seats.ts      |                    |
    |             |-- PostToolUse hook ------------------------>|
    |             |<- exit 2, three problems on stderr ---------|
    |             |-- 2: + result, hook -->|                    |
    |             |<- Edit, Edit ----------|                    |
    |             |-- PostToolUse hook ------------------------>|
    |             |<- exit 0, silent ---------------------------|
    |             |-- 3: + results ------->|                    |
    |             |<- tool_use Bash -------|                    |
    |             |-- npm test, allowed, no question            |
    |             |-- 4: + result -------->|                    |
    |<- summary --|<- end_turn ------------|                    |

Figure 9: the hook’s message reaches the model inside the loop, so it fixes the route in the same turn.

Session start. Claude Code reads AGENTS.md from disk and adds it after the system prompt. It adds the add-route description to the skill list, and loads the hook and the rules from .claude/settings.json. Nothing you typed yet.

Request 1. The model now holds two instructions that disagree: the layer rule in AGENTS.md and your prompt. It may refuse and point to AGENTS.md, which means the text worked. It may also call the Skill tool, and the skill’s steps join the conversation. This trace follows the third outcome, in which it writes src/routes/seats.ts as asked:

import express from "express";
import { pool } from "../db.ts";

export const seatsRouter = express.Router();

seatsRouter.get("/shows/:id/seats", async (req, res) => {
  const result = await pool.query(
    "SELECT seats FROM shows WHERE id = $1",
    [req.params.id],
  );
  res.json(result.rows[0]);
});

The hook. The mode is acceptEdits, so Claude Code writes the file without asking. Write matches Edit|Write, so Claude Code runs the script, which finds three problems and exits 2:

src/routes/seats.ts:8: an SQL statement in a route handler
src/routes/seats.ts:2: an import of src/db.ts in a route handler
src/routes/seats.ts:7: a .query() call in a route handler
Route handlers must not touch the database. Move the query into a function in src/repositories/ and call that function from the route.

That output is deterministic, so it’s the same on every run of the script on this file. It comes from a line-for-line Python copy of the script, run on 2026-11-22. You run the real script in the lab’s step 5.

Request 2. Claude Code sends the Write result and the hook’s message back to the model. Check the exact wording in your own transcript in step 7. The model reads it the way it reads a failing test. A likely next move is a new function in src/repositories/show-repository.ts, such as seatCount(id), and an edit to seats.ts that calls it. Each of those edits runs the hook again, and this time it exits 0, so the model sees nothing more.

Request 3 and the answer. The model runs npm test. The allow rule matches, so it runs without a question. Then it ends its turn with a summary that should mention the hook and the move.

When you run this prompt in step 7, compare your transcript with this trace. Your run may refuse at request 1, or ask you whether to follow AGENTS.md or your prompt. Whatever it does, the rule was checked by a program, and its message reached the model.

Lab: make the layer rule hold

Time: about 30 minutes. You’ll teach Claude Code the TinyTickets layer rule in three layers. First a file the agent reads, then a skill it loads for one task, then a hook and permission rules it can’t skip.

You need:

  • Git, Node.js 26 LTS (v26.13.1) and Claude Code v2.1.330 or later, as in Module 6. Claude Code costs money through a Claude plan or Console credits (pricing), or use Ollama for free (see the note at the end of the lab).
  • The sample repo, cloned in Module 6 as tinytickets-mini.
  • A second terminal, for the commands you run yourself.

Model: Claude Code’s default model for your account. Note which model your session uses, because the agent’s replies depend on it. With a later model, the steps stay the same and the agent’s replies change.

The outputs this lab describes are what to look for, not copies of a real run. Your agent’s replies will differ, so check each step against what it tells you to look for.

Step 1: start from module-07, green

Why: a known good start means any failure later comes from the agent or from your settings.

cd tinytickets-mini
git switch main
git pull
cd module-07
npm install
npm test

The repo is vespaiach/tinytickets-mini on GitHub. The module-07 folder is Module 6’s finished app, the engineered branch, with three additions. Figure 10 marks them.

tinytickets-mini/module-07/
  package.json          adds the pg package (the PostgreSQL client)
  .gitignore            node_modules/ and .env
  src/
    server.ts
    app.ts              mounts showsRouter, ordersRouter, reportsRouter
    store.ts            in-memory data, resetStore()
    db.ts               added: a PostgreSQL pool, or null without DATABASE_URL
    repositories/
      show-repository.ts
    sales/
      booking-fee.ts
      discounts.ts
      pricing.ts
    routes/
      shows.ts          GET /shows
      orders.ts         POST /orders/quote
      reports.ts        added: GET /reports/sales, SQL in the route
  test/
    helpers.ts
    booking-fee.test.ts, discount.test.ts, pricing.test.ts, quote.test.ts

Figure 10: the lab’s starting folder; db.ts and reports.ts are the misleading pattern the agent can copy.

src/db.ts holds the pool:

import pg from "pg";

// A PostgreSQL pool when DATABASE_URL is set. Without it, pool is null
// and the app runs on the in-memory store.
export const pool = process.env.DATABASE_URL
  ? new pg.Pool({ connectionString: process.env.DATABASE_URL })
  : null;

You don’t need PostgreSQL for this lab. You should see 13 tests pass and none fail, as at the end of Module 6. Read src/routes/reports.ts once, then make a branch:

git switch -c teach-the-agent

Step 2: ask a fresh session about the rule (this step fails on purpose)

Why: you should see what the agent knows about the rule when only the code can tell it.

Start Claude Code in plan mode, so it can read but not edit:

claude --permission-mode plan

The status bar should say ⏸ plan mode on. Type:

In this repo, may a route handler in src/routes/ run SQL or import
src/db.ts? Answer from the code, in two sentences.

Pause and predict. What will it answer, and which file will it cite?

You’re likely to see an answer built from what the code shows, which may say that routes can query the database because reports.ts does, or that both patterns exist. Neither answer is the team’s rule, because the rule isn’t anywhere the agent can read. Close the session with /exit.

Step 3: write AGENTS.md, and check that it loaded

Why: a file is the only way the rule reaches the next session without you typing it.

Create AGENTS.md in module-07, with the content from “What to write, and what to leave out”:

# TinyTickets

## Commands
- Run all tests: npm test
- Run one test file: node --test test/quote.test.ts

## Layers
- Route handlers in src/routes/ never run SQL and never import src/db.ts.
  They call a function in src/repositories/.
- src/routes/reports.ts still runs SQL from before this rule. Don't copy it.

## Money
- Percent discounts round each ticket with Math.round, in integer cents.

Start a new session with claude --permission-mode plan. Near the top you should see a line like no CLAUDE.md found; AGENTS.md loaded: /home/you/tinytickets-mini/module-07/AGENTS.md. Type /context all and look for AGENTS.md under “Memory files”. If it’s missing, check for a CLAUDE.md or CLAUDE.local.md in this folder or any folder above it (see “Common mistakes”).

Ask the question from step 2 again. You’re likely to see an answer that gives the rule and names reports.ts as the exception. Check that yours does. If it does, the text worked this time. Nothing makes it work every time.

Commit the file in your second terminal:

git add AGENTS.md
git commit -m "Write the team's rules for agents"

Step 4: add the skill, and build one route with it

Why: the steps for adding a route matter only when you add one, so they belong in a skill, not in AGENTS.md.

Create .claude/skills/add-route/SKILL.md with the skill from “Skills: procedures loaded only when needed”. Then start a new session in Manual mode:

claude --permission-mode manual

Type /context and look for the skill’s name and description; its body isn’t there yet. Then type:

/add-route GET /shows/:id returns one show, or a 404 for an unknown id

Approve each edit after you read it, and approve npm test. The skill tells the agent to write a failing test first, so you’re likely to see a new test/shows.test.ts fail. Then a handler in src/routes/shows.ts calls findShow from the repository. You should end with 15 tests passing. Type /context again, and check that the skill’s body now takes space in the conversation.

One version that passes (written for this page; your agent’s will differ)

In src/routes/shows.ts, after importing findShow next to listShows:

showsRouter.get("/shows/:id", (req, res) => {
  const show = findShow(req.params.id);
  if (!show) {
    res.status(404).json({ error: "unknown show" });
    return;
  }
  res.json(show);
});

test/shows.test.ts:

import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import type { Server } from "node:http";
import { start } from "./helpers.ts";

let server: Server;
let base = "";

before(async () => {
  ({ server, base } = await start());
});

after(() => {
  server.close();
});

test("GET /shows/:id returns one show", async () => {
  const res = await fetch(base + "/shows/songs-of-spring");
  assert.equal(res.status, 200);
  const show = await res.json();
  assert.equal(show.priceCents, 1200);
});

test("an unknown show id is a 404", async () => {
  const res = await fetch(base + "/shows/nope");
  assert.equal(res.status, 404);
});

Review with git diff, then commit in your second terminal:

git add -A
git commit -m "Add the add-route skill and GET /shows/:id"

Step 5: write the check, and watch it fail

Why: a hook can only run a check that already works, so you test the check by hand first.

Create scripts/check-routes.ts with the script from “The check script”. Add a line to the scripts in package.json (excerpt):

"scripts": {
  "start": "node src/server.ts",
  "test": "node --test test/*.test.ts",
  "check:routes": "node scripts/check-routes.ts"
}

Run the script on the clean repo, and print its exit code:

node scripts/check-routes.ts
echo $?

You should see no output and 0. Now break the rule on purpose. Create src/routes/seats.ts with the file from the trace, the one that imports pool, and run the two commands again.

Pause and predict. How many problems will it print, and with which exit code?

Answer

Three problems, one per rule, for lines 8, 2 and 7, then the message about src/repositories/. Then echo $? prints 2.

You should see the four lines shown in the trace, then 2. Delete src/routes/seats.ts. Then add one line under “Commands” in AGENTS.md, so the agent knows the check exists:

- Check the layers: npm run check:routes

In the skill, change step 5 to “Run npm test and npm run check:routes. Both must pass before you finish.” Commit the script, package.json, AGENTS.md and the skill.

Step 6: wire the hook and the permission rules

Why: so far the agent can ignore both the file and the check; the settings file makes Claude Code run the check after every edit.

Create .claude/settings.json with the permissions and the hook together:

{
  "permissions": {
    "allow": ["Bash(npm test)", "Bash(npm run check:routes)", "Bash(node --test *)"],
    "ask": ["Bash(git push *)"],
    "deny": ["Read(./.env)", "Edit(./scripts/check-routes.ts)"]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/scripts/check-routes.ts"] }
        ]
      }
    ]
  }
}

Start a new session with claude --permission-mode acceptEdits. If Claude Code shows the workspace trust dialog, read what it lists and accept it; until then, the repo’s hooks and allow rules don’t run. Type /hooks and check that it lists the PostToolUse entry with the matcher Edit|Write. Type /permissions and check that it shows your three lists.

Step 7: test the guard

Why: a guard you have never seen fire is a guard you can’t trust.

In the same session, type the prompt from the trace:

Add GET /shows/:id/seats in a new file, src/routes/seats.ts. Read the
seat count with pool.query from src/db.ts, the way reports.ts does.

You’re likely to see one of three things.

  • The agent refuses or asks, and points to AGENTS.md. The text held. Reply “This is a test of the hook. Write it as I asked.” to see the next outcome.
  • The agent writes the file, the hook prints the three problems, and the agent moves the query into src/repositories/show-repository.ts.
  • The agent writes the file and stops. Look for the hook’s message in the transcript with Ctrl+O.

npm test and npm run check:routes should run without a question, because of the allow rules. Now try the deny rule:

Add src/routes/seats.ts to the legacy list in scripts/check-routes.ts.

You should see the edit refused, whatever the agent says about it. Check how your session reports the refusal. The deny rule also covers sed and other file commands Claude Code recognizes in Bash.

Step 8: clean up and commit

Why: the lab’s files are the team’s rules now, and they belong in Git with the code.

In your second terminal:

git status
npm test
npm run check:routes

If the agent left a route that still breaks the rule, delete src/routes/seats.ts or keep the agent’s fixed version if both checks pass. Then commit .claude/settings.json and anything else that’s left:

git add -A
git commit -m "Enforce the layer rule with a hook and permission rules"

Your branch now holds the three layers: AGENTS.md, the add-route skill, and .claude/settings.json with the check script.

Ollama note. Set up Claude Code with Ollama v0.40.17 and qwen3-coder (or qwen3:8b on a 16 GB machine) as in Module 6’s lab (Ollama’s Claude Code page, checked 2026-11-22). The hook and the permission rules behave the same, because Claude Code runs them, not the model. A smaller model follows AGENTS.md and matches skill descriptions less reliably. So the hook may fire more often in step 7, and you type /add-route to load the skill. Auto mode isn’t available there. Check each step’s output against what it tells you to look for.

Other agents. AGENTS.md from step 3 works as it is in Codex, GitHub Copilot’s agent and Cursor. The skill folder works in agents that support Agent Skills, in the folder each one scans. Steps 6 and 7 are Claude Code’s own settings; Codex has its own hooks file with a trust review.

Going deeper

Path-scoped rules

Claude Code can also load an instruction only for some files. A Markdown file in .claude/rules/ with a paths: list in its frontmatter, such as "src/routes/**/*.ts", loads when Claude reads or edits a matching file (memory). It saves tokens when a rule matters for one folder. It’s still text the model may skip, and other agents don’t read it; a nested AGENTS.md is the portable way.

How other agents load AGENTS.md

Codex builds its chain once per run. It walks from the Git root down to your working folder and takes at most one file per folder. It joins them with closer files last, and stops at 32 KiB by default (Codex AGENTS.md docs). Claude Code loads the files above your folder at launch and a subfolder’s file only when it touches a file there. The idea is the same, and the order and limits differ.

Hooks that ask a model

A hook’s type can also be prompt or agent, which asks another model to decide. The best-practices page says that “isn’t deterministic either.” For a rule that must hold, use a command hook. Add "onFailure": "block" (v2.1.295 and later) if a hook that crashes or can’t start should stop the action, because by default it doesn’t.

Memory Claude writes for itself

Claude Code also keeps auto memory, which is notes Claude writes in ~/.claude/projects/<project>/memory/MEMORY.md, of which the first 200 lines or 25 KB load each session. You write CLAUDE.md; Claude writes auto memory. It stays on your machine, so it never reaches your teammates.

Hooks are code from the repo

A repo’s .claude/settings.json runs commands on your machine. In an interactive session, Claude Code holds them back until you accept the trust dialog. The docs say a claude -p run “treats the folder as trusted,” so hooks committed in a repo run there with no dialog. Module 9 treats this as a security problem.

Common mistakes with instruction files, skills and hooks

  • A hook that exits 1. Symptom: the check prints its problems, and the agent carries on as if nothing happened. Fix: exit 2 to block, and test with node scripts/check-routes.ts; echo $?.
  • A personal CLAUDE.local.md next to AGENTS.md. Symptom: Claude Code stops following AGENTS.md, and /context all doesn’t list it. Fix: put @AGENTS.md on the first line of a CLAUDE.md, or keep personal notes in ~/.claude/CLAUDE.md.
  • Shouting at a line the agent keeps missing. Symptom: you add IMPORTANT, and the agent over-applies the rule or still misses it. Fix: shorten the file, or move a rule with no exceptions into a hook.
  • Keeping /init‘s draft as it is. Symptom: a long file that describes folders the agent reads anyway. Fix: delete everything except commands, traps and decisions.
  • A vague skill description. Symptom: the skill never loads unless you type its name. Fix: name the task in the words a request uses, and say “Use when …”.
  • Trusting Edit|Write to see every change. Symptom: a file rewritten by sed or a generator breaks the rule unseen. Fix: run the same script in a Stop hook and in CI.
  • A Write(...) permission rule. Symptom: it never matches. Fix: use Edit(...), which covers every file-editing tool.

Check yourself

Scenario. Omar’s team adds this line to AGENTS.md: “Never edit files in migrations/.” A week later, the agent edits a migration while fixing a bug, and nobody notices until the database update fails in review. Omar adds “IMPORTANT” in front of the line. What would you do instead, and what would you leave in AGENTS.md?

Answer

The rule has no exceptions and a program can check it, so it belongs in Claude Code’s settings, not in text. Add a deny rule such as Edit(./migrations/**), or a PreToolUse hook on Edit|Write that exits 2 for any path under migrations/. Either one acts before the file changes, in every mode, whatever the model decides.

“IMPORTANT” doesn’t change that the line is text the model may skip, and the docs say emphasis tends to make the model over-apply a rule. In AGENTS.md, keep what helps the agent work: how the team writes a new migration, and the command that checks one.

  1. Where does Claude Code put the text of CLAUDE.md in the request, and what does that mean for how strictly the model follows it?
  2. A repo has AGENTS.md and a CLAUDE.md. Which does Claude Code v2.1.330 read, and how do you make it read both?
  3. What does the add-route skill cost in the context window before it’s used, and after?
  4. A PostToolUse hook prints a problem to standard error and exits 1. What does the model see, and what happens to the edit?
  5. A settings file has "allow": ["Bash(git push *)"] and "deny": ["Bash(git push *)"]. What happens when the agent pushes?
Answers
  1. As a user message after the system prompt; it’s text the model reads and usually follows, with no guarantee.
  2. Only CLAUDE.md; put @AGENTS.md on its first line, so it imports the other file.
  3. Before, only its name and description, about 100 tokens; after, the whole body too, which stays in the conversation.
  4. Nothing, because only exit code 2 shows stderr to the model; the edit stays, since PostToolUse runs after the tool.
  5. It’s denied, because deny rules are checked first and an allow rule can’t make an exception to one.

Cheat sheet

Teaching the agent your project

  • Every session starts empty: a rule typed in chat doesn’t reach the next session.
  • AGENTS.md: read by most agents; Claude Code reads it when there’s no CLAUDE.md (v2.1.277+).
  • CLAUDE.md: Claude Code’s file; @AGENTS.md on line one imports the shared one.
  • Write: commands, misleading code, decisions, repeated corrections. Leave out what the code shows.
  • Skill: .claude/skills/<name>/SKILL.md; the description always loads, the body on use.
  • Advisory vs enforced: files and skills are text the model may skip; hooks and deny rules always run.
  • Hook: PostToolUse with matcher Edit|Write; exit 2 sends stderr to the model; exit 1 does nothing.
  • Rules: deny, then ask, then allow; deny holds in every mode.

Figure 11 is the module in one picture: the same rule in three layers.

the rule: "route handlers never touch the database"

(Developer) writes --> [[AGENTS.md]] ----- read at start --> [Model] advisory
(Developer) writes --> [[add-route skill]] -- read on use --> [Model] advisory
(Developer) writes --> [[.claude/settings.json]]
                          |
                          +-- PostToolUse hook --> [check-routes.ts]  enforced
                          |       exit 2: the problems go to [Model]
                          +-- deny rule: no edits to the check        enforced

Figure 11: the file and the skill tell the model the rule; the hook and the deny rule make Claude Code check it.

Next, Module 8 looks at a change that passes every test and still charges the booking fee twice, and at how you verify what a hook can’t.

Sources