All articles
Engineering · 9 min read

How to structure a codebase for AI coding agents: what we replaced when 420k tokens of markdown broke

Adding more rules to a markdown file does not make an AI agent more reliable. Changing the harness does.

A dark architectural control room overlooking a harbour at first light, where a tangled wall of scrolling markdown files on the left is routed through five clean deterministic gates into a structured multi-repo blueprint on the right.
Contents

Every team building seriously with AI coding agents eventually hits the same wall. The setup that felt like magic at 10,000 lines of code starts actively working against you at 100,000.

For the first few months, the playbook seems obvious. Whenever an agent makes a mistake, you add a rule to CLAUDE.md. Whenever you finish a sprint, you append a post-mortem to lessons_learned.md. Whenever you design a feature, you drop a new folder into design_docs/. Whenever you run parallel tasks, you spin up another git worktree.

At Pelaris, we hit the tipping point of that approach at the end of October. We were burning tokens, consuming credits, and spending money needlessly on GitHub Actions, bloated context, and test suites that were running three times for every merge. Worse than the cost, our structure had turned needlessly complex, and because it was complex, it was falling further out of date every week.

We paused feature work for a weekend and shipped an internal infrastructure release we called Harbour. We name all of our releases after the ocean and navigation - First Light, Tideway, Spring Tide, Harbour - partly because I grew up living in the pool and at the beach, and partly because the metaphor holds up. A harbour is the sheltered structure that lets you refit the ship and head back out into open water safely.

The edge-case spiral: why AI agents over-engineer by default

Before looking at file trees and hooks, it helps to name the behaviour that creates the mess in the first place.

The most frustrating habit AI coding agents have is designing for imaginary edge cases and enterprise scale when nobody asked for either. Left to their own devices, agents will take a problem that is used by one person - something that could honestly be HTML over an Excel sheet - and quietly build it on enterprise-grade infrastructure.

I see this constantly when running parallel sessions. An agent will stop mid-build and ask me to clarify a design requirement that makes no sense to me. When I dig into why it is asking, I find that the agent designed a feature to handle an edge case, inside a new helper it invented, to cover an edge case in my original design. It is an edge case on an edge case on an edge case.

Without structural boundaries, every session adds more defensive scaffolding, a parallel utility service, or another 300 lines of documentation explaining the scaffolding. Multiply that across hundreds of pull requests and five repositories, and the codebase accumulates structural debt faster than any human team could type it.

What our first-generation setup actually looked like

Before touching anything in Harbour, we ran a read-only audit across the workspace to measure what our agents were walking into at the start of a session:

  • 420,000+ tokens of root markdown (~1.7 MB): lessons_learned.md alone had grown past 5,300 lines, and data_model.md, features.md, architectural_context.md and conventions.md accounted for another 900 KB between them
  • A split-brain timeline: readme.md told every assistant to read context.md first, while context.md still described Sprint 10 from February and the live product was on Release 1.4.2 in late October
  • 140+ design-doc folders containing over 9,000 files: Raw evaluation JSON dumps and old screenshots sat in the default search path so every ripgrep search drowned in historical noise
  • 350+ git worktrees: Scattered across sibling directories, with more than 320 already merged to main
  • 1,500+ one-off allow rules: Accumulated across project and user settings alongside 105 prose rules in MEMORY.md (sitting at 18.4 KB against a 25 KB cap where lines past the limit truncate silently)
  • Zero lifecycle hooks: None of those 105 prose rules were enforced mechanically
  • Full test suites running three times per merge: Once on the pull request, once on branch push, and once again inside deployment

When you pay for AI through metered plans where token arbitrage hides what a unit costs under the hood, feeding hundreds of kilobytes of stale markdown into agent search loops is a quiet tax on every turn. And as we saw in the 95% enterprise AI failure data, adding faster models on top of a broken process only gives you a faster broken process.

Comparison chart showing the Pelaris workspace before and after the Harbour release: root context dropped from over 420,000 tokens to under 2,500 tokens, active git worktrees from 368 to clean active branches only, settings rules from over 1,500 ad-hoc allows to 40 patterns plus a strict deny list, lifecycle hooks from 0 to 5 shared events, and CI test runs per merge from 3 down to 1

Bringing an enterprise mindset to a startup

People often talk about bringing an entrepreneurial mindset into the enterprise: cutting ceremony, shipping a thin slice, learning from real usage. I spend a lot of my life in large enterprise environments, and I believe in that completely.

What gets talked about far less is how valuable the reverse is. When you are building a company with AI agent squads, you need to bring an enterprise mindset to the startup from day one.

In a traditional early-stage company, human typing speed is the natural rate-limiter. In an AI-native organisation, generation is practically free and agents have zero long-term memory between sessions unless you engineer it. If you do not start with strict governance, security boundaries, and deterministic engineering practice from the beginning, agents will cheerfully route around your architecture by Tuesday afternoon.

“A rule in a markdown file is a suggestion. A lifecycle hook that returns a non-zero exit code is a law.”

The five foundations of the Harbour architecture

Across 2026, a clear consensus has formed among teams running coding agents at scale. OpenAI’s Ryan Lopopolo called it harness engineering when describing how a lean internal team shipped a million-line production codebase with Codex across 1,500 pull requests, and Birgitta Böckeler expanded on the pattern on Martin Fowler’s site. Academic work on Codified Context across 280+ agent sessions reached the same conclusion: when an agent makes the same mistake twice, stop writing paragraphs in a markdown file and upgrade the deterministic environment around the model.

In Harbour, we replaced our entire setup in five layers.

Architectural diagram of the five-layer Harbour harness across five repositories: Layer 1 is a single under-100-line AGENTS.md imported via @AGENTS.md and paired with PRODUCT.md; Layer 2 is path-scoped .claude/rules globs and a generated CODEBASE_MAP.md that load on demand; Layer 3 is five deterministic lifecycle hooks shared from one repository; Layer 4 is a three-rung validation ladder; Layer 5 is automated worktree and CI hygiene

1. One 100-line AGENTS.md, imported everywhere

Claude Code reads CLAUDE.md, while OpenAI Codex, Gemini and Antigravity read AGENTS.md. Worse, placing @docs/conventions.md inside CLAUDE.md expands the entire imported file inline on turn one.

We replaced all of that with a strict rule across all five Pelaris repositories (wayfinder, pelaris-admin, pelaris-io, pelaris-content and pelaris-mcp-server):

  • AGENTS.md holds the canonical context: Hard-capped at 100 lines containing our mission, engineering principles, exact build and test commands, and pointers to deeper docs
  • CLAUDE.md is a single line: @AGENTS.md, so every assistant reads the exact same words from one file
  • PRODUCT.md sits in the main app repo: Capped at 150 lines defining what Pelaris is, user personas, subscription tiers, our team-sport wedge, and a one-line-per-feature index

2. Path-scoped rules and an auto-generated codebase map

An agent editing a marketing page in Astro does not need 50 KB of Firestore security conventions or Flutter widget rules in working memory. We moved domain rules into .claude/rules/*.md using YAML paths: frontmatter globs, which sit at zero token cost until the agent touches matching files:

Context LayerFile / MechanismWhen It LoadsToken Cost on Unrelated TasksWhat It Prevents
Always-On CoreAGENTS.md (via @AGENTS.md) + PRODUCT.mdEvery session start~1,800 tokens totalSplit-brain product assumptions, wrong CLI commands, scope creep
Path-Scoped Rules.claude/rules/critical-systems.md, workout-engine.md, growth-content.md, windows.mdOnly when reading/editing matching file globs0 tokensTouching privacy scrubbers, ID generators, billing or voice copy without area invariants
Reuse Inventorydocs/CODEBASE_MAP.md (auto-generated by script)Linked on demand before creating new services/widgets0 tokens at startup (~400 lines when read)Agents writing a duplicate date formatter, chart helper or Cloud Function
Design Lifecycledesign_docs/<stream>/README.md (60-line cap, status frontmatter)Only when working on that stream0 tokensGrepping through 9,000 dead planning files or re-asking settled decisions

A short script scans our 127 Dart services, 86 shared widgets, 143 Cloud Function services and 39 coach tools, extracts the file path and its first doc-comment line, and writes docs/CODEBASE_MAP.md. Before an agent writes a new helper, it must check the map and name the existing service it is extending.

3. Deterministic hooks over append-only prose

We moved 105 prose memory rules out of markdown and into five hook events (SessionStart, PreToolUse, PostToolUse, PostToolUseFailure and Stop) committed in .claude/settings.json and backed by a 136-case self-test suite in pelaris-content/harbour/hooks/:

  • Never put heavy analyzers in PostToolUse: PostToolUse fires concurrently during parallel edits, which spawns colliding analyzer processes. PostToolUse now runs only fast single-file dart format and logs the command, exit code and commit SHA. flutter analyze --no-fatal-infos runs once per turn in the Stop hook behind a lock file
  • Block dangerous commands before they run: PreToolUse blocks direct pushes to main, blocks local firebase deploy, blocks live-AI evaluation runners outside emulators, and refuses git worktree remove until Windows node_modules junctions are cleanly unlinked
  • Evidence must be written by tools, not claimed by agents: Following Anthropic’s research on verification loops, hooks log every command execution to ledger.jsonl, and pull requests cite the ledger line or CI run link verbatim

4. Right-sizing review: the three-rung validation ladder

Forcing heavyweight ceremony onto a ten-line copy fix wastes tokens and trains teams to skip review. We replaced one-size-fits-all panels with a three-rung validation ladder:

  • Rung 0 (Self-check): Copy tweaks, small isolated fixes and read-only research use local deterministic checks and hooks only
  • Rung 1 (One fresh reviewer): Standard features and protected paths are checked by a fresh agent session that did not write the code
  • Rung 2 (Two lenses): Architecture, privacy scrubbing, deterministic IDs, server-side generation and billing are reviewed through two independent lenses plus a cross-model review from Gemini

5. Built-in entropy collection inside /ship and CI

To make sure the mess could not quietly grow back, we built hygiene directly into SessionStart and our /ship skill:

  • SessionStart drift checks: Prints a one-line warning if MEMORY.md creeps past 15 KB, if AGENTS.md passes 120 lines, if the checkout is behind origin/main, or if merged worktrees sit around older than seven days
  • /ship worktree pruning: Automatically removes merged git worktrees older than seven days after verifying clean status and unlinking Windows junctions
  • Single-pass CI: Running the four-way sharded Flutter test suite on the PR and having deploy verify the proven PR result cut PR CI to roughly 12 minutes and deploy time to 11 minutes

“When an agent makes the same mistake twice, stop writing paragraphs in a markdown file and upgrade the harness.”

What to do if your AI codebase is starting to creak

If your context is starting to fight you, treat the cleanup as one clean weekend cut rather than a phased migration:

  • Measure your startup tax: Anything over 100 lines in your root CLAUDE.md or AGENTS.md should become a path-scoped rule in .claude/rules/ or a deterministic hook
  • Stop using lessons_learned.md as a graveyard: If a linter, architectural fitness test, or PreToolUse / Stop hook can check a rule, delete the prose
  • Give agents a map of what exists: Generate a compact CODEBASE_MAP.md so agents extend existing foundations instead of inventing parallel helpers
  • Pull agents back from imaginary edge cases: Require agents to name the existing service they are extending before writing anything new, and make them stop and ask in three bullet points before introducing new infrastructure

Consistency and continual improvement win in sport, in careers, and in software. With AI agents, continual improvement means improving the harbour they sail out of, so every build leaves the system cleaner than it found it.

aiai-coding-agentsclaude-codeharness-engineeringcontext-engineeringsoftware-architectureagents-mddevopsengineering-leadershipenterprise-architecturepelarisci-cd
Share

Read next

BH

Bradley Hunt

AI, engineering & leadership