Skip to content
atif.hossain
Toggle menu
← All writing
·7 min

Docs-as-runtime: making AI coding agents ship production code

Why agents drift on real codebases

An AI coding agent is only as good as its model of the system it's changing. Point one at a large, real codebase with no structured context and it fills the gaps with plausible guesses. The guesses compile, the tests it wrote pass, and the change is still wrong, because it broke a rule that lived only in someone's head.

The fix isn't a bigger prompt. It's treating documentation as something the agent loads at runtime, not something humans read occasionally. If a rule matters, it is written down, in a place the agent is routed to, in a form it can check itself against.

I've worked this way since early 2025, on a multi-tenant SaaS platform and on the small tools I run my own work with. This is the method, stripped to the parts that carry over.

The context layer: four artifacts

Four documents do most of the work. Each answers a question the agent would otherwise guess at.

  • Domain model — what are the things in this system, and how do they relate? An organisation owns projects; a project owns resources; a user acts through a membership. Written in the product's own words, with each term defined once.
  • System invariants — what must always be true, no matter what code runs? "A usage event is counted exactly once." "Access is denied unless something explicitly allows it." These are the rules agents break most, because nothing in a single file tells them the rule exists.
  • ERD — the data model, explicitly: tables, keys, ownership, which columns are derived. Agents read schemas well, but an ERD shows intent the migrations don't, like which table is the source of truth and which is a cache.
  • API contracts — the boundaries between modules: what each one accepts, returns and promises. A contract tells the agent where it may reach and where it must go through an interface.

None of these are new ideas. What changes is who they're written for. A human skims a design doc once; an agent reads it at the start of every session and takes it literally. So the documents have to be short, precise and current, and they have to say things plainly: "never", "always", "only through".

When I specified a metered billing system this way, the invariants document came first: twenty of them, alongside the user stories and functional requirements, before any workflow code existed. The agent then had something better than "build billing" to work from. It had the rules a correct implementation could not break.

Route context, don't dump it

The obvious next move is to paste all of it into one giant instructions file. That fails in two ways: the agent's attention spreads thin across text that has nothing to do with the task, and the file grows until nobody maintains it.

Instead, put an AGENTS.md in every directory that matters, and make each one a router: what this directory is for, what the agent may and may not do here, and which document to read next for which kind of task. The agent starts at the root and follows the chain down to the context its task needs, and no further.

An example of a root router, trimmed:

# AGENTS.md — root router

## Directories
- docs/      → canonical source of truth. Only write here when told to.
- research/  → agent findings. Provisional, never authoritative.
- data/      → raw API output. Never embed it in docs; link to it.

## Routing rules
1. Research tasks → research/
2. A single task's output belongs in one place.
3. Findings move from research/ to docs/ only after human review.

Two things make this work. First, the hierarchy follows intent, not just code layout: "where do research findings go" and "where is the truth" are routing questions, so the router answers them. Second, each level carries a trust level. The agent can write freely in a scratch area, must follow a template in another, and may only propose changes to the canonical docs. Those rules stop an agent from "helpfully" rewriting the source of truth mid-task.

Directory-scoped files also keep the cost down. An agent fixing a collector script reads the collectors' router, not the dashboard's. The context it loads stays proportional to the task.

One source per fact

The fastest way to make an agent unreliable is to tell it the same thing twice in two places, then update only one. Now it holds two versions of the truth and picks whichever it read last.

So every fact lives in exactly one file, and everything else links to it. The strategy doc doesn't repeat the message template; it names the template file. The router doesn't restate the strategy; it says "strategy lives in strategy/, follow it, don't copy it". When something changes, there's one place to edit, and the agent can't find a stale copy because there isn't one.

An example of the rule written as a router instruction:

## Rules
- `strategy/*.md` is the single source of truth for strategy.
  Agents follow it; the dashboard renders the same files.
- Don't restate strategy content (templates, cadence, filters) in this
  file or anywhere else. Link to the doc. To change strategy, edit the doc.

This sounds like documentation hygiene, and it is. The difference is that with agents, the cost of skipping it shows up within the hour instead of within the year.

Invariants that become tests

An invariant written only in prose is a wish. The agent will read it, agree with it, and occasionally violate it anyway. The fix is to write invariants so each one maps to a check that fails loudly.

An example, written so it can be tested:

### INV-04: usage is counted exactly once
For any usage event E, the sum of E's contribution across all
billing periods equals E.units: never zero, never 2 × E.units.
Test: replay the same event batch twice; invoice totals must not change.

Now the invariant does three jobs. It tells the agent the rule before it writes code. It names the test that proves the rule, so the agent writes that test too. And when a later change breaks the rule, the failure message points back to a numbered invariant a human can read, not to an anonymous assertion.

The stronger version is a property test: generate random batches of usage events, replay them in shuffled orders and with duplicates, and assert the invoice totals never change. Agents are good at writing these once the invariant is stated precisely, and bad at inventing them from nothing.

Keep the documents alive

Context documents rot like any other documentation, and rotted context is worse than none, because the agent trusts it. A few habits keep them honest:

  • Edit in place. No -v2 or dated copies; version control is the history. A second copy is a second source of truth.
  • Update the doc in the same change as the code. If a change breaks a documented rule, either the code is wrong or the doc is. Decide which before merging.
  • Put metadata on every doc (title, status, last updated), so both humans and agents can tell a current spec from an abandoned draft.

What still needs a human

None of this removes the engineer. It moves their effort to where it counts.

  • Design calls. Agents are good at executing a decision and poor at making the ones that shape a system: what the invariants are, where the module boundaries go, what to leave out. Those are written by a person, and the quality of everything downstream depends on them.
  • Review. Every change still gets read. The context layer means review is about "is this right?" rather than "what was it even trying to do?", so it's faster, but it isn't optional.
  • Promotion to truth. Agents can draft findings and propose doc changes. A human decides what becomes canonical.

What changes

With the context layer in place, agents stop guessing about the architecture, because it's written down where they look. The gaps that cause hallucinated behaviour close at the source. Sessions produce code that gets reviewed rather than rewritten.

The method is small: four artifacts, routers instead of one huge file, one source per fact, invariants that become tests, and a human who owns the design. It fits a weekend project as well as a platform. The only real cost is writing things down before you build them, which was good practice before agents existed too.

Building something in this space?