Skip to content
/ 16 min read

Longer prompts and louder rules don't steer a coding agent; the codebase does. Twelve audit prompts that fix what the agent finds, what catches its mistakes and how work reaches it, plus when to use tickets and when to let it rip.

Sometimes the work stalls. You've tried the fix several ways, rewritten the prompt, added rules, and it still isn't landing. Each attempt feels like progress, because you are improving something. But it's like cleaning the mud off the tyres of a car stuck in a rut. The tyres come up clean, spin, and pick up the same mud. The effort is real; it's going into the wrong thing. The problem is the ground.

That is pushing on a string. Push one end and it buckles; pull the other and it follows.

Most advice on AI coding is pushing: longer prompts, more rules, more emphasis, more capital letters. The agent still drifts, edits the wrong file, uses a deprecated API, or trusts a doc that stopped being true two years ago.

The alternative is to pull. The agent's behaviour is mostly a function of what it finds when it looks around. Fix the codebase and the same prompt works better. This post is a series of prompts that do that: each one points an agent at your repository's health, not at a feature.

Each section opens with the rut: the symptom you'd otherwise keep fixing. The prompt that follows works on the ground instead. Taken together, they cover what the agent finds when it looks around, the guardrails and feedback that catch its mistakes, the environment it starts in, and the routines that keep all of it firm. The agent's results are a property of that ground, and the ground needs an owner.

Run the token audit in section 9 first to get a baseline, then work through the rest. Better still, have your agent adapt each prompt to your repository before you run it (section 12). Review the diffs. Commit each separately.

1. Optimise the file structure for machine comprehension

The rut: you add file paths to the prompt so the agent stops opening the wrong one. Next week it opens a different wrong one.

An agent navigates by names and paths. It reads a directory listing, guesses, and opens files. Every ambiguous name is a coin flip, and every flat directory of 200 files is a search problem.

What helps:

  • Names that say what the file does. utils.ts, helpers.ts, common.ts, misc/ and index2.ts tell an agent nothing. parse-invoice-line.ts tells it everything.
  • Hierarchy that mirrors the domain, not the framework. billing/invoices/ beats controllers/, services/, models/ scattered across three trees.
  • Progressive disclosure. A short root file points to the areas; each area has a short note on its own rules; the detail lives in the code. The agent loads what it needs, when it needs it.
  • Colocation. Tests, types and the module they describe sit together.
  • One concept, one name. If the code says Customer, Client and Account for the same thing, the agent will treat them as three things.
Audit this repository's file and directory structure for AI-agent comprehension.

Find and list:
1. Ambiguous or generic filenames (utils, helpers, common, misc, data, index variants).
2. Directories with more than ~15 files, or hierarchies deeper than 4 levels.
3. Concepts that share multiple names across the codebase.
4. Related files (module, tests, types) that live far apart.

Then propose a restructure as a table of old path -> new path, with the reason for each move.
Do not move anything yet. After I approve, perform the moves with git mv, update every
import, and run the typecheck and test suite to confirm nothing broke.

2. Run package manager checks

The rut: you remind it, again, that the library has moved on two major versions. It agrees, and the next session forgets.

Models are trained on a snapshot. Your dependencies are not. The agent writes against the API it remembers, which may be two major versions behind what is installed, or a package that is deprecated, abandoned or vulnerable.

There is a second, sharper risk: agents sometimes suggest packages that don't exist, and attackers register those names. This is known as slopsquatting. Treat every dependency an agent adds as untrusted until checked.

Audit this project's dependencies using its package manager.

1. Confirm a lockfile exists, is committed, and matches the manifest.
2. List outdated packages, flagging major-version gaps.
3. Run the ecosystem's vulnerability audit and summarise findings by severity.
4. Identify deprecated, unmaintained (no release in 2+ years) or unused dependencies.
5. Flag any dependency added recently that has few downloads, a very young publish date,
   or a name close to a popular package.
6. For each major-version gap on a package we use heavily, note the breaking changes
   an agent trained on older docs would likely get wrong.

Output a prioritised list. Do not upgrade anything yet.

Point 6 is the useful one. The result becomes a short note in your agent instructions: "We're on v5 of X; v3 patterns in your training data are wrong."

3. Strip legacy docs down to the non-obvious

The rut: you write a rule overriding the old convention. The old doc still says the opposite, at greater length.

An agent can read the code. Documentation that restates the code is pure cost: it consumes context, and it goes stale. Stale docs are worse than none, because the agent believes them.

Keep only what code cannot tell you:

  • Why: the decision, the constraint, the incident behind a strange choice.
  • Gotchas: things that look wrong but are right, and the reverse.
  • Commands: how to build, test, lint and run, exactly.
  • Boundaries: what must never be touched, and what needs a human.

Delete architecture overviews that describe folder contents, internal API listings generated from types, and changelogs masquerading as documentation.

Review every markdown file, README, docs/ folder and agent instruction file in this repo.

For each document, check its claims against the current code and classify it:
- DELETE: restates what the code shows, or is stale/contradicted by the code.
- TRIM: contains some non-obvious content (rationale, gotchas, constraints) among noise.
- KEEP: already non-obvious and accurate.

Rules for what survives: explain why, not what; include exact commands; record only
things an engineer couldn't learn by reading the code in a few minutes.

Show me the classification table first. After approval, delete and trim, and rewrite the
root agent instruction file to under 100 lines, linking to deeper notes only where needed.

4. Give the agent a feedback loop

The rut: the agent says it's done. It isn't. You become the test suite.

An agent that cannot verify its work will guess confidently. One command that typechecks, lints and tests turns a vague instruction into a closed loop.

Make this repository verifiable with a single command.

1. Identify the typecheck, lint, format and test commands that exist.
2. Combine them into one documented entry point (e.g. `npm run verify`) that exits non-zero
   on any failure and runs in under 60 seconds if possible.
3. Fix or quarantine flaky tests, with a note on why.
4. Enable the strictest type-checking settings the codebase can tolerate; list what blocks the rest.
5. Add that one command to the root agent instruction file.

5. Remove dead code

The rut: you add "ignore that folder" to the instructions, because the agent keeps extending a module you thought was retired.

Unused code is a trap with a plausible face. The agent finds it, assumes it matters, and extends it.

Find dead code: unused exports, unreachable branches, unreferenced files, commented-out
blocks, feature flags that are permanently on or off, and TODOs older than a year.
Verify each candidate with a repo-wide search and the test suite. Delete in small commits
grouped by area, so each can be reverted independently.

6. Audit the harness: plugins, skills and MCP servers

The rut: you name the right skill in every prompt, because left alone the agent reaches for the wrong one.

The agent's environment is part of the codebase. Skill descriptions, plugin commands and MCP tool schemas are loaded into context before the agent reads a line of your code. Every addition spends context and competes for the agent's attention.

Common failures:

  • Overlapping skills. Two skills whose descriptions both match "write a document" make triggering a lottery.
  • Bloat. Dozens of installed skills and MCP servers, most never used, each adding tokens to every session.
  • Vague descriptions. A skill is selected on its description alone. If the description doesn't say when to use it, it won't be used, or will be used wrongly.
  • Unvetted provenance. A third-party skill or MCP server is instructions plus, often, executable code, running with your permissions. It is a supply-chain dependency and deserves the scrutiny from section 2.
Audit the agent harness for this project and my user-level configuration.

List every installed plugin, skill, slash command and MCP server, with:
1. Source and maintainer (first-party, team, third-party, unknown).
2. Approximate context cost (description length, number and size of tool schemas).
3. Whether it was used in the last 30 days, if usage can be determined.
4. Overlap: other skills or tools whose descriptions match the same triggers.
5. Permissions and side effects: network access, shell execution, file writes, credentials.

Flag: unused items, overlapping pairs, descriptions that don't state when to use the skill,
and third-party items whose scripts or instructions I should read before trusting.
Recommend remove / merge / rewrite / keep for each. Do not change anything yet.

Scope matters. A skill that applies to one repo belongs in that repo, not in your global configuration.

7. Replace instructions with hooks, and tighten permissions

The rut: a rule you've written down three times gets broken, so you write it a fourth time, in capitals.

Instructions are a push. "Never edit the lockfile by hand" is a request, and the agent can forget it, misjudge it, or lose it in a long session. A pre-tool hook that rejects the edit changes the ground instead: the wrong move simply isn't available.

Rule of thumb: if breaking a rule is costly and checkable by a script, enforce it with a hook. Keep instructions for judgement calls.

Good candidates:

  • After every edit: format the file, then typecheck or lint the affected area. Errors return to the agent immediately, while the context is fresh.
  • Before tool calls: block writes to lockfiles, generated files, .env, applied migrations and CI configuration; block destructive commands (rm -rf, force-push, dropping tables).
  • Before commit: run the verify command from section 4.
  • At the end of a turn: refuse to call the work done if verification fails.

Hooks go wrong in predictable ways: they are slow, they fail silently, their error messages don't tell the agent what to do next, or they have side effects nobody remembers adding.

Audit this project's agent hooks, git hooks and permission settings.

For every hook (agent pre/post tool hooks, git pre-commit/pre-push, stop hooks), report:
1. What it does, what triggers it, and how long it takes.
2. What happens on failure: is the message actionable, does it block, does it fail silently?
3. Side effects (network calls, file mutations, anything touching credentials).

For permissions, list the allow/deny rules and flag:
- Broad allowances (arbitrary shell, unrestricted network, writes outside the repo).
- Rules that are never exercised or contradict each other.

Then propose: instructions in the agent file that should become hooks, hooks that are too slow
or too noisy, and protected paths and commands that currently have no guard. Do not edit yet.

A hook that takes 30 seconds on every edit will be worked around. Keep the per-edit hooks fast and push the slow checks to commit time and CI.

8. Audit CI

The rut: green locally, red in the pipeline. You rerun until it passes.

CI is the backstop for everything above. An agent can pass its local checks and still break the build, and agent-written changes arrive in volume. CI needs to be fast, trustworthy and identical in intent to the local loop.

Check:

  • Parity. CI should run the same verify command as the agent does locally. Two definitions of "passing" will diverge.
  • Speed. A 25-minute pipeline kills iteration. Cache dependencies, parallelise, and run the cheap checks first.
  • Flakes. A flaky test teaches the agent, and you, to ignore red.
  • Required checks. Branch protection should require the checks that matter. A pipeline nobody is forced to pass is decoration.
  • Supply chain. Pin third-party actions or steps to immutable versions, grant the CI token the minimum permissions, scope secrets to the jobs that need them, and be careful with workflows that run on untrusted pull requests.
  • Agent-authored changes. Decide whether CI treats them differently: extra review, restricted secrets, no auto-merge.
Audit this repository's CI configuration.

Report on:
1. Parity: does CI run the same verify command used locally? List any differences.
2. Duration: total and per-job timing, the slowest steps, missing caching, jobs that could run in parallel.
3. Reliability: tests that failed intermittently in recent history, and retry logic that masks failures.
4. Gates: which checks are required by branch protection and which are advisory.
5. Security: unpinned third-party actions/steps, over-broad token permissions, secrets exposed to
   untrusted triggers (e.g. runs on forked pull requests), and anything that executes code from
   a pull request with privileged access.
6. Agent changes: how pull requests authored by an agent are distinguished, reviewed and merged.

Output prioritised findings with a concrete fix for each. Do not modify workflows yet.

9. Treat tokens as a budget

The rut: an hour in, the answers get slower and vaguer. You explain the task again, which makes the context longer still.

Every section above is also a token-efficiency measure. Every token costs you three ways: money, latency and quality. The third is the one people miss. A context stuffed with irrelevant material doesn't just cost more; it dilutes the signal the agent needs, so the answers get worse as well as slower.

Where the tokens go:

  • Always-loaded context. The root instruction file, skill descriptions, MCP tool schemas. Paid at the start of every session, whether or not it's relevant.
  • File reads. Large files, generated files, lockfiles and vendored code that an agent opens because they match a search.
  • Command output. A test run that prints 4,000 lines of passing tests, a build log, a verbose install. The agent reads all of it, and it stays in context.
  • History. Long sessions carry every earlier dead end with them.

The levers:

  • Small, single-purpose files. An agent can read the 60 lines it needs instead of a 2,000-line module.
  • Ignore rules. Keep build output, generated code, vendored dependencies and large fixtures out of the agent's search paths.
  • Quiet commands. Make the verify command print a one-line pass, or only the failures. Verbosity should be opt-in.
  • A stable prefix. Where the tooling caches prompts, a root instruction file that doesn't change between turns is cheaper than one rewritten mid-session. Keep volatile content out of it.
  • Short sessions. One task per session, with a fresh start when the topic changes, beats an ever-growing thread.
  • Delegate noisy work. Broad searches and log analysis can run in a subagent that returns a conclusion instead of the raw material.

Guard against the opposite error. Compressing the instruction file until it drops the non-obvious why defeats the purpose. The target is fewer wasted tokens, not fewer useful ones.

Audit this project for token efficiency. Measure; do not guess.

1. Baseline: how much context is loaded before I type anything (instruction files, skill
   descriptions, MCP tool schemas)? Rank the contributors by size.
2. The 20 largest files an agent is likely to open. Mark generated, vendored, fixture and
   lockfile entries, and suggest splitting or excluding each.
3. Run the verify command and common dev commands. Report output size per command and
   propose quiet modes (summary on success, detail on failure).
4. Check ignore files for gaps: build output, caches, coverage reports, large binaries.
5. List instruction-file content that restates the code or changes frequently.

Output a ranked list of changes by estimated token saving per unit of effort.

Run it before and after the other prompts and record the numbers. They are your evidence that the work paid off.

10. Run architecture audits on a schedule

The rut: no single diff is wrong. The codebase still gets harder to work in every month.

Each agent session solves its task well in isolation, with no memory of the design it is extending. Every diff looks reasonable, so per-change review passes it. The damage is cumulative:

  • A second helper that does what an existing one already does, because the agent didn't find the first.
  • Three patterns for the same job (data fetching, error handling, validation), one per session that touched it.
  • Layer violations: UI code reaching into the database because it was the shortest path.
  • Thin wrappers around wrappers, and abstractions with a single caller.
  • Files that only ever grow, because appending is the lowest-risk edit.
  • Circular dependencies, which make every later change harder to reason about.

This is spaghetti by accretion, and agents accelerate it because they add code faster than people notice.

The fix is a recurring audit, not a heroic rewrite. Pick a cadence that matches your merge rate (monthly, or after any burst of feature work) and keep it small enough that it actually happens.

Use mechanical evidence where you can. Dependency-graph tools find cycles and layer violations, duplicate-code detectors find copy-paste, and git log shows churn hotspots: files changed constantly are usually where the design is failing. Then let the agent interpret the evidence, not guess at it.

Run a codebase architecture audit. Base findings on evidence from tools and git history, not impressions.

1. Dependency structure: circular dependencies, imports that cross intended layer boundaries,
   modules with unusually high fan-in or fan-out.
2. Duplication: near-identical functions, parallel implementations of the same concept,
   multiple patterns for the same job (fetching, validation, errors, config, logging).
3. Size and complexity: files and functions in the top 5% by length or complexity, and files
   that grew most over the last 90 days.
4. Churn hotspots: files changed most often, and files that are routinely changed together
   but live apart.
5. Abstractions: wrappers with one caller, interfaces with one implementation, layers that only delegate.
6. Drift: places where the code contradicts the structure described in the agent instruction file.

For each finding give the evidence, the cost of leaving it, and the smallest refactor that fixes it.
Rank by impact. Propose no more than five changes for this cycle.
Do not refactor yet.

Then run the fixes with discipline:

  • Tests first. If an area lacks coverage, write characterisation tests before restructuring it.
  • Small, separate commits. One refactor per commit, each passing the verify command.
  • No big-bang rewrites. An agent given a whole subsystem to "clean up" produces a new mess with better formatting.
  • Encode the decision. Where a boundary matters, turn it into a lint rule or dependency check that runs in CI (section 8). A rule the build enforces outlasts a paragraph in a document.
  • Record the why. Add only the non-obvious decision to the agent instruction file, so the next session doesn't undo it.

11. Choose the unit of work: ticket, or let the agent rip

The rut: each ticket closes cleanly. The same kind of problem turns up in the next one.

A ticket is a window. An agent handed one optimises for closing it. It cannot see the design the ticket sits inside, so it fixes the symptom where the symptom appears, adds a helper that already exists two directories over, and picks whichever pattern is nearest. Each ticket is correct. The sum is the accretion described in section 10.

That makes the ticket the narrowest push there is. It is the right tool for some work and the wrong one for the rest.

Use a ticket when the change is bounded and the big picture is already encoded:

  • A small defect with a known cause and a failing test that proves it.
  • Work inside one module whose boundaries are enforced by types, lint or CI.
  • A diff small enough that you will actually read it.

Let the agent rip when the change crosses seams:

  • A feature that touches several modules.
  • A refactor, a migration, or deepening a module.
  • Anything where the right answer depends on how the existing code is shaped.

Ripping does not mean a vague prompt. It means a broad brief: the outcome, the constraints, and an instruction to read the codebase before writing anything. Slice the work into tickets after the design exists, not before. Tickets cut from a written design are safe, because each one carries the design with it, even into a fresh session.

I want this outcome: [outcome, in one or two sentences].
Constraints: [what must not change, what must stay compatible].

Before writing code:
1. Read the areas this touches and the agent instruction files that cover them.
2. List the existing helpers, patterns and boundaries that already solve part of this.
3. Propose the design: which modules change, which are reused, what is new and why.
4. Name anything in the design that would add a second way of doing something the codebase already does.

Stop after the design and wait for my approval. After approval, implement in small commits,
each passing the verify command.

Two guards keep tickets honest. First, put the big picture where a ticket-sized agent will find it: domain names, short area notes and enforced boundaries (sections 1, 3 and 7). Second, run the scheduled audit from section 10. A long run of tickets with nobody holding the whole is how a codebase drifts, one reasonable diff at a time.

12. Ask the agent to write the prompt

The rut: a generic prompt audits a stack you don't have, and you spend the session correcting it.

The prompts in this post are generic on purpose. They say "the verify command" and "the package manager" because I can't know your stack. Your agent can. It can read the repository, see that the build is deno task ci and the lockfile is deno.lock, and write the audit prompt with the real names in it.

So don't paste my prompts. Give the agent the goal and have it write the prompt you will run:

I want to run an audit of this repository for [topic: file structure, dependencies, CI, hooks, tokens].
Write the prompt I should give an agent to do that audit well. Do not run the audit.

Before writing it:
1. Read the root agent instruction file and the repo's task runner, CI config and manifest.
2. Use this repo's real commands, paths, tools and vocabulary, not generic placeholders.
3. Include what the audit must produce, how findings are ranked, and an explicit
   "propose only, change nothing" stop.
4. Add checks for the failure modes specific to this repo, not just the common ones.

Output the prompt in a single code block, then list the assumptions you made about this repo.

What you get back is a one-off skill: instructions written for one job in one repository, with the context already baked in. Section 6 warned about permanent skills that load into every session. This is the opposite. It is cut to fit, used once, and discarded unless it earns a place.

Read it before you run it. That is the whole discipline. The agent writes the prompt from what it found, so it inherits its own blind spots, and an unread prompt is an instruction you never reviewed. Check the assumptions list first. A wrong assumption caught here costs nothing; caught after the audit, it costs a diff.

Why it works:

  • The prompt gets specific. "Run the typecheck" becomes the exact command, and "large files" becomes the directories that actually hold them.
  • Reviewing a prompt is cheaper than reviewing a diff. You see what the agent understood about your repo before it touches anything.
  • It is disposable or reusable. Most are one-offs. Save the ones that worked next to the code, and promote any you keep reusing to a real skill scoped to this repo (section 6).

Keep the "propose, change nothing" stop in every audit prompt. If the agent drops it, put it back.

What each prompt fixes

Each prompt reduces the number of wrong things an agent can plausibly do:

ProblemWhat the agent doesWhat fixes it
Ambiguous namesOpens the wrong fileSpecific names, domain hierarchy
Version driftWrites against an old APIPackage audit, version notes
Stale docsTrusts false claimsDelete, keep only the non-obvious
No verificationDeclares success uncheckedOne verify command
Dead codeExtends what nobody usesRemove it
Bloated or overlapping harnessPicks the wrong skill, wastes contextPrune, merge, sharpen descriptions
Rules only in proseForgets or breaks themHooks and permissions enforce them
Weak or divergent CIShips what passes locally but fails in the pipelineParity, speed, required gates
Wasted contextSlower, costlier, less accurate answersSmall files, ignore rules, quiet output, short sessions
Accumulating driftDuplicates, mixed patterns, layer violationsScheduled architecture audits, enforced boundaries
Ticket tunnel visionCloses the issue, ignores the designTickets for bounded fixes, broad briefs for cross-cutting work
Generic promptsAudits against a stack it hasn't readHave the agent write the repo-specific prompt, then review it

None of this is specific to a model or tool. It's the same hygiene that makes a codebase easier for a new engineer, applied with the recognition that an agent is a new engineer on every single session, with no memory of yesterday.

The ground

The twelve sections are four parts of the same ground:

  • What the agent finds (sections 1, 2, 3, 5): file structure, dependencies, docs and dead code. This is what the agent finds when it looks around.
  • Guardrails and feedback (4, 7, 8): the verify command, hooks and permissions, and CI. They make wrong moves unavailable and tell the agent when it is wrong.
  • The agent's own environment (6, 9): skills, plugins, MCP servers and the token budget. This is the context the agent carries before it reads a line of your code.
  • Upkeep and ways of working (10, 11, 12): scheduled architecture audits, choosing ticket or rip, and agent-written prompts. They keep the ground firm and decide how work enters it. Prompts still matter here, but they work because they lean on everything else: a brief or an audit prompt is only as good as the codebase it sends the agent into.

It is maintained, not built once. Codebases drift, dependencies age, docs go stale and harnesses accrete. Ground nobody maintains ruts again, and you're back to cleaning tyres.

Caveats

  • Let the agent propose; review before it executes. Restructures and deletions are where mistakes are expensive.
  • Do one prompt per branch. Mixed diffs are unreviewable.
  • Measure. Pick a few representative tasks, run them before and after, and compare. If a change didn't help, revert it.

When the work stalls, check where the effort is going before you push harder. Stop leaning on the prompt to do the steering. Pull on the codebase, and keep the ground under it firm.

Related by topic

Stop Turning One-Way AI Workflows into Build Systems

Coding agents love modelling human AI workflows like reactive build graphs with hash-pinned staleness and stateful backtracking. Across two real products, that instinct caused most of the usability bugs and shipping drag.

Redundancy Is Not a Property of a File

You can't reason your way to whether a CLAUDE.md, a plugin, or a workflow is still doing anything. Redundancy is a property of a system and a workload, not a file — and the only honest test is ablation, measured per behaviour, against the outcome you actually care about.

The Durable Personal AI Stack Beyond Any Single Tool

Build the durable parts of your personal AI stack first: persistent memory, native execution, and plain-file knowledge. Let orchestration stay swappable.