# Agentic Coding Playbook

How to prepare, instruct, and run coding agents like Claude Code so you ship maintainable software instead of ceremony.

**Provenance.** These are my working notes, published as-is. I wrote them for myself while figuring out how to run coding agents on real client work, then cleaned them up: client names removed, internal architecture genericised, and every external claim re-verified against its primary source before publishing.

**Last verified: 28 July 2026.** Sources at the end. Anything I could not verify against a primary source has been cut rather than softened.

**A note on model versions.** The research below describes ablations run on Claude Opus 4.5 and 4.6. Those were the frontier models when the work was done. The lineup has since moved on (Opus 5, Sonnet 5, and Fable 5 all shipped after). I have deliberately left the original model names in place, because the *finding* is about a specific model generation and rewriting it to name a newer model would be inventing a result nobody measured. Read the version numbers as history, not as current recommendations. That is the whole point of Part 1's closing argument anyway.

---

## The short version

Three things reliably improve output. Everything else is negotiable ceremony:

1. **A spec that pins down intent, scope, and what "done" looks like.** Without it the agent under-scopes or solves the wrong problem.
2. **A verification loop the agent can run itself.** Tests, a build, a screenshot diff, a linter. If it cannot check its own work, you become the check.
3. **Codebase structure that keeps changes local.** Small blast radius, explicit boundaries, no hidden coupling.

Three things are usually stale overhead, and they are the usual source of frustration:

1. **Phase and timeline theater.** "Week 1 to 3, Phase 2 of 4, estimated 6 hours." An agent does not have a calendar. Sequencing is real, calendars are not.
2. **Forced task decomposition into micro-steps.** This existed because older models lost coherence over long runs. Current models mostly do not.
3. **Open-ended option generation.** When the agent brainstorms five approaches and you pick one, planning authority has quietly transferred to the agent. That correlates with worse outcomes, not better.

**The rule that resolves it:** every piece of process encodes an assumption about what the model cannot do alone. Those assumptions go stale fast. Stress test them by removing one at a time and watching what breaks.

---

## Part 1. The mental model

### Who decides what

Anthropic analysed roughly 400,000 interactive Claude Code sessions from about 235,000 people, between October 2025 and April 2026. In the typical session the human makes about **70% of the planning decisions** (what to build, which approach, what counts as done) and only about **20% of the execution decisions**, which means Claude makes roughly 80% of those.

That split is not an accident. It is the shape that works.

Success rates track domain expertise, not coding ability. Sessions rated novice hit verified success 15% of the time. Intermediate and above hit 28 to 33%. Novices abandon troubled sessions at 19% versus 5 to 7% for everyone else. Most of the gain comes from novice to intermediate, not intermediate to expert. Competence is enough. Mastery adds little.

There is a second finding worth sitting with: on coding tasks, every major occupation succeeds at close to the same rate as software engineers. The constraint is domain knowledge about the problem, not fluency in the language.

**What this implies.** Your leverage is in the *what*, stated precisely. Not in supervising the *how*. Every minute of process that pulls you toward reviewing implementation choices instead of sharpening the requirement is a minute spent on the wrong side of the split.

### Context is the binding constraint

Almost every best practice reduces to one fact. Performance degrades as the context window fills. A single exploration session can burn tens of thousands of tokens. When context is full, the agent starts forgetting your earlier instructions and making more mistakes.

So the game is not "give the agent everything." It is **progressive disclosure**. A small stable entry point, plus a map to where the deeper information lives, plus mechanisms that load detail only when relevant.

This is why an enormous CLAUDE.md makes things *worse*, not better. When everything is marked important, nothing is.

### The four loading mechanisms, ranked by cost

| Mechanism | Loads when | Cost | Use for |
|---|---|---|---|
| CLAUDE.md | Every session, in full | Highest, every request | Always-true rules and commands |
| `.claude/rules/` with `paths:` | When the agent opens a matching file | Medium | Stack-specific or directory-specific conventions |
| Skills | Description at start, body on demand | Low | Reference material and repeatable workflows |
| Hooks | On a lifecycle event, outside the conversation | Zero | Things that must happen every time, no exceptions |

The most common setup mistake is putting everything in tier 1. Push things down the list aggressively.

---

## Part 2. Does brainstorming earn its keep

Short answer: it depends entirely on **who is generating the content**.

### What the evidence says

Anthropic's Labs team built a three-agent harness (planner, generator, evaluator) for long autonomous builds, then methodically removed one component at a time to see what was load-bearing.

**Kept the planner.** Without it, in their words, "the generator under-scoped: given the raw prompt, it would start building without first speccing its work."

**Kept the evaluator, but changed its shape.** It moved from grading every sprint to a single pass at the end. An independent checker earns its cost only when the task sits beyond what the model does reliably solo. When the model got better, that boundary moved outward.

**Deleted the sprint decomposition entirely.** The write-up is blunt about it: "I started by removing the sprint construct entirely." It had been scaffolding for a weaker model. On Opus 4.6 the generator planned, wired up, and tested an app across a build phase of two hours and seven minutes without it. For contrast, Opus 4.5 had "exhibited context anxiety strongly enough that compaction alone wasn't sufficient."

Their conclusion, quoted exactly: "every component in a harness encodes an assumption about what the model can't do on its own, and those assumptions are worth stress testing, both because they may be incorrect, and because they can quickly go stale as models improve."

### So where does brainstorming land

**Brainstorming that extracts what is in your head is high value.** You know the business constraint, the client's real objection, the edge case that breaks at month-end. The agent does not. A structured interview that pulls that out of you and writes it down is the single highest-leverage step in the whole workflow. Anthropic's own docs recommend exactly this:

> I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
>
> Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.
>
> Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.

**Brainstorming that generates options for you to approve is low value and often negative.** It looks like collaboration. It is actually the agent taking over the planning decisions, which is the side of the split where humans should stay. It also adds scope. An adversarial reviewer asked to find gaps will always find some, and chasing all of them produces over-engineering: extra abstraction layers, defensive code, tests for cases that cannot happen. Anthropic warns about this explicitly.

### The keep/cut table

| Practice | Verdict | Why |
|---|---|---|
| Interview me, then write the spec | **Keep** | Extracts your knowledge, prevents under-scoping |
| Explore before planning (read the code first) | **Keep** | Prevents solving the wrong problem |
| Written spec with explicit non-goals | **Keep** | Non-goals are the cheapest scope control that exists |
| A verification step the agent runs itself | **Keep** | The single biggest quality lever |
| Fresh-context review of the diff | **Keep for risky work** | Fresh context is not biased toward code it just wrote |
| Phases with time estimates | **Cut** | Meaningless to an agent, invites padding |
| Break into 2 to 5 minute tasks | **Cut by default** | Solves a problem the current models no longer have |
| Generate 3 approaches for me to choose | **Cut** | Transfers planning to the agent, expands scope |
| Full ceremony for small changes | **Cut** | If you can describe the diff in one sentence, skip the plan |
| TDD on everything | **Situational** | Great where behaviour is verifiable, ceremony on glue code and UI |

### The 30-second triage to run on every task

- **Can I describe the diff in one sentence?** Go direct. No plan mode, no spec, no ceremony.
- **Multi-file, or I am unfamiliar with this code, or the approach is genuinely uncertain?** Explore, then plan, then implement.
- **New feature or new product?** Interview, spec, then a fresh session to build.

That is the whole decision tree. Anthropic's docs say the same thing more bluntly: "Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan."

---

## Part 3. Project setup, before any code

The core principle, from the OpenAI team who shipped roughly a million lines of a production beta with no code written by human hands (three people, empty repo, five months from late August 2025):

> Give the agent a map, not a 1,000-page instruction manual.

They tried one big instruction file. It failed predictably. Context crowded out the actual task. Everything was marked important so nothing was. It rotted instantly and nobody could tell which rules were still true. It could not be mechanically verified so drift was guaranteed.

Their fix: **the instruction file is a table of contents. The `docs/` directory is the system of record.**

The second principle, also theirs, is the one worth tattooing somewhere:

> From the agent's point of view, anything it cannot access in-context effectively does not exist.

That Slack thread where you and a colleague agreed on the architecture? Invisible. That decision you made in the shower? Invisible. If it is not a versioned file in the repo, it is not real to the agent.

### The repo skeleton

```
project-root/
├── CLAUDE.md                    # The map plus always-true rules. Keep it short.
├── AGENTS.md                    # Optional. For other agents. CLAUDE.md imports it.
├── ARCHITECTURE.md              # Domain map, layers, dependency directions.
├── CHANGELOG.md                 # What shipped, when, why.
├── docs/
│   ├── decisions/               # ADRs. One file per decision. Never edited, only superseded.
│   │   └── 0001-why-this-database.md
│   ├── specs/                   # Product specs. What we're building and why.
│   │   ├── index.md
│   │   └── some-feature.md
│   ├── plans/
│   │   ├── active/              # Current work. Checkboxes. Survives context loss.
│   │   └── done/                # Archive. Cheap to keep.
│   ├── conventions/             # Long-form standards. Referenced, not always loaded.
│   └── references/              # Vendored llms.txt files for libraries you use.
├── .claude/
│   ├── rules/                   # Path-scoped conventions.
│   │   ├── api.md               # paths: ["src/api/**/*.ts"]
│   │   └── testing.md
│   ├── skills/                  # On-demand workflows and reference.
│   │   └── ship/SKILL.md
│   ├── agents/                  # Custom subagents.
│   │   └── reviewer.md
│   └── settings.json            # Permissions, hooks, worktree config. Committed.
└── src/
    └── ...                      # Domain-first. See Part 6.
```

### The CLAUDE.md template

Rules for this file. Anthropic's documented guidance is to **target under 200 lines per CLAUDE.md file**, because longer files consume more context *and* reduce adherence. I aim for under 150 and treat 200 as the ceiling, which is my preference rather than the official number. For every line ask: *would removing this cause the agent to make a mistake?* If not, delete it.

```markdown
# Project

One or two lines: what this is and who it is for.

Stack: Next.js 15 (App Router), TypeScript, Postgres, Tailwind, Vercel.

## Commands

- Dev: `pnpm dev` (port 3000)
- Test: `pnpm test` (Vitest). Single file: `pnpm test path/to/file.test.ts`
- Typecheck: `pnpm typecheck`
- Lint: `pnpm lint`
- Migrations: `pnpm db:migrate`. Never edit applied migrations, add a new one.

## Layout

- `src/<domain>/<use-case>/` is the unit of change. See ARCHITECTURE.md.
- Cross-domain code goes in `src/shared/`. Nothing else is shared.
- Deeper maps: @ARCHITECTURE.md, docs/decisions/, docs/conventions/

## Rules

- Package manager is pnpm. Never npm, never yarn.
- Validate all external data at the boundary with Zod. Never trust an API shape.
- No `any`. If you need an escape hatch use `unknown` and narrow it.
- Server-only code never imports from `src/ui/`.
- YOU MUST run `pnpm typecheck && pnpm test` before saying a task is done.
  Show me the output, don't just assert it passed.

## Workflow

- Small change (one sentence of diff): just do it.
- Multi-file or unfamiliar code: plan first, write the plan to
  `docs/plans/active/<slug>.md`, then implement.
- Never create a file unless the task requires it. No README per folder,
  no index barrel files, no speculative abstractions.
- When you finish a unit of work, append one line to CHANGELOG.md
  under `## Unreleased`.

## Gotchas

- Row-level security is on for every table. The server client uses the service
  key, the browser client uses the anon key. Mixing them silently returns
  empty arrays instead of erroring.
- Vector similarity search needs an explicit index hint above roughly 50k rows
  or it does a sequential scan and times out.
```

Note what is *absent*: no tutorial, no architecture essay, no directory listing the agent can read itself, no "write clean code." Those either belong in `docs/` or nowhere. Claude Code's `/doctor` will even propose trims now, cutting content it can derive from the codebase (directory layouts, dependency lists, architecture overviews) and keeping pitfalls, rationale, and conventions that differ from tool defaults.

### Where the rest goes

**`.claude/rules/` for path-scoped conventions.** These load only when the agent opens a matching file, so they cost nothing the rest of the time.

```markdown
---
paths:
  - "src/api/**/*.ts"
---
# API rules

- Every endpoint validates input with a Zod schema exported from `./schema.ts`.
- Errors use `AppError`, never bare `throw new Error`.
- Handlers are thin. Business logic lives in the service layer.
```

Rules without a `paths` field load unconditionally. Path-scoped rules trigger when the agent reads a matching file, not on every tool use.

**Skills for workflows you repeat.** The trigger is simple: the third time you paste the same multi-step procedure into chat, it becomes a skill.

```markdown
---
name: ship
description: Run the full pre-merge check and open a PR
disable-model-invocation: true
---
1. `pnpm typecheck && pnpm lint && pnpm test`
2. If anything fails, fix it and re-run. Do not proceed on failure.
3. Review the diff for anything outside the task's stated scope. Flag it.
4. Update CHANGELOG.md under `## Unreleased`.
5. Commit with a conventional-commit message, push, open a PR.
```

Set `disable-model-invocation: true` on anything with side effects. It costs zero context until you type `/ship`.

**Hooks for anything that must happen every single time.** A CLAUDE.md rule is advisory. The agent reads it and tries. A hook is deterministic and fires regardless of what the agent decides.

Put in hooks: format after edit, run the typechecker after edit, block writes to `migrations/` or `.env`, block destructive deletes. If you find yourself writing "NEVER do X" in CLAUDE.md, that is a signal it should be a hook instead.

You do not have to write them by hand. *"Write a hook that runs prettier after every file edit"* works.

**`settings.json` for anything deterministic.** Permissions, denied reads, worktree config. Do not put in CLAUDE.md what a setting enforces mechanically.

### The build-it-over-time rule

Do not set all of this up on day one. It will be wrong and you will have wasted an afternoon. Add each piece when its trigger fires:

| Trigger | Add |
|---|---|
| The agent gets a convention wrong twice | Line in CLAUDE.md |
| You type the same starting prompt repeatedly | A skill |
| You paste the same procedure a third time | A skill |
| A side task floods your context with output | Route it to a subagent |
| Something must happen every time, no exceptions | A hook |
| A second repo needs the same setup | Package it as a plugin |

---

## Part 4. The working loop

Five stages. You gate each one. This is the pattern every serious methodology converges on independently, which is decent evidence it is real.

### Stage 0. Triage

Run the 30-second decision from Part 2. Most tasks skip to Stage 3.

### Stage 1. Explore

Plan mode. Read only, no edits.

```
Read src/reporting/ and understand how we currently calculate the weekly
figures. Also look at how the export job pulls from it.
Don't propose anything yet, just tell me what's there and what surprised you.
```

For anything that would read a lot of files, push it to a subagent so the file contents never enter your main context:

```
Use subagents to investigate how we handle input normalisation and whether
there's an existing scoring utility I should reuse.
```

### Stage 2. Spec

Two modes. Pick based on whether the knowledge is in your head or in the code.

**New feature or product, knowledge is in your head:** use the interview prompt from Part 2.

**Change to existing code, knowledge is in the repo:** ask for a plan directly.

```
I want to add competitor tracking to the dashboard.
What files change? What's the data flow? Write a plan to
docs/plans/active/competitor-tracking.md.

Include: files touched, the interface between the collector and the scorer,
what is explicitly out of scope, and an end-to-end check that proves it works.
Do not include time estimates or phases. Sequence only where one step
genuinely blocks another.
```

That last paragraph is the anti-ceremony clause. Use it every time.

**Write the plan to a file, always.** Long sessions compact their context along the way and conversation history is the first thing to go. A file on disk survives. It is also your recovery mechanism if a session dies, and your checklist for what actually got done.

In Claude Code, `Ctrl+G` opens the plan in your editor so you can cut things directly instead of arguing about them in chat. Use it. Editing the plan is far cheaper than editing the code.

### Stage 3. Implement

Fresh session. Clean context, focused entirely on execution.

```
Implement docs/plans/active/competitor-tracking.md.
Follow existing patterns in src/reporting/scoring/ rather than inventing new ones.
Write tests as you go. Run `pnpm typecheck && pnpm test` and fix failures
before you report back. Show me the test output.
```

Three things to hold to:

- **`/clear` between unrelated tasks.** The kitchen-sink session is the most common failure mode there is.
- **After two failed corrections, stop.** Do not correct a third time. The context is now polluted with failed approaches. `/clear` and rewrite the prompt with what you learned. Anthropic's docs put it plainly: a clean session with a better prompt almost always outperforms a long session with accumulated corrections.
- **Course-correct immediately.** `Esc` stops it mid-action with context preserved. `Esc Esc` or `/rewind` opens the rewind menu and restores conversation and code state. Do not watch it go down a wrong path politely.

### Stage 4. Verify

This is the stage people skip, and it is the one that matters most. Anthropic's framing, quoted exactly: *"Claude stops when the work looks done. Without a check it can run, 'looks done' is the only signal available."*

Escalating options, cheapest first:

1. **In the prompt.** "Run the tests and iterate until they pass." Works today, no setup.
2. **`/goal` condition.** A separate evaluator re-checks after every turn and the agent keeps working until it holds.
3. **Stop hook.** Your check runs as a script and blocks the turn from ending until it passes. Note that Claude Code overrides the hook and ends the turn after 8 consecutive blocks, so it is a gate, not an infinite loop.
4. **Fresh-context reviewer.** A subagent sees only the diff and your criteria, not the reasoning that produced it.

For the reviewer, scope it or you will drown in noise:

```
Use a subagent to review the competitor-tracking diff against
docs/plans/active/competitor-tracking.md.

Check: every requirement implemented, listed edge cases have tests,
nothing outside scope changed. Report only gaps that affect correctness
or the stated requirements. Style preferences are not findings.
```

Always demand evidence over assertion. Test output, the command it ran, a screenshot. Reading evidence is faster than re-running the verification yourself, and it is the only thing that works for runs you were not watching.

### Stage 5. Ship

Commit, changelog, PR. Make it a skill so it is identical every time.

---

## Part 5. Prompt patterns worth memorising

These are the phrasings that consistently change output quality. The pattern across all of them: **name the file, name the constraint, name what done looks like.**

**Point at existing patterns instead of describing what you want.**

> Bad: "add a calendar widget"
>
> Good: "look at how existing widgets are implemented on the home page to understand the patterns. `RankingWidget.tsx` is a good example. follow that pattern for a calendar widget that lets the user pick a month and paginate by year. build it from scratch, no new libraries."

**Give the symptom, the likely location, and the definition of fixed.**

> Bad: "fix the login bug"
>
> Good: "users report login fails after session timeout. check `src/auth/`, especially token refresh. write a failing test that reproduces it first, then fix it."

**Ban the escape hatches explicitly.**

> "Address the root cause. Do not suppress the error, do not add a try/catch that swallows it, do not skip the test."

**Cap the scope in the prompt itself.**

> "Change only what this task requires. If you think something adjacent needs fixing, list it at the end instead of doing it."

This one is worth adding to CLAUDE.md. Unrequested improvements are the number one source of the two-hour session for a fifteen-minute task.

**Kill the ceremony inline.**

> "No phases, no time estimates, no effort scoring. Sequence steps only where one genuinely blocks another."

**Ask a question rather than requesting a change.**

> "Why does the scorer call `normalize()` before dedup instead of after? Is that deliberate?"

Often the answer is that it is fine and you just saved yourself a refactor.

---

## Part 6. Code that stays maintainable

The goal is code that feels like puzzle pieces, where changing one thing does not scare you. That is a real, well-studied property. Five characteristics determine it:

| Characteristic | What it means | What breaks without it |
|---|---|---|
| **Locality** | How many places you touch for one change | Features scatter across helpers and side effects |
| **Blast radius** | Size of unintended consequences | Small edits cause broad regressions |
| **Boundary integrity** | Contracts and responsibilities are explicit | Agent infers the wrong contract from local evidence |
| **Navigability** | How fast someone new finds the right file | Context budget burned exploring irrelevant code |
| **Test scope** | How narrowly you can verify a change | Every change needs a slow full-system check |

The diagnostic: **can a fresh agent find the relevant behaviour, change one bounded area, and run the smallest meaningful check, without guessing?** If not, your codebase is demanding more hidden context than any agent can reliably hold.

### Structure: domain first, then vertical slice

Your top-level `src/` should say what the system *does*, not what framework it uses. Not `controllers/`, `services/`, `utils/`. Instead `billing/`, `identity/`, `reporting/`.

Then inside each domain, one folder per **use case**, not per noun. `changePassword`, not `user`. The use case is the unit of change, validation, and verification.

```
src/
  reporting/
    scoreVisibility/
      command.ts
      scorer.ts
      handler.ts
      test.ts
    exportWeeklyReport/
      query.ts
      handler.ts
      test.ts
  billing/
    refundPayment/
      command.ts
      handler.ts
      test.ts
  shared/
    db/
    telemetry/
```

Why this specifically: the domain folder narrows *where to look*, the slice narrows *what changes*, shared rules stay inside the domain boundary instead of being copied around, and each slice maps to a small test cluster. All five characteristics improve at once.

The tradeoff is real. Cross-cutting concerns get harder to standardise, and changes spanning slices still need coordination. But for AI-heavy codebases the domain-plus-slice hybrid beats both flat slices and deep layered nesting.

### The couplings to actively ban

These are the ones that destroy local reasoning, which is exactly what an agent depends on. Put them in your rules file.

- **Global state coupling.** A module reads or mutates process-wide state (singletons, config registries, mutable globals, ambient context). Retrieval surfaces the file doing the work but not the file that quietly set the state it depends on. Most severe of the lot.
- **Temporal coupling.** Correctness depends on call order. Initialise before use, `begin` before `commit`, populate cache before read. Each step looks valid alone. It only breaks when a caller reorders.
- **Control coupling.** Flags and mode strings that tell another module which branch to run. `isPreview`, `skipValidation`, `"fast"` versus `"safe"`. Signals one abstraction doing several jobs.
- **Semantic coupling through convention.** Two modules agree on a magic string format, a JSON shape, a naming scheme, an implied unit. Nothing in the types reveals it. This is the single most common failure in generated code, where separate files independently "agree" on a format nobody ever defined.
- **Content coupling.** One module reaches into another's internals. Now clients depend on representation, not behaviour, and internal refactors become breaking changes.

### Three things to say no to, repeatedly

**Premature abstraction.** An abstraction earns its keep only when it removes repeated change or protects a volatility that has actually shown up. Otherwise it is one simple path turned into three layers of indirection.

**Premature generalisation.** Worse than abstraction because it creates a false common core. Paths that only *looked* alike diverge under real use, and then the shared layer accumulates flags to preserve the illusion. Let duplication live a little longer until the real axes of variation are visible. Extracting later is cheaper than maintaining the wrong generalisation.

**Premature optimisation.** The danger is not extra code, it is extra invariants. Caches must stay coherent, fast paths must match slow paths, pooled resources must be released. Each one is hidden context an agent has to carry.

For agents all three have a direct token cost. Every extra layer competes with the information that actually determines behaviour. Put this in CLAUDE.md verbatim:

> Do not add abstraction, generalisation, or optimisation for a problem we don't have yet. Duplication is cheaper than the wrong abstraction. If you think something needs abstracting, say so and let me decide.

### Enforce it mechanically, not by asking nicely

This is the part most people skip and it is where the leverage is. The OpenAI team enforces layer dependency directions with custom linters and structural tests, plus what they call taste invariants: structured logging, naming conventions, file size limits. They write the lint error messages to include remediation instructions so the fix lands in agent context automatically.

Their framing is the right one. In a human workflow these rules feel pedantic. With agents they are multipliers, because once encoded they apply everywhere at once. Enforce boundaries centrally, allow freedom locally.

Practically, for a normal-sized project:

- A dependency-direction lint (`eslint-plugin-boundaries`, `import-linter`, `ArchUnit`, depending on stack)
- A file-length lint. Pick a number, 300 lines is reasonable, and hold it
- A pre-commit hook running typecheck and lint
- CI that fails on both

Ask the agent to write all of it. That is exactly the kind of thing it is good at.

### Garbage collection

Agents replicate patterns that already exist in the repo, including the bad ones. Drift is guaranteed, not possible.

The OpenAI team initially burned every Friday, 20% of their week, cleaning up slop. That obviously did not scale. What worked was encoding golden principles into the repo and running scheduled background agents that scan for deviations and open small targeted refactor PRs, most reviewable in under a minute.

At a smaller scale that is one scheduled task, weekly:

```
Scan src/ for deviations from docs/conventions/ and ARCHITECTURE.md.
List the top 5 by risk. Do not fix anything yet.
```

Then pick one or two. Tech debt behaves like a high-interest loan. Continuous small payments beat painful bursts.

---

## Part 7. Memory, plans, and changelog

Four artifacts. Each has one job. Confusing them is why people end up with a bloated CLAUDE.md that nobody trusts.

| Artifact | Who writes it | Job | Update when |
|---|---|---|---|
| `CLAUDE.md` | You | Always-true rules and the map | The agent makes the same mistake twice |
| Auto memory | The agent | Learnings it discovers | Automatic, you audit it |
| `docs/plans/active/*.md` | Agent writes, you edit | Current work, survives context loss | Every plan, every time |
| `CHANGELOG.md` | The agent | What shipped and why | Every completed unit of work |
| `docs/decisions/*.md` | Either | Why, not what. Never edited | Any non-obvious choice |

### Auto memory

Claude Code writes its own notes now, per repository, stored outside your repo at `~/.claude/projects/<project>/memory/`. `MEMORY.md` is an index, and only the first 200 lines or 25KB, whichever comes first, load at session start. Topic files load on demand.

It is on by default. Two things to know: it is machine-local, so it does not sync to your teammates, and you should run `/memory` occasionally to read what it saved. It is plain markdown you can edit or delete. When you tell the agent "remember that the integration tests need a local Redis," this is where it goes.

Do not confuse it with CLAUDE.md. CLAUDE.md is instructions you give. Auto memory is patterns the agent noticed. Both load every session.

### Plan files

Non-negotiable for anything multi-file. Checkboxes, exact file paths, explicit non-goals, and a final end-to-end verification step. It is the recovery mechanism when a session dies and the diff-check when you review.

Move to `docs/plans/done/` when finished. Cheap to keep, and it becomes the answer to "why is this built like this" six months from now.

### Changelog

Keep it dumb. Conventional Commits style, `## Unreleased` at the top, one line per shipped unit. Add "append to CHANGELOG" to your `/ship` skill so it is mechanical, not a thing you remember.

The value is not the file itself. It is that a future session can read it and reconstruct what happened without you explaining.

### Decisions

The one thing that consistently pays off long-term. One file per decision, numbered, never edited. Context, the options considered, what was chosen, what it costs.

Why it matters for agents specifically: an agent reading only the code sees *what* but never *why*. Six months later it will helpfully refactor away a workaround that existed for a real reason. A decisions folder is the cheapest insurance against that.

---

## Part 8. Failure modes and the actual fix

| Symptom | Cause | Fix |
|---|---|---|
| Ignores your CLAUDE.md rules | File too long, rules lost in noise | Cut it down hard. Move to rules or skills. Run `/context` to confirm it even loaded |
| Wanders into unrelated refactors | No scope ceiling in the prompt | Add the scope clause to CLAUDE.md. Give it a plan file with explicit non-goals |
| Two-hour session for a small task | Kitchen-sink context | `/clear` between unrelated tasks. Always |
| Same mistake after three corrections | Context polluted with failures | Stop at two. `/clear`, rewrite the prompt |
| Says done, is not done | No verification loop | Give it a check it can run. Demand output as evidence |
| Reads 200 files and fills context | Unscoped investigation | Scope it, or push it to a subagent |
| Generates plausible but wrong code | No spec, wrong problem | Explore then plan. Point at existing patterns |
| Over-engineers after a review | Reviewer told to find gaps, so it found gaps | Tell the reviewer to flag only correctness and requirement gaps |
| Loses the thread on long builds | Context filled, conversation compacted | Write the plan to a file. Fresh session per phase |
| Rules keep getting violated | You wrote a request, not enforcement | Convert to a hook. Advisory versus deterministic |

---

## Part 9. Cross-tool setup

If you run more than one coding agent, do not maintain two files. `AGENTS.md` is the cross-tool convention read natively by several other agents.

Claude Code reads `CLAUDE.md`, not `AGENTS.md`. Bridge it with an import:

```markdown
@AGENTS.md

## Claude Code

Use plan mode for changes under `src/billing/`.
```

A symlink also works (`ln -s AGENTS.md CLAUDE.md`) if you do not need agent-specific additions. On Windows that needs Administrator privileges or Developer Mode, so use the import instead.

Same rules apply: keep it short, put in commands and boundaries and the one or two architectural decisions that look wrong to an outsider but are intentional. In monorepos, one per package.

One more thing worth doing regardless of tool: keep a gotchas section recording failure patterns as they happen. Problem, effect, fix, prevention. When something appears three times, promote it to a hard rule.

---

## Part 10. What to do this week

Ordered by return on effort. Do not do all of it.

**Day 1, one hour.**
1. Pick your most active repo. Run `/init`, then cut the result down using the template in Part 3.
2. Add the two clauses that fix the most common complaint: the scope ceiling, and the no-ceremony clause.
3. Add one hook: typecheck after every edit.

**Day 2, one hour.**
4. Write `ARCHITECTURE.md`. Domains, layers, allowed dependency directions. One page.
5. Create `docs/plans/active/` and `docs/decisions/`. Make the next plan go in a file.
6. Add a file-length lint and a dependency-direction lint. Have the agent write both.

**Week 2.**
7. Turn your most-repeated prompt into a skill. Then the second one.
8. Add a `/ship` skill with typecheck, test, scope review, changelog, PR.
9. Try the interview prompt on your next new feature. Compare the result to how you would normally start.

**Ongoing.**
10. Every time the agent makes the same mistake twice, add one line. Every time your CLAUDE.md grows past your ceiling, cut something.

**Do not do yet.** Agent teams, parallel worktrees, custom plugins, MCP servers you do not need. Every one of those is a harness component encoding an assumption. Add them when a specific problem forces you to, not because they exist.

---

## The compressed version

- You supply intent, constraints, and the definition of done. The agent supplies implementation. Do not cross the line in either direction.
- Context is the scarce resource. Short instructions, deep docs, progressive disclosure.
- A check the agent can run itself is worth more than any amount of planning ceremony.
- Structure the code so changes stay local. That is what makes it feel like puzzle pieces.
- Advisory rules go in CLAUDE.md. Rules that must hold go in hooks and linters.
- Every process step encodes an assumption about a model limitation. Test those assumptions. Delete what is stale.
- If you can describe the diff in one sentence, skip all of the above and just ask.

---

## Sources

**Anthropic**
- [Best practices for Claude Code](https://code.claude.com/docs/en/best-practices)
- [How Claude remembers your project](https://code.claude.com/docs/en/memory)
- [Harness design for long-running application development](https://www.anthropic.com/engineering/harness-design-long-running-apps), 24 March 2026
- [Agentic coding and persistent returns to expertise](https://www.anthropic.com/research/claude-code-expertise), 16 June 2026

**OpenAI**
- [Harness engineering: leveraging Codex in an agent-first world](https://openai.com/index/harness-engineering/)

**Two caveats on the evidence.** Anthropic's session study measures transcript-inferred success, not real-world outcomes, and cannot tell you whether the code was actually used. Vendor-reported numbers on spec-driven development are directional, not proven. The findings I would bet on are the ones that show up independently across all of these sources: context is the constraint, verification is the lever, and structure beats process.
