alberto marturelo
← Volver

2 de julio de 2026

Context-First Development (CFD): A Methodology for AI-Assisted CLI Development

por Alberto

"The most expensive code an AI agent can write is code written without context."

Introduction: The Problem Nobody Wants to Admit

There's an elephant in the room of AI-assisted development. Every time you start a new session with your AI agent — whether it's Claude Code, Gemini CLI, or any terminal tool — you start from scratch. The model doesn't remember the architectural decisions you made yesterday. It doesn't know why you chose PostgreSQL over MongoDB. It doesn't understand that your team decided to use the Repository pattern for specific testability reasons.

The result is predictable: the agent generates technically correct but contextually incorrect code. And you end up spending more time correcting the model than writing the code yourself.

This problem scales in direct proportion to project size. In a 50-file project, the model can scan everything and understand the structure. In a 500-file project, scanning consumes tokens exponentially and the model starts losing coherence. In a 5,000-file project — where any serious production project lives — the model is essentially blind.

The solution isn't a model with more context. GPT-4 Turbo has 128K tokens. Claude has 200K. Gemini reaches 2M. And yet, the problem persists. Because the problem isn't context capacity — it's context quality.

This article proposes Context-First Development (CFD): a methodology for structuring code repositories so that AI agents can operate with persistent, accurate, and efficient context. It's not a framework. It's not a tool. It's a work discipline that transforms your repository into a living knowledge base that any agent can consume.


The Current Landscape: What Exists and Why It's Not Enough

Before proposing something new, let's understand what the industry has built so far.

CLAUDE.md and the First Generation of "Agent Instructions"

Anthropic introduced the concept of CLAUDE.md as an instruction file that Claude Code reads automatically when starting a session. The idea is simple: a Markdown file at the project root that tells the model how to behave.

Anthropic's official best practices recommend keeping the file between 100-200 lines and applying a strict rule: "For each line, ask yourself: would removing this cause Claude to make mistakes? If not, cut it."

The problem is that most CLAUDE.md files end up being lists of build and lint commands. An academic study from September 2025 analyzed 253 CLAUDE.md files from 242 repositories and found that 77.1% only contained Build/Run instructions, 71.9% implementation details, and a mere 8.7% mentioned security. The industry is using the most powerful context file available to do what a Makefile already did.

AGENTS.md: The Standardization Attempt

In July 2025, Sourcegraph's Amp team launched AGENTS.md — an open format designed to be a "README for agents" that works with any tool: OpenAI Codex, Google Jules, Cursor, Aider, Gemini CLI. By February 2026, over 40,000 open source repositories had adopted it.

AGENTS.md proposes one file per directory level (ideal for monorepos), with a recommended limit of 150 lines and content oriented toward: project description, architecture, commands, conventions, and navigation hints.

It's a good step toward interoperability, but it suffers from the same fundamental problem: it's a static file that doesn't scale with project complexity.

Cole Medin's Template: Practical Context Engineering

Cole Medin published a template repository that goes a step further. Its structure includes:

  • CLAUDE.md with project rules
  • .claude/commands/ with custom slash commands
  • examples/ with patterns for the model to follow
  • PRPs/ (Product Requirements Prompts) — specifications the model executes

This approach is significantly more sophisticated because it introduces the idea of commands as workflow and examples as context. But it remains a template that each team must adapt without a clear methodology for when and how to evolve each piece.

Spotify: 1,500 PRs in Production with Claude Code

Spotify published a three-part series in November-December 2025 documenting their experience with coding agents in production. Key findings:

  • Claude Code was their top-performing agent
  • They executed ~50 automated migrations
  • Over 1,500 AI-generated PRs merged
  • Critical discovery: Claude Code works better with end-state descriptions rather than step-by-step instructions

This last point is fundamental and we'll incorporate it into CFD: context should describe the "what" and "why", not the "how".

ADRs: The Missing Piece

Chris Swan wrote in July 2025 about the connection between Architecture Decision Records and AI agents. His central argument: ADRs provide structured, natural-language context that is inherently LLM-friendly. Each documented decision includes context, evaluated alternatives, consequences, and status — exactly what a model needs to understand why the code is the way it is.

Josh Rotenberg published a complete ADR system designed specifically for Claude integration. Piethein Strengholt built an agent that automates ADR creation. But nobody has integrated ADRs as the central piece of an AI development methodology.

Addy Osmani: The "Specs First" Workflow

Addy Osmani, engineering lead at Google Chrome, proposed a workflow that can be summarized as: specs first, then plan, then code. He also coined the 70/30 rule: AI completes ~70% of the task, but the last 30% (edge cases, production readiness) requires human expertise.

The Academic Research

Three fundamental papers from 2025:

  1. "On the Use of Agentic Coding Manifests" (arXiv:2509.14744) — Empirical analysis of 253 CLAUDE.md files.
  2. "Agent READMEs: An Empirical Study" (arXiv:2511.12884) — 2,303 context files from 1,925 repositories. Conclusion: these files are "not static documentation but complex, difficult-to-read artifacts that evolve like configuration code."
  3. "Context Engineering for Multi-Agent LLM Code Assistants" (arXiv:2508.08322) — Proposes multi-agent architectures with semantic retrieval.

Memory Banks: Persistent State Between Sessions

Cline's Memory Bank (adopted and extended by Roo Code and others) pioneered structured, file-based memory for coding agents: a directory of markdown files — project brief, active context, progress, decision log — that the agent reads at session start and updates at session close. Mechanically, this is CFD's closest neighbor, and it deserves the credit: same core insight (context must live outside the session), same medium (versioned markdown), same rituals (read at start, write at close).

CFD builds on that shared foundation with two additional commitments. First, decisions as portable first-class artifacts: full ADRs with rejected alternatives — the memory of why not, which is what stops an agent from re-proposing an option the team already discarded. A decision log line records what was chosen; an ADR records what was chosen over what, and at what cost. Second, shared work state lives in the external tracker, not in the memory files — which keeps the memory per-developer and the team coordination in a tool built for it. A developer comfortable with a Memory Bank workflow will find CFD immediately familiar; the two schools agree on far more than they differ on.

Spec-Driven Development: GitHub Spec Kit and Kiro

In 2025 a second school consolidated: spec-driven development. GitHub's Spec Kit drives a specify → plan → tasks pipeline with human review gates; AWS's Kiro builds requirements, design, and task documents per feature before any code is written. Both are rigorous exactly where CFD is deliberately light: the inside of a large feature. For multi-session work, a reviewed spec catches requirement gaps that a lightweight issue template will not.

The two govern different scopes. Spec-driven governs the feature; CFD governs the project between features — decision memory, the conventions ratchet, session continuity. They compose naturally: run a spec pipeline for a large epic while CFD carries the cross-feature "why"; CFD's issue template is a lightweight spec, and its own rule that Estimated sessions > 1 forces decomposition is precisely the point where reaching for a fuller spec pays for itself.

Multi-Agent Orchestration: Role Agents and Agent Teams

A third school orchestrates multiple agents: the BMAD-Method defines agile role agents (analyst, PM, architect, developer) that hand structured artifacts to each other, and agent CLIs now ship native subagents and workflow fan-out. This school solves throughput and separation of concerns at scale.

CFD deliberately defines no agent-to-agent handoff. There is one loop, and the developer sits inside it as orchestrator and observer — a per-session human checkpoint, consistent with CFD's drift thesis: adherence degrades as context accumulates, and a human in the loop catches drift before it compounds across a chain. This is a scope choice for CFD's audience (individuals and small teams supervising real production code), not a judgment on orchestration. The approaches also converge more than they compete: a well-formed CFD issue — context, target paths, ADRs to load, pattern to mirror, acceptance criteria — is exactly the self-contained handoff package an orchestrated agent needs. Teams that outgrow the single loop can parallelize CFD sessions over independent issues without changing a single artifact.

What's Missing

Each of the above solves its slice well: instruction files standardize behavior, memory banks persist state, spec pipelines de-risk large features, orchestration buys throughput. What none of them assembles is a cohesive, CLI-first methodology that an individual developer or small team can adopt tomorrow — persistent decision memory with rationale, tracker-based work units, token discipline, and a human-supervised loop — and that scales from a 10-file project to a 10,000-file one.

That's Context-First Development.


Context-First Development: The Six Principles

CFD is built on six non-negotiable principles. These aren't suggestions — they're design constraints.

Principle 1: Context Before Code

Before writing the first line of code in any session with an AI agent, context must be resolved. This means the model must be able to answer these questions without scanning source code:

  • What is the project's architecture?
  • What decisions have been made and why?
  • What conventions are followed?
  • What is the current state of work in progress?

If the model needs to read 50 files to answer any of these questions, your context is broken.

Principle 2: Single Source of Truth (SSOT)

Every piece of project knowledge must exist in exactly one place. If the architecture is documented in CLAUDE.md, in an ADR, in a README, and in code comments, you have four sources that will inevitably desynchronize. The model won't know which to trust.

CFD defines a clear hierarchy: the root file (CLAUDE.md or AGENTS.md) is an index that references specialized documents. It never duplicates content.

Principle 3: Hierarchical Context Architecture

Context is organized in layers, from most general to most specific:

1Level 0: Root file (CLAUDE.md / AGENTS.md) → ~100-150 lines
2Level 1: Domain documents (docs/) → Architecture, stack, conventions
3Level 2: Decisions (docs/decisions/) → Individual ADRs
4Level 3: Module context (CLAUDE.md per folder) → Area-specific instructions

The model only needs to read Level 0 to orient itself. It dives into lower levels when the task requires it. This minimizes token consumption per session.

Principle 4: Decisions as First-Class Citizens

Every significant technical decision is documented in an ADR (Architecture Decision Record) with a strict format:

1# ADR-NNN: Decision Title
2
3## Status
4Accepted | Superseded by ADR-XXX | Deprecated
5
6## Context
7What is the issue that we're seeing that is motivating this decision?
8
9## Decision
10What is the change that we're actually doing?
11
12## Alternatives Considered
13What other options were evaluated and why were they rejected?
14
15## Consequences
16What becomes easier or more difficult to do because of this change?

This isn't bureaucracy — it's persistent memory. When you start a new session and the model reads docs/decisions/007-use-repository-pattern.md, it instantly understands why the code is structured that way. Without the ADR, the model might suggest refactoring toward a different pattern, wasting your time and its tokens.

Principle 5: English as Context Language

All technical context is written in English. This isn't elitism — it's token efficiency.

LLM tokenizers (both Anthropic's and Google's) are optimized for English. The same information in Spanish can consume 20-40% more tokens than in English. In a context file that's loaded in every session, that adds up quickly.

Practical rule: code, file names, ADRs, context documents, and CLAUDE.md are written in English. PR comments and team communication can be in the team's language.

Principle 6: Automation Through Slash Commands

Repetitive context maintenance tasks are automated through custom slash commands. You don't depend on someone "remembering" to update a document — the agent itself executes commands that generate and update context.

The commands CFD ships:

  • /session:start — Orient in ~1k tokens from the status file and the decision index
  • /session:close — Update status, capture corrections, stage docs with the code
  • /project:init — Initialize the context structure in an existing project
  • /decision:new — Create a new ADR from a discussion
  • /issue:new — Create a self-sufficient work unit in the tracker
  • /issue:start — Load an issue and its ADRs as the focus of the session
  • /review:pr — Review a PR against ADRs, conventions and acceptance criteria
  • /context:validate — Audit context integrity and report PASS/WARN/FAIL

A command still depends on someone invoking it, and a ritual that survives only on discipline is the first thing dropped under deadline pressure. So the commands are backed by a mechanical layer: a SessionStart hook that injects the status file and the decision index automatically, a commit-time guard that refuses to stage code without staging the status update, and a CI check that annotates — never blocks — a pull request that changes code without touching context. The commands stay the portable source of truth; the hooks are the enforcement.


The Knowledge Architecture: Directory Structure

A project following CFD has the following context structure (coexisting with source code):

1project-root/
2├── CLAUDE.md # Root context file (Level 0)
3├── docs/
4│ ├── ARCHITECTURE.md # Architecture overview
5│ ├── STACK.md # Tech stack and versions
6│ ├── CONVENTIONS.md # Code conventions and style
7│ ├── CURRENT_STATUS.md # Current project status (WIP)
8│ └── decisions/
9│ ├── _index.md # Decision index with status
10│ ├── 001-initial-architecture.md
11│ ├── 002-database-selection.md
12│ ├── 003-auth-strategy.md
13│ └── ...
14├── .claude/
15│ ├── commands/
16│ │ ├── session-start.md # /session:start
17│ │ ├── session-close.md # /session:close
18│ │ ├── project-init.md # /project:init
19│ │ ├── new-decision.md # /decision:new
20│ │ ├── issue-new.md # /issue:new
21│ │ ├── issue-start.md # /issue:start
22│ │ ├── review-pr.md # /review:pr
23│ │ └── validate-context.md # /context:validate
24│ ├── hooks/
25│ │ ├── session-start-context.sh # injects status + decisions
26│ │ └── guard-commit-context.sh # blocks code staged without status
27│ └── settings.json
28└── src/ # (or lib/, app/, etc.)
29 ├── feature-a/
30 │ └── CLAUDE.md # Module-specific context
31 ├── feature-b/
32 │ └── CLAUDE.md
33 └── ...

The Root File: CLAUDE.md

This is the entry point. The model reads it automatically when starting a session. It should be a map, not an encyclopedia.

1# Project: [project-name]
2
3## What This Project Does
4[2-3 sentences. What problem does it solve? Who uses it?]
5
6## Context Map (read on demand, not upfront)
7- Architecture: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
8- Tech stack: [docs/STACK.md](docs/STACK.md)
9- Conventions: [docs/CONVENTIONS.md](docs/CONVENTIONS.md)
10- Current status: [docs/CURRENT_STATUS.md](docs/CURRENT_STATUS.md)
11- Decisions index: [docs/decisions/_index.md](docs/decisions/_index.md)
12
13## Build & Run
14- Install: `[command]`
15- Dev: `[command]`
16- Test: `[command]`
17- Lint: `[command]`
18
19## Critical Rules
20- Read `docs/CONVENTIONS.md` before writing or editing code — not at
21 session start, at first-edit time.
22- [Rule 1: e.g., "Never modify the migration files directly"]
23- [Rule 2: e.g., "All API endpoints must have integration tests"]
24
25## When Context and Code Disagree
26Precedence: **code is the truth about WHAT the system does; ADRs are the
27truth about WHY; `docs/` describes both and can go stale.** If a document
28contradicts the code, STOP and flag the conflict — do not silently trust
29the document, and do not "fix" correct code to match a stale one.

Use plain Markdown links here, not @path references. In Claude Code an @path inside CLAUDE.md is an eager import: the entire referenced file is injected into context at the start of every session. Writing @docs/ARCHITECTURE.md in the root file does not keep it compact — it silently turns the index back into the encyclopedia, which is exactly what Principle 3 exists to prevent. Links are lazy: the agent follows one only when the work requires it, and /session:start performs the two orientation reads explicitly.

ARCHITECTURE.md

1# Architecture Overview
2
3## System Diagram
4[ASCII diagram or reference to an image in assets/]
5
6## Layer Structure
7- **Presentation**: [framework, patterns]
8- **Domain**: [business logic organization]
9- **Data**: [persistence strategy, repositories]
10
11## Module Map
12| Module | Purpose | Key Files |
13|--------|---------|-----------|
14| auth | Authentication & authorization | src/auth/ |
15| users | User management CRUD | src/users/ |
16| ... | ... | ... |
17
18## Data Flow
19[Description of how data flows through the system]
20
21## External Dependencies
22| Service | Purpose | Docs |
23|---------|---------|------|
24| Stripe | Payments | [link] |
25| ... | ... | ... |

CURRENT_STATUS.md

This file is dynamic. It's updated at the end of every work session. It's the first thing the model reads (via the reference in CLAUDE.md) to know what was happening.

1# Current Project Status
2
3Last updated: 2026-02-19
4
5## In Progress
6- [ ] Implementing user profile API (#142)
7 - Endpoint created, missing validation tests
8 - Blocked by: Decision on email validation strategy (see ADR-015)
9
10## Recently Completed
11- [x] Database migration for user preferences (#138)
12- [x] Auth middleware refactor (#135)
13
14## Known Issues
15- Performance degradation in search endpoint when > 1000 results
16- Flaky test in auth.integration.test (timing issue)
17
18## Next Priorities
191. Complete user profile API
202. Address search performance issue
213. Begin notification system (ADR pending)

The Decision Index: decisions/_index.md

1# Architecture Decision Records
2
3| ID | Title | Status | Date |
4|----|-------|--------|------|
5| 001 | [Initial architecture](001-initial-architecture.md) | Accepted | 2026-01-15 |
6| 002 | [Use PostgreSQL](002-database-selection.md) | Accepted | 2026-01-16 |
7| 003 | [JWT auth strategy](003-auth-strategy.md) | Superseded by 004 | 2026-01-20 |
8| 004 | [Switch to session auth](004-session-auth.md) | Accepted | 2026-02-10 |

The Daily Routine: The CFD Workflow

This is the practical part. CFD defines a daily routine with three clear phases.

Phase 1: Session Start (2-3 minutes)

Every work session with the agent begins with a context ritual. This is not optional.

1# 1. Sync with the remote repository
2gh repo sync
3
4# 2. Review project state (PRs, issues)
5gh pr list --state open
6gh issue list --label "in-progress"
7
8# 3. Start a session with Claude Code
9claude
10
11# 4. Inside Claude, run the start routine
12> /session:start

The slash command /session:start is defined in .claude/commands/session-start.md:

1Read the following files in order, then produce a brief summary:
21. docs/CURRENT_STATUS.md - What's in progress, blocked, and next
32. docs/decisions/_index.md - Recent decisions that might affect current work
4
5Then state:
6- What was being worked on at the last session close
7- What's blocked and why
8- What should be the focus of THIS session
9
10If CURRENT_STATUS.md references an in-progress issue by number, also run
11`gh issue view <n>` and surface its title and acceptance criteria.
12
13Do NOT read source code files yet. Orient in O(1k) tokens, not O(50k).
14Source code reading happens after the focus is chosen.

This command consumes ~500-800 tokens instead of the 10,000-50,000 that scanning source code would cost. That's the difference between a sustainable workflow and one that burns through your API budget.

Phase 2: Development (the main cycle)

During development, the flow follows a disciplined pattern:

Before implementing: Clarify and decide

1# If a significant technical decision arises
2> /decision:new

The command /decision:new in .claude/commands/new-decision.md:

1I need to document a new architectural decision. Guide me through the following:
2
31. Ask me what decision needs to be made
42. Help me articulate the context (what problem are we solving?)
53. Propose 2-3 alternatives with pros/cons
64. Once I choose, generate a new ADR file in docs/decisions/ following this format:
1# ADR-[next number]: [Title]
2
3## Status
4Accepted
5
6## Date
7[today's date]
8
9## Context
10[What I described]
11
12## Decision
13[What was chosen]
14
15## Alternatives Considered
16[The alternatives we discussed]
17
18## Consequences
19[What changes as a result]

Then update docs/decisions/_index.md with the new entry.

1#### During implementation: Work in atomic blocks
2
3CFD recommends implementation sessions focused on **one atomic task** at a time. This isn't basic productivity — it's context management. An AI agent works better when it has a clear, scoped instruction than when it has a list of 10 things to do.
4
5```bash
6# Bad: vague instruction that scatters context
7> "Implement the notification system"
8
9# Good: atomic instruction with explicit context
10> "Create the notification repository interface in src/notifications/domain/.
11 Follow the repository pattern we use (see ADR-001).
12 Look at src/users/domain/user_repository for reference."

When the agent gets it wrong: Don't correct — document

One of the most common mistakes when working with AI agents is manually correcting code without updating context. If the model generates something incorrect, it will likely do it again in the next session because the context doesn't say it's incorrect.

1# The model generates a singleton where it should use dependency injection
2
3# Bad: you fix the code manually and move on
4
5# Good: you document the convention
6> "That's incorrect. We use dependency injection, never singletons.
7 Please fix the code AND add this rule to docs/CONVENTIONS.md
8 under the 'Patterns' section."

Now the convention is persisted. Next session, the model reads it automatically.

Phase 3: Session Close (3-5 minutes)

Before closing the session, the agent updates the project status. This is non-negotiable in CFD.

1# Run the close routine
2> /session:close
3
4# If there are changes to commit
5gh pr create --title "feat: notification repository" --body "..."

/session:close updates docs/CURRENT_STATUS.md, captures any correction you made during the session as a rule in docs/CONVENTIONS.md, proposes ADRs for decisions that were taken informally, and stages the documentation in the same commit as the code — so context and code can never land separately.

The session close produces a diff in CURRENT_STATUS.md that is essentially a session log. This creates natural traceability:

1# View project evolution over time
2git log --oneline -- docs/CURRENT_STATUS.md

GitHub CLI Integration: The Complete Flow

GitHub CLI (gh) is a fundamental piece of CFD because it connects repository context with the team workflow.

Issues as Work Units

Context, decisions and in-flight state live in the repository. Tasks do not. They live in a persistent, agent-readable tracker — canonically GitHub Issues — with a fixed body template so that any session can parse a work unit at constant token cost instead of reverse-engineering it from a prose description.

The template is not a suggestion; /issue:start parses by section header, so the section names and their order are part of the contract:

1## Context
2What triggered this, and what the user-visible outcome is.
3
4## Target
5- Files / dirs: src/notifications/domain/notification-repository.ts (new file)
6- Pattern to mirror: src/users/domain/user-repository.ts
7
8## ADRs to load
9- [ADR-012](docs/decisions/012-notification-system.md)
10
11## Acceptance criteria
12- [ ] NotificationRepository interface in the domain layer
13- [ ] PostgreSQL implementation in the data layer
14- [ ] Integration test against a real test database
15
16## Estimated sessions
171

Four of those sections carry most of the weight. Target tells the agent where the work goes, so it stops hunting. Pattern to mirror names an existing file to copy in shape and naming — one skim replaces a paragraph of conventions. ADRs to load is a pre-reading list, so the session opens with the right constraints already in scope instead of discovering them halfway through. And Estimated sessions is a tripwire: anything above 1 must be decomposed into sub-issues before work starts, because a task that cannot fit in one session cannot be handed off cleanly either.

You don't write this by hand. /issue:new interviews you for each field, refuses to continue if a decision the task depends on isn't an ADR yet — it sends you to /decision:new first — and then creates the issue:

1> /issue:new

Picking the work up is the mirror image:

1> /issue:start 42

That command fetches the issue, refuses to proceed if a required section is missing rather than guessing, reads the listed ADRs, skims the pattern file for shape, and reads target files only when they already exist and will be modified. And if docs/CURRENT_STATUS.md already references an in-progress issue, /session:start loads it for you — the two entry points converge on the same readiness state.

The principle is tracker-agnostic. Linear, Jira and Asana all qualify if their CLI can create, view, list by milestone, and edit. The body template stays; only the CLI changes.

Pull Requests with Traceable Context

1# Create a PR that references decisions and context
2gh pr create \
3 --title "feat(notifications): add notification repository" \
4 --body "## Summary
5Implements the notification repository following ADR-012.
6
7## Changes
8- Added NotificationRepository interface
9- Added PostgresNotificationRepository implementation
10- Added unit and integration tests
11
12## Decision References
13- ADR-012: Notification system architecture
14- ADR-001: Repository pattern convention
15
16## Testing
17\`\`\`bash
18npm test -- --grep notification
19\`\`\`"

Context-Assisted Code Review

When reviewing a PR from another team member (or from an agent):

1# View the PR with its context
2gh pr view 87
3
4# Inside Claude Code, review with project context
5> Review PR #87. Read the PR description first, then check:
6 1. Does it follow our conventions in docs/CONVENTIONS.md?
7 2. Is it consistent with the referenced ADRs?
8 3. Are there missing tests per our testing standards?
9 Use `gh pr diff 87` to see the changes.

Automation with GitHub Actions

CFD recommends a validation workflow that checks context integrity:

1# .github/workflows/context-validation.yml
2name: Context Validation
3on:
4 pull_request:
5 paths:
6 - 'src/**'
7 - 'docs/**'
8 - 'CLAUDE.md'
9
10jobs:
11 validate-context:
12 runs-on: ubuntu-latest
13 steps:
14 - uses: actions/checkout@v4
15
16 - name: Check CURRENT_STATUS is updated
17 run: |
18 if git diff origin/main --name-only | grep -q "^src/"; then
19 if ! git diff origin/main --name-only | grep -q "docs/CURRENT_STATUS.md"; then
20 echo "::warning::Source code changed but CURRENT_STATUS.md was not updated"
21 fi
22 fi
23
24 - name: Validate ADR index
25 run: |
26 # Check that all ADR files are listed in the index
27 for adr in docs/decisions/[0-9]*.md; do
28 filename=$(basename "$adr")
29 if ! grep -q "$filename" docs/decisions/_index.md; then
30 echo "::error::ADR $filename is not listed in _index.md"
31 exit 1
32 fi
33 done

Anti-Patterns: What CFD Explicitly Forbids

A methodology is defined not only by what it recommends — but by what it forbids.

Anti-pattern 1: The Monolithic CLAUDE.md

1# ❌ BAD: Everything in a 500-line file
2# CLAUDE.md containing architecture, conventions, decisions,
3# project status, and a novel about the code's history

If your CLAUDE.md has more than 150 lines, it's already broken. Use @references.

Anti-pattern 2: Duplicated Context

1# ❌ BAD: Same information in three places
2# CLAUDE.md says "we use PostgreSQL"
3# docs/ARCHITECTURE.md says "the database is PostgreSQL"
4# docs/decisions/002.md says "we chose PostgreSQL"
5
6# ✅ GOOD: Single source, cross-references
7# CLAUDE.md: link to docs/STACK.md from the Context Map
8# docs/STACK.md: "Database: PostgreSQL 16 (see ADR-002)"
9# docs/decisions/002.md: [source of truth with full context]

Anti-pattern 3: Documentation in Native Language

1# ❌ BAD: Context in Spanish
2## Arquitectura
3La aplicación utiliza una arquitectura de capas separadas...
4# Consumes ~30% more tokens than the English equivalent
5
6# ✅ GOOD: Context in English
7## Architecture
8The application uses a layered architecture...

Articles, PRs, and team communication can be in any language. Technical context consumed by the model should be in English.

Anti-pattern 4: Scanning Code Instead of Reading Context

1# ❌ BAD: Prompt that forces scanning
2> "Read all files in src/ and tell me how the project is structured"
3# Cost: 10,000-50,000+ tokens
4
5# ✅ GOOD: Prompt that uses existing context
6> "Read docs/ARCHITECTURE.md and summarize the project structure"
7# Cost: 500-1,500 tokens

Anti-pattern 5: Implicit Decisions

1# ❌ BAD: Decision made in a conversation that gets lost
2"Let's just use Redis for caching" → implemented → session ends →
3next session doesn't know why Redis is there
4
5# ✅ GOOD: Decision documented before implementing
6> /decision:new
7→ ADR-015: Use Redis for caching
8→ Recorded in docs/decisions/
9→ Next session reads the ADR automatically

Anti-pattern 6: Not Closing the Session

The most common and most costly mistake. If you don't update CURRENT_STATUS.md at the end of the session, the next session starts without knowing what was done. It's the equivalent of not committing — work that exists but is invisible.


Scaling CFD: From Individual to Team

For an Individual Developer

The minimum CFD implementation for a solo developer:

1CLAUDE.md # Root file (required)
2docs/
3 ARCHITECTURE.md # Overview (required)
4 CURRENT_STATUS.md # Current status (required)
5 decisions/
6 _index.md # Decision index (required)
7.claude/
8 commands/
9 start-session.md # Session start (recommended)
10 new-decision.md # New decision (recommended)

Setup time: ~30 minutes with /project:init. Daily overhead: ~5-8 minutes (session start + close). ROI: pays for itself after 3-4 work sessions.

For a Team

In a team, CFD extends with:

1docs/
2 TEAM_CONVENTIONS.md # Team conventions
3 ONBOARDING.md # Guide for new members (and new agents)
4 decisions/
5 TEMPLATE.md # ADR template for consistency

Additional team rules:

  1. ADRs require review — like code, decisions are reviewed in PRs.
  2. CURRENT_STATUS.md leaves version control and becomes per-developer — .gitignore it; each developer keeps a personal local copy for session continuity. A single shared status file is a merge-conflict magnet (every PR touches it) and pollutes each developer's session start with everyone else's in-flight state. Shared "who is doing what" lives in the tracker (issues, milestones, assignees), not in a status file. Solo developers keep the file tracked — for one person it doubles as a session log.
  3. Slash commands are shared — .claude/commands/ lives in the repository.
  4. Each member can have local preferences — ~/.claude/CLAUDE.md for personal configuration that doesn't affect the team.

For Monorepos

In monorepos, CFD leverages the hierarchical nature of context:

1CLAUDE.md # Global monorepo context
2docs/ # Global documentation
3packages/
4 service-a/
5 CLAUDE.md # service-a specific context
6 docs/ # Specific docs
7 service-b/
8 CLAUDE.md # service-b specific context
9 docs/ # Specific docs

The model reads the nearest CLAUDE.md to the current working directory, with inheritance from the parent level.


Metrics: How to Know if CFD is Working

CFD is not dogma — it's a measurable practice. Before the numbers, though, be clear about which one matters.

The primary payoff is adherence, not tokens: code that respects your conventions on the first attempt, decisions that don't get re-litigated, corrections that never repeat. Token savings are real and welcome, but they are a side effect. Modern agents don't naively scan whole repositories — they search, and they search well. What they cannot search for is the why: the rejected alternatives, the conventions, the in-flight state. That is what CFD persists. If you adopt CFD to save tokens, you are optimizing the wrong variable; the honest measures are re-explanation rate and time to first correct action, below.

Tokens Per Productive Session

Measure how many tokens an average session consumes. With well-implemented CFD, you should see:

  • Session start: 500-1,500 tokens (context reading)
  • Productive session: 5,000-15,000 tokens (actual work)
  • Session close: 500-1,000 tokens (status update)

Without CFD, session start alone can consume 20,000-50,000 tokens just scanning code.

Time to First Correct Action

How many minutes pass from session start until the agent produces correct code (that doesn't need manual correction)? With CFD, it should be < 5 minutes. Without context, it can be 15-30 minutes of back-and-forth.

Re-explanation Rate

How often do you have to explain to the model something that was already discussed in a previous session? If you're constantly re-explaining decisions, the context is incomplete.

CURRENT_STATUS.md Freshness

1# How many commits ago was it last updated?
2git log -1 --format="%ar" -- docs/CURRENT_STATUS.md

If the answer is "more than 1 working day ago", the context is stale.


Complementary Tools

Repomix: For When You Need Total Context

Repomix packages entire codebases into a single AI-optimized file. It's useful for:

  • Generating the initial ARCHITECTURE.md
  • Full project audits
  • Technology migrations
1# Generate a project snapshot (excluding context docs)
2npx repomix --ignore "docs/,node_modules/,.claude/"

Don't use it every session — it's the "nuclear context" tool for when you need the model to understand everything.

GitHub CLI: The Glue

Already covered in detail, but to summarize the essential gh commands in a CFD flow:

1gh issue list # View pending work
2gh issue view <n> # Task context
3gh pr list # View open PRs
4gh pr create # Create PR with context
5gh pr diff <n> # View PR changes
6gh pr review <n> # Review a PR
7gh repo sync # Sync with remote

Case Study: Implementing CFD in an Existing Project

Let's see how CFD is implemented in a project that already has code. We're not starting from zero — we have a project with 200+ files, 6 months of history, and zero context documentation.

Step 1: Initialization (30 minutes)

1# Start Claude Code in the project
2claude
3
4# Run initialization
5> I want to implement Context-First Development (CFD) in this project.
6 Analyze the directory structure (do NOT read individual files) and:
7 1. Create docs/ARCHITECTURE.md based on the directory structure and
8 dependency files (package.json, pubspec.yaml, etc.)
9 2. Create docs/STACK.md listing all technologies and their versions
10 3. Create docs/CONVENTIONS.md — infer 5-10 key conventions from
11 the project structure
12 4. Create docs/CURRENT_STATUS.md — initialize with "Project initialized
13 with CFD"
14 5. Create docs/decisions/_index.md — empty index
15 6. Create docs/decisions/001-initial-architecture.md documenting
16 the current architecture as the first ADR
17 7. Update CLAUDE.md to reference all docs/ files

Step 2: Document Existing Decisions (1-2 hours, distributed)

You don't need to document everything at once. Each time you work on an area of the code and discover an implicit decision:

1> I see we're using [pattern X] in this module.
2 Let's document this as an ADR. /decision:new

After 2-3 weeks of normal work, you'll have 10-15 ADRs that capture the project's most important decisions.

Step 3: Establish the Routine (permanent)

From here, the flow is:

1Session start → /session:start → Work → /decision:new (if applicable) → Close → Update CURRENT_STATUS.md

Conclusion: Context Is the Competitive Advantage

There's a dangerous illusion in the industry: that increasingly larger AI models will solve the context problem. They won't. A model with a 2 million token context window isn't more useful if you feed it 2 million tokens of noise.

The competitive advantage isn't in the model — it's in the context you provide. A developer with a well-documented project using Claude 3.5 Sonnet will consistently outperform a developer with zero context using Claude Opus. Context multiplies the model's capability; it's not a substitute for it.

Context-First Development is not a revolutionary framework. It's the disciplined application of principles that good engineers already know — clear documentation, explicit decisions, shared state — adapted to a world where your programming partner has amnesia at the start of every session.

The question isn't whether you need a methodology like CFD. The question is how many more sessions you'll waste re-explaining the same decisions before adopting one.


Addendum: What Lives in the Repository

This essay is the canonical statement of the methodology, and it is kept in sync with context-first-development.md in the repository. The repository is the source of truth. Where this article and the repository disagree, the repository is the one that is right.

Three parts of CFD are shipped as artifacts rather than described here:

  • A shareable ADR catalog. Atomic, technology-neutral decision records you copy into your own repo instead of installing a library — why you use the repository pattern, why tests hit a real database instead of mocks, why corrections get documented rather than merely applied, each with its rejected alternatives intact. Categories: architecture, testing, process, ai-workflow.
  • A distribution channel for the commands. An optional Claude Code plugin ships the slash commands only — not the scaffold. Pick one channel and delete the other, or the same procedure runs from two places and they drift.
  • A documented adopter. sii, a TypeScript monorepo born with CFD on day zero: ADR-001 is the adoption decision itself, and twenty-one ADRs landed in the first week.

Everything is at github.com/albertomarturelo/context-first-development. Code, templates and slash commands are MIT; the prose is CC-BY-SA 4.0.


References

  1. Anthropic. "Effective Context Engineering for AI Agents." anthropic.com, 2025.
  2. Anthropic. "Claude Code Best Practices." code.claude.com, 2025.
  3. Sourcegraph Amp Team. "AGENTS.md: A Standard for AI Agent Instructions." agents.md, 2025.
  4. Medin, Cole. "Context Engineering Intro." GitHub, 2025.
  5. Osmani, Addy. "My LLM Coding Workflow Going into 2026." addyosmani.com, 2025.
  6. Osmani, Addy. "The AI-Native Software Engineer." Substack, 2025.
  7. Spotify Engineering. "1,500+ PRs Later: Spotify's Journey with Our Background Coding Agent." engineering.atspotify.com, 2025.
  8. Spotify Engineering. "Context Engineering: Background Coding Agents Part 2." engineering.atspotify.com, 2025.
  9. Swan, Chris. "Using Architecture Decision Records (ADRs) with AI Coding Assistants." blog.thestateofme.com, 2025.
  10. Rotenberg, Josh. "Claude ADR System Guide." GitHub Gist, 2025.
  11. Strengholt, Piethein. "Building an Architecture Decision Record Writer Agent." Medium, 2025.
  12. Chatlatanagulchai et al. "On the Use of Agentic Coding Manifests: An Empirical Study of Claude Code." arXiv:2509.14744, 2025.
  13. "Agent READMEs: An Empirical Study of Context Files for Agentic Coding." arXiv:2511.12884, 2025.
  14. "Context Engineering for Multi-Agent LLM Code Assistants." arXiv:2508.08322, 2025.
  15. Grandau, Mark. "Turning AI Code Reviews Into Continuous Improvement." Medium, 2025.
  16. GitHub. "Agentic Workflows." github.github.io/gh-aw, 2026.
  17. Steinberger, Peter. "agent-rules." GitHub, 2025 (archived).
  18. Li, Bojie. "Claude's Context Engineering Secrets." 01.me, 2025.
  19. Cline. "Memory Bank: How to Make Cline an Autonomous Coding Agent with Persistent Memory." docs.cline.bot, 2025.
  20. GitHub. "Spec Kit — a toolkit for Spec-Driven Development." github.com/github/spec-kit, 2025.
  21. AWS. "Kiro — an agentic IDE with spec-driven development." kiro.dev, 2025.
  22. "BMAD-Method: Breakthrough Method for Agile AI-Driven Development." github.com/bmadcode/BMAD-METHOD, 2025.

Uso Google Analytics para saber qué se lee. Sin cookies de publicidad ni de terceros más allá de esa medición. Más detalle