The Context Amnesia Problem in AI Coding Agents
Modern AI coding agents—such as Claude Code, OpenAI Codex, Cursor, and Google Antigravity—are exceptionally fast at generating code. But every developer working on non-trivial systems with coding agents eventually hits the context amnesia wall:
Claude built half your project.You hit a token usage limit, conversation limit, or context compaction event.
You switch to OpenAI Codex or start a fresh session.
Codex knows nothing about:
- What features were completed vs in-progress
- Why specific architecture choices were made
- Which edge cases broke and what was fixed
- Which tests are passing vs failing
- What the single next exact action should be
Even within a single agent session, long conversations inevitably degrade:
To solve this, developers often try to dump their entire conversation transcript into a prompt or install complex vector database memory servers. But both approaches fail: conversation transcripts contain 90% noisy reasoning tokens, and external databases detach project memory from the code itself.
This is why I built ContextOS around a single non-negotiable premise:
Conversations are temporary. The repository is the durable memory.
The Mental Model: Repository-Native Memory
Instead of treating project intelligence as ephemeral chat history, ContextOS persists the project's living brain directly inside the repository in a structured, portable directory:
YOUR PROJECT
│
▼
.context/ ← Durable memory, committed to Git
│
┌────────────┼────────────┐
▼ ▼ ▼
PRD STATUS DECISIONS
│ │ │
└────────────┼────────────┘
▼
HANDOFF
│
┌────────────┼────────────┐
▼ ▼ ▼
Claude Codex Cursor / Other AI
Because this memory consists of plain, inspectable Markdown files committed to Git, it provides distinct engineering advantages: 1. Model & Agent Independent: Any LLM, coding agent, or human developer can read and edit standard Markdown. 2. Zero External Infrastructure: No required cloud accounts, hosted vector databases, or telemetry servers. 3. Version Controlled & Diffable: Project memory changes alongside code commits in your Git history. 4. Resilient to Context Loss: When a session resets or context compacts, the agent cold-rehydrates from disk in milliseconds.
The Three Architecture Layers
ContextOS separates functionality into three clean, decoupled layers:
| Layer | Purpose | Location | Consumers |
| :--- | :------ | :------- | :-------- |
| 1. Protocol | The portable .context/ Markdown specification | ./.context/ | Any AI agent, human developer, or CI script |
| 2. Skill | Router behavior: when to init, compile, snapshot, or hand off | skills/context-os/SKILL.md | Claude Code, Agent Skills standard tools |
| 3. Adapters | Thin entrypoints pointing agents to .context/ | CLAUDE.md, AGENTS.md | Specific agent runtimes |
The protocol is the source of truth. Adapters never duplicate documentation—they simply instruct the agent where to find project intelligence.
Anatomy of the .context/ Protocol
The .context/ directory organizes project knowledge into high-signal files with distinct lifecycles:
.context/
├── INDEX.md # Tiny map: what exists and when to read it (L0)
├── STATUS.md # The heartbeat: objective, done, in-progress, blocked, next, validation (L0)
├── CONSTRAINTS.md # Hard MUST / MUST NOT boundaries (L0)
├── PRD.md # Requirements with stable IDs (AUTH-001, API-004) (L2)
├── ARCHITECTURE.md # System components, data flows, and dependencies (L2)
├── PLAN.md # Phased roadmap with exit criteria & traceability (L1/L2)
├── DECISIONS.md # ADR-style decisions with "Do Not" guardrails (L2)
├── HANDOFF.md # Cold-takeover briefing: next action & do-not-redo (L0)
├── prompts/
│ ├── original/ # Verbatim substantial user requests
│ └── compiled/ # Engineering-grade execution specs
├── sessions/ # Lightweight per-session notes (never transcripts)
└── archive/ # Cold storage for completed investigations & logs (L3)
Context Budgeting: Why Dumping Everything Fails
One of the most dangerous mistakes in context engineering is loading the entire repository's documentation into every turn. Overloading the context window increases hallucination rates, distracts the model's attention mechanism, and depletes budget for actual code diffs.
ContextOS implements a strict 4-Level Context Budget:
L0 ALWAYS LOADED Objective · STATUS.md · CONSTRAINTS.md
L1 TASK CONTEXT Relevant code files · Targeted tests · Active PLAN.md phase
L2 ON-DEMAND REF Relevant PRD sections · API schema · Architecture references
L3 COLD STORAGE archive/ · Past session logs · Superseded research
The Core Budget Rule:
Use the smallest high-signal context sufficient to make the next decision correctly.
An agent working on a focused bug fix only reads STATUS.md and CONSTRAINTS.md (L0), jumping straight to the affected source file and test (L1). It pulls PRD.md or DECISIONS.md (L2) only if contemplating an architectural deviation.
The Prompt Compiler: Vague Asks → Execution Specs
When users give vague instructions to AI agents, the agents often guess implementation details, producing brittle code. ContextOS features a Prompt Compiler that converts rough requests into structured engineering specifications before a single file is touched.
Before (Raw User Input):
fix auth, make dashboard better and make everything faster
After (Compiled Execution Spec):
OBJECTIVE
Fix reported auth session drop, enhance dashboard state rhythms, reduce p95 latency.CURRENT SYSTEM
Next.js App Router + Supabase Auth; session JWT cookie; PostgreSQL.
REQUIREMENTS
1. Auth: Reproduce failure, write failing regression test, fix refresh token cycle. Keep provider (D-002).
2. Dashboard: Implement 4 application states (Loading, Empty, Populated, Error) on /dashboard.
3. Performance: Measure main-thread blocking time; eliminate layout shifts on font load.
CONSTRAINTS
Keep auth endpoints backward-compatible. Zero mock data in production. Tests before "done".
FILES / AREAS TO INSPECT
lib/auth/*, app/dashboard/page.tsx, app/globals.css.
VALIDATION
Vitest unit tests for token refresh; Playwright E2E for login flow; CWV audit.
DEFINITION OF DONE
Auth bug fixed with regression test; dashboard states validated; zero CLS verified.
The prompt compiler clarifies requirements and establishes verifiable definitions of done without inventing new product decisions that the user did not intend.
STATUS.md as the Project Heartbeat
STATUS.md is the single most important file in ContextOS. It provides an objective, real-time snapshot of where the project stands:
Updated: 2026-08-16
Agent: Claude Code (claude-3-7-sonnet)
Phase: Phase 2 — Authentication Hardening
Status: blockedCurrent Objective
Resolve session expiry on mobile browser tabs and establish test mail transport.Completed
[x] AUTH-001: Email OTP login flow implemented and tested.
[x] AUTH-002: Session persistence in secure httpOnly cookies. In Progress
[-] AUTH-003: Token auto-refresh handler during background tab wake. Blocked
[!] E2E auth test failing in CI due to missing local SMTP transport. Next Action
Configure local SMTP capture (Mailpit) in test environment; re-run auth-otp.spec.ts.Validation
Unit: pass (16/16) | E2E: fail (1 failing) | Build: pass (0 errors) | Typecheck: pass
The Snapshot Principle:
pass means you actually ran the compiler or test runner and received a zero exit code. Never fake validation.Decision Memory: ADRs with Guardrails
When AI agents work without decision memory, they frequently introduce regressions by unknowingly undoing past architectural choices. ContextOS records Architectural Decision Records (ADRs) in DECISIONS.md with explicit "Do Not" guardrails:
## D-002 — Custom Session Management over Hosted Lock-in
Status: Accepted (2026-08-16)
Decision: Use direct Supabase Auth with custom numeric OTP verification and httpOnly cookies.
Reason: Eliminates external redirects, gives full control over auth UI, and avoids third-party vendor lock-in.
Implication: Auth flows must handle rate-limiting and token refresh internally.
Do Not: Replace with hosted Clerk/Auth0 popups without explicit architecture review—our custom admin flows depend on this model.
The Do Not directive acts as an immediate guardrail that stops subsequent agents from tearing down deliberate architecture.
Switching Models: Claude Code ↔ OpenAI Codex
Switching agents or models with ContextOS requires zero migration scripts:
CLAUDE CODE OPENAI CODEX
1. Complete current task unit 1. Reads AGENTS.md natively
2. Update STATUS.md + DECISIONS.md → Points to .context/INDEX.md
3. Write HANDOFF.md (Next Exact Action) → Reads STATUS.md + HANDOFF.md
4. Commit to Git: git commit -m "..." 2. Verifies Git status & test suite
5. End session 3. Executes Next Exact Action immediately
Because the next model rehydrates directly from committed repository truth rather than an imperfect chat summary, the handover is seamless and lossless.
Source-of-Truth Priority Hierarchy
When different sources of information conflict during an agent session, ContextOS enforces a strict priority order:
1. Current User Instruction (Immediate interactive intent)
↓
2. Actual Repository Code & Real Test Results (Ground truth)
↓
3. Accepted Decisions (DECISIONS.md)
↓
4. Product Requirements Document (PRD.md)
↓
5. Architecture Specification (ARCHITECTURE.md)
↓
6. Project Status (STATUS.md)
↓
7. Handoff Notes (HANDOFF.md)
↓
8. Cold Archive (archive/)
If STATUS.md or ARCHITECTURE.md disagrees with what the code and test runners report, the code wins, and the agent immediately repairs the stale documentation file.
Deterministic Context Health Auditing
ContextOS includes a built-in deterministic health audit CLI (contextos health) that analyzes the repository memory across five core metrics:
$ contextos health .Context Health: 100/100
Freshness 100 (STATUS.md updated recently relative to Git commits)
Consistency 100 (No contradictory states; Next Action explicitly defined)
Completeness 100 (All core L0/L2 memory files populated)
Token Efficiency 100 (Always-loaded L0 files remain compact < 250 lines)
Handoff Readiness 100 (HANDOFF.md contains clear Next Action & Do-Not-Redo)
The health score is not an opaque AI estimate; it is a deterministic heuristic computed by analyzing file timestamps, section completeness, heading syntax, and token footprint.
Zero Dependencies, Zero Telemetry
The ContextOS CLI (bin/contextos.mjs) was engineered with strict minimalism:
node:fs, node:path, node:test). No bulky node_modules dependency tree..context/.Quickstart & Installation
Initialize ContextOS in your project in seconds:
# 1. Install ContextOS agent skill
npx skills add pokhrelboss/context-os2. Scaffold .context/ memory directory in your repository
npx github:pokhrelboss/context-os init .3. Check health and status anytime
npx github:pokhrelboss/context-os health .
npx github:pokhrelboss/context-os status .
Verified Compatibility Matrix:
CLAUDE.md adapter + optional lifecycle hooks).AGENTS.md standard support).AGENTS.md and .cursor/rules integration).AGENTS.md standard).Conclusion & Open Source
Software engineering is cumulative; conversations are fleeting. By moving project intelligence from chat windows into a version-controlled, model-independent .context/ layer, ContextOS gives developers and AI coding agents the memory, continuity, and discipline required to ship resilient systems.
Try ContextOS on your next multi-session agent project and never let your coding agent forget its purpose again.