Every developer using AI coding tools hits the same wall: your project grows from 5 files to 50, and suddenly the AI becomes noticeably worse. It reads more irrelevant code, makes more mistakes, and burns through tokens at an alarming rate. The problem isn't the model — it's how we feed context to AI.
This article introduces the Module Contract Pattern — an architectural solution that reduces AI token consumption by 60-90% per task, prevents "context amnesia" between sessions, and keeps AI output quality high even in large codebases.
The Problem: Token Inflation Is Real
Here's what happens when you use Cursor, Copilot, or Claude Code on a growing project:
Phase 1: Early Project (files < 10)
- AI reads 3-5 files to understand context
- Token consumption: ~2K-5K per task
- Output quality: High
- Your feeling: "This is amazing!"
Phase 2: Mid-size Project (files 10-50)
- AI scans 10-15 files to understand modules and dependencies
- Token consumption: ~10K-30K per task
- Output quality: Mixed — sometimes great, sometimes way off
- Your feeling: "Why is it getting worse?"
Phase 3: Large Project (files 50+)
- AI scans 20+ files, traces imports, reads entire modules just to understand one function
- Token consumption: ~30K-80K per task
- Output quality: Poor — generates code that doesn't match architecture, makes wrong assumptions about module boundaries
- Context compression kicks in, old context is lost, "amnesia" between sessions
- Your feeling: "I spend more time fixing AI outputs than writing code myself"
This isn't a model problem. Claude 4.5, GPT-5.2, and DeepSeek are all capable models. The problem is context pollution — AI is reading implementation details it doesn't need, burning tokens on code it shouldn't care about.
The Insight: AI Should Read Interfaces, Not Implementations
Think about how you work as a developer:
- You want to call
payment.refund(order_id)— you read the function signature and docstring, not the 200 lines of implementation - You use a library — you read the API docs, not the library source code
- You work on a team — you understand module boundaries and contracts, not every line your teammates wrote
This is the Interface Segregation Principle from software engineering, applied to AI context management.
In C, you have .h header files. In TypeScript, you have .d.ts declaration files. They exist for a reason: the caller shouldn't need to read the implementation to use the interface.
Why would AI be any different?
The Solution: Module Contract Pattern
Every module in your project gets a .contract.md file — a human and AI-readable interface definition that contains:
- Public API — functions, classes, methods, and their signatures
- Dependencies — what other modules this module relies on
- Side Effects — database writes, network calls, file I/O
- Source Files — where the actual code lives
Example: payment.contract.md
# Module: payment
> Payment processing — orders, refunds, billing
## Public API
### Functions
`async create_order(amount, currency) -> Order`
Create a new payment order. Order starts as "pending".
`refund(order_id, reason, partial=False) -> RefundResult`
Process a refund. Set partial=True for partial refunds.
### Classes
- **Order**
- `mark_paid()` -> None
- `cancel() -> None
## Dependencies
- `database` — order and refund persistence
- `gateway` — payment gateway (WeChat Pay / Stripe)
## Side Effects
- [x] Database writes (orders, refunds)
- [x] Network requests (payment gateway API)
## Files
- `src/payment/service.py` — core payment logic
- `src/payment/models.py` — Order, RefundResult dataclasses This is ~500 tokens. The AI reads this and knows everything it needs to work with the payment module — without reading 300 lines of implementation code.
How It Works With Your AI Tool
Instead of the traditional flow:
User: "Add partial refund support"
AI: Scans src/ directory → Reads 20+ files → Traces imports → Finally understands payment module → Implements
Token cost: 15K-50K ❌ The contract flow is:
User: "Add partial refund support"
AI: Reads .ai/PROJECT.md (234 tokens) → Reads payment.contract.md (500 tokens) → Reads payment/service.py (2K tokens) → Implements
Token cost: 2K-5K ✅ Measured Results
| Scenario | Traditional | Contract Mode | Savings |
|---|---|---|---|
| Modify single function | 5K-15K tokens | 1K-3K tokens | 70-80% |
| Add new feature | 10K-30K tokens | 2K-5K tokens | 75-85% |
| Cross-module integration | 15K-40K tokens | 2K-6K tokens | 80-85% |
| First session (new project) | 50K+ tokens | 5K-15K tokens | 80-90% |
On a 50-file FastAPI project: contract mode saved ~80% tokens per task on average. Over 100 AI interactions, that's the difference between $5 and $50 in API costs.
The "Context Amnesia" Fix
One of the most frustrating AI coding problems is session amnesia. You start a new session, and the AI has forgotten your entire project architecture. It makes the same mistakes, asks the same questions, generates code that contradicts decisions you made three sessions ago.
Why does this happen? Because AI context is ephemeral — it only exists for the duration of a conversation. When you start a new session, the AI has to re-read your entire codebase to "re-learn" the project.
Contract files solve this: they are persistent, structured project knowledge that survives across sessions.
Session 1: AI reads payment.contract.md → builds payment feature
Session 2: AI reads payment.contract.md → extends payment feature
Session 3: AI reads payment.contract.md → fixes payment bug
...
Session 50: AI reads payment.contract.md → same understanding as Session 1 No context decay. No re-learning. Just consistent, high-quality output.
How to Get Started: AI Context Manager (Free, Open Source)
We built AI Context Manager to automate the contract generation process:
# Install
$ pip install ai-context
# Initialize in your project
$ cd your-project
$ ai-context init # English mode (default)
$ ai-context init --lang zh # Chinese mode
$ ai-context scan # Scans code, generates all contracts
$ ai-context status # See token savings report Output:
PROJECT.md: OK
GUIDE.md: OK
Contracts: 12 modules
Token savings estimate:
Traditional (full scan): ~90,000 tokens
Contract mode (on demand): ~6,800 tokens
Savings: 92% AI Context Manager is completely free, MIT licensed, open source. No signup, no API key, no vendor lock-in. It generates plain Markdown files that work with every AI coding tool: Cursor, Windsurf, Claude Code, GitHub Copilot, WorkBuddy, you name it.
How to Combine With Rules Files
Contract files are complementary to rules files — they work at different levels:
| File | Level | What It Tells AI |
|---|---|---|
.cursorrules / .mdc | Project conventions | "Use TypeScript, functional components, Tailwind CSS" |
CLAUDE.md | Project commands + conventions | "Run tests with pnpm test, DB at localhost:5432" |
.ai/PROJECT.md | Project architecture | "Payment module → src/payment/, Auth module → src/auth/" |
.ai/contracts/*.md | Module interfaces | "payment.refund() takes order_id and reason, returns RefundResult" |
Use them together:
# In your .cursorrules, .mdc, or CLAUDE.md, add:
## AI Context
- Always read .ai/PROJECT.md first to understand project structure.
- Before modifying any module, read its .ai/contracts/*.contract.md.
- Do not scan the entire src/ directory to find files — use the Files section in contracts. The Architectural Principle: AI-Native Design
The Module Contract Pattern is part of a larger philosophy: AI-Native Architecture. Just like we design APIs for human developers, we should design project structures for AI assistants.
AI-native projects follow three principles:
- Interface segregation for AI — Every module exposes a contract file. AI reads contracts, not implementations.
- Context budgeting — Track and optimize how much context each AI task consumes. Run
ai-context statusto see your savings. - Persistent structure — Contracts are committed to Git. They persist across sessions, tools, and team members.
Common Questions
Do I need to manually update contracts?
Mostly no. ai-context scan auto-detects function signatures, classes, and imports. When you change an API, just re-run scan. The Side Effects section is the only part that benefits from manual input.
Should contracts be committed to Git?
Yes. The .ai/ directory should be version-controlled. This ensures every team member's AI tool has the same project understanding. Contracts are lightweight — a 50-module project's contracts total ~15KB.
What languages are supported?
Currently Python (full AST parsing) and TypeScript/JavaScript (regex-based export detection). Go, Rust, and Java support are planned.
How is this different from rules files?
Rules files (.cursorrules / CLAUDE.md) tell AI how to write code (conventions, style, tech stack). Contract files tell AI what the code does (module APIs, dependencies, side effects). They work at different levels and are complementary.
Start Saving Tokens Today
The Module Contract Pattern is simple to adopt: install the tool, run it once, and your AI tools immediately become more efficient. For a 50-file project, that's potentially hundreds of dollars saved in token costs per year — plus the time saved from fewer AI mistakes and faster sessions.
Get started: AI Context Manager — Free, MIT licensed. One command to install:
pip install git+https://github.com/KaiDev-dev/ai-context.git && ai-context scan Also read: How to Write Cursor Rules Guide — combine with contracts for maximum AI context efficiency.