Applied Intelligence
Module 4: Advanced Context Management

Persistent Context with Files

The file system as memory

Context windows are volatile. Every session starts empty. Compaction summarizes but loses detail. Sessions end, and accumulated understanding vanishes.

The file system solves this. Files persist across sessions, survive compaction, and load deterministically every time. Where conversation context is temporary and fragile, file-based context is permanent and reliable.

CLAUDE.md as persistent memory

CLAUDE.md files function as the agent's external memory. Every session begins with CLAUDE.md content loaded before any conversation starts. Decisions documented in CLAUDE.md survive across sessions without degradation.

The mechanism is simple: Claude Code reads designated files into context automatically. No retrieval step, no summarization the full content loads verbatim. This determinism matters because it means you get exactly what you wrote, every time.

Why file memory beats conversation memory

Conversation context degrades in ways that are hard to predict. The "lost in the middle" effect reduces recall for information buried in context midpoints. Compaction summarizes, losing nuance. Long sessions accumulate irrelevant history that dilutes signal.

File memory avoids these problems:

  • Deterministic loading: Same content, same position, every session
  • Explicit structure: Headers, sections, and formatting aid retrieval
  • Version controlled: Changes tracked in git, revertible, reviewable
  • Shareable: Team members get identical context
  • Compact by design: Files encourage concise, essential content

Consider a decision buried in turn 47 of a long conversation. It might survive compaction as "decided to use approach X." The same decision in CLAUDE.md reads: "Use approach X because Y constraint requires Z behavior. Never use approach W due to performance implications."

The file version preserves the reasoning, constraints, and prohibitions. The summarized version loses exactly what the agent needs to make consistent future decisions.

The hierarchical loading system

Context files load in a specific order, with later files able to reference or override earlier ones. Understanding this hierarchy determines where to place different types of guidance.

Claude Code's five-level hierarchy

PriorityTypeLocationScope
1 (Lowest)EnterpriseSystem pathsOrganization-wide policy
2Project./CLAUDE.mdTeam standards, shared via git
3Rules./.claude/rules/*.mdTopic-specific, modular guidance
4User~/.claude/CLAUDE.mdPersonal preferences, all projects
5 (Highest)Local./CLAUDE.local.mdPersonal project overrides, gitignored

Each level serves different needs:

Enterprise level establishes non-negotiable constraints security policies, compliance requirements, approved libraries. Individual developers cannot override these restrictions.

Project level captures team conventions coding standards, testing requirements, architectural decisions. Changes require team agreement and code review.

Rules directory enables modular organization. Instead of one monolithic file, separate concerns into focused documents: security.md, testing.md, api-patterns.md. Rules can include path-specific triggers via frontmatter:

---
paths:
  - "src/api/**/*.ts"
---
# API endpoint requirements
- Input validation required on all handlers
- Structured logging with request correlation

User level personalizes behavior without affecting teammates. Editor preferences, communication style, personal tool configurations.

Local level overrides project conventions for individual work. Experimental approaches, debugging aids, temporary workarounds. Files with the .local.md suffix are automatically gitignored.

Discovery mechanism

Claude Code discovers context files through upward traversal:

  1. Start from current working directory
  2. Search for CLAUDE.md, CLAUDE.local.md, and .claude/ directory
  3. Move to parent directory
  4. Repeat until repository root (or filesystem root if no git)
  5. Check user directory (~/.claude/)

This traversal enables monorepo patterns. A frontend subdirectory can have its own CLAUDE.md extending the root configuration:

monorepo/
├── CLAUDE.md           # Shared conventions
├── frontend/
│   └── CLAUDE.md       # Frontend-specific additions
└── backend/
    └── CLAUDE.md       # Backend-specific additions

Nested files extend rather than replace parent files. The agent sees all discovered content, concatenated in discovery order.

The import mechanism

Large context files defeat their purpose cognitive saturation occurs around 150-200 instructions. The import mechanism solves this by enabling selective loading.

Import syntax

Reference external files using the @ prefix:

## Architecture
See @docs/architecture.md for system design details.

## API Conventions
@docs/api-guide.md

## Personal setup
@~/.claude/my-preferences.md

Imports support:

  • Relative paths from the current file: @./sibling.md
  • Project-relative paths: @docs/guide.md
  • User directory paths: @~/.claude/personal.md
  • Repository root references: @/CHANGELOG.md

Maximum recursion depth is 5 levels imports can import other files, but the chain terminates to prevent infinite loops.

Strategic import patterns

Root file as router: Keep the main CLAUDE.md lean, routing to detailed documentation:

# Project Context

## Quick Reference
- Build: `npm run build`
- Test: `npm test`
- Deploy: `./scripts/deploy.sh`

## Detailed Guides
For comprehensive documentation, see:
- Architecture decisions: @docs/architecture.md
- API patterns: @docs/api-conventions.md
- Security requirements: @docs/security.md

Conditional detail: Reference documentation the agent can read when relevant rather than loading everything upfront:

## Database Migrations
Run `npm run migrate` for schema changes.
Full migration guide available in @docs/migrations.md if needed.

The agent decides whether to read the referenced file based on task requirements.

File-based compensation strategies

Context windows have hard limits. Files enable strategies that work around these constraints.

External storage for accumulated knowledge

Instead of relying on conversation history to remember decisions, write them to files:

## Session Notes (updated 2026-01-15)

### Decisions Made
- Authentication: JWT with 24-hour expiry, refresh tokens stored server-side
- Database: PostgreSQL with read replicas for reporting queries
- Caching: Redis for session data, 15-minute TTL

### Open Questions
- Rate limiting strategy pending security team review
- Mobile API versioning approach TBD

Next session, this file loads automatically. No need to re-establish decisions through conversation.

Progress tracking files

Complex tasks benefit from explicit progress documentation:

## Migration Progress

### Completed
- [x] Database schema updated
- [x] User model migrated
- [x] Authentication endpoints converted

### In Progress
- [ ] Order processing (blocked on payment gateway update)

### Remaining
- [ ] Reporting module
- [ ] Admin dashboard
- [ ] Integration tests

The agent reads current state immediately rather than inferring from conversation history.

Handoff summaries

When ending a session with incomplete work, document the handoff:

## Handoff: Authentication Refactor (2026-01-15)

### Current State
Migrated 4 of 7 endpoints. Working code committed to branch `auth-refactor`.

### Where I Stopped
`src/auth/refresh.ts` line 45 - implementing token rotation logic.
The rotation strategy uses sliding expiration with 7-day absolute maximum.

### Blockers
Waiting for security team decision on refresh token storage location.
Options documented in PR #234 comments.

### Next Steps
1. Complete refresh.ts implementation
2. Update integration tests
3. Add rate limiting per security requirements

This summary gives the next session (or next developer) complete context without reading the full conversation history.

The "everything is context" perspective

File-based context extends beyond explicit configuration files. The entire file system provides implicit context that shapes agent behavior.

Folder structure as context

Directory organization communicates architecture:

src/
├── components/     # UI building blocks
├── features/       # Domain-specific functionality
├── hooks/          # Shared React hooks
├── services/       # External API integrations
└── utils/          # Pure utility functions

The agent infers patterns from structure. New code matching existing organization requires less explicit instruction.

Naming conventions as context

Consistent naming teaches the agent by example:

  • useAuth.ts, useCart.ts → hooks follow use prefix
  • auth.service.ts, payment.service.ts → services use .service.ts suffix
  • Button.tsx, Modal.tsx → components use PascalCase

Explicit documentation of these conventions in CLAUDE.md reinforces what the codebase demonstrates. But existing code provides context even without documentation.

Configuration files as context

Build configurations, linter rules, and TypeScript settings all provide context:

  • tsconfig.json strict mode indicates type safety requirements
  • ESLint rules demonstrate code style expectations
  • Package.json dependencies reveal available libraries

The agent reads these files when relevant, extracting constraints that shape generated code.

Cross-tool applicability

File-based context works across all major coding agents, though mechanisms vary.

ToolPrimary FileDiscoveryImports
Claude CodeCLAUDE.mdHierarchical traversal@path syntax
CodexAGENTS.mdRoot + override filesStandard markdown links
Cursor.cursor/rules/*.mdcRules directoryFrontmatter globs
Copilot.github/copilot-instructions.mdGitHub directoryapplyTo frontmatter
AiderCONVENTIONS.mdExplicit /read commandManual includes

The AGENTS.md standard, governed by the Agentic AI Foundation since December 2025, provides cross-tool compatibility. A single AGENTS.md file works with Codex, Cursor, Copilot, and others. Claude Code can import AGENTS.md content via the @ mechanism.

Practical interoperability

For teams using multiple tools:

project/
├── AGENTS.md           # Cross-tool compatible
├── CLAUDE.md           # Claude-specific extensions
│   # Import shared content:
│   # @AGENTS.md
└── .cursor/rules/
    └── shared.mdc      # Cursor-specific format

Shared content lives in AGENTS.md. Tool-specific extensions live in dedicated files. Imports prevent duplication.

Designing for file-based memory

Effective file-based context requires intentional design.

Conciseness over completeness

Every token in a context file competes for attention. A 1,000-line CLAUDE.md dilutes critical instructions. Aim for 60-100 lines of essential guidance at the root level.

Move details to importable documents the agent reads when needed.

Explicit over implicit

Document decisions, not just rules. "Use approach X" is less useful than "Use approach X because constraint Y makes alternatives Z impractical."

The reasoning helps the agent make consistent decisions in novel situations.

Current over historical

Context files should reflect current state, not accumulated history. Old decisions that no longer apply create confusion. Regular pruning keeps content relevant.

Tested assumptions

Instructions in CLAUDE.md should be verified. If the agent ignores a guideline, investigate why:

  • Too vague?
  • Contradicted by other context?
  • Lower priority than competing instructions?

Iterate on context files like any other code artifact.

File-based context transforms ephemeral conversation memory into persistent, reliable, version-controlled guidance. The next page examines scratchpad and task tracking patterns file-based techniques for managing work in progress.

On this page