Claude Code Memory Limits: CLAUDE.md Sizing, Auto-Memory, and Context Workarounds
Claude Code memory limits represent the size thresholds and retention boundaries governing CLAUDE.md files, persistent auto-memory directories, and active session compaction. Operating within a 200,000-token context window, Claude Code reads manual instruction files at launch and automatically records session learnings to a 200-line index. When context fills or projects outgrow local files, offloading large reference corpora to external workspaces prevents memory bloat.
What Are the Operational Limits Across Claude Code Memory Tiers?
Anthropic documented file boundaries establish clear ceilings across platforms: standard Claude chats accept up to 20 files at up to 500MB each, while Claude Projects accepts files up to 30MB each with an unlimited file count bounded entirely by the model context window. In Claude Code, the memory architecture operates under a different set of constraints. Developers working in the terminal interact with an active working context window of 200,000 tokens (or 1,000,000 tokens on extended configurations), paired with a dual-layer local file system: static instruction files (CLAUDE.md) capped at 4 MiB, and dynamic auto-memory index files (MEMORY.md) limited to 200 lines or 25KB.
Claude Code memory limits represent the size thresholds and retention boundaries governing CLAUDE.md files, persistent auto-memory directories, and active session compaction. Evaluating memory capacity requires distinguishing between three separate operational tiers:
- Active session context window (working memory). This is the ephemeral scratchpad for the running terminal session. It holds system prompts, MCP tool definitions, skill indexes, environment data, file contents read during execution, bash tool outputs, and conversational turns. Once the session ends or you run
/clear, unpersisted conversational history disappears. - Manual project instructions (
CLAUDE.mdand rules). Human-authored Markdown files that define coding standards, build workflows, and architectural patterns. Claude Code reads these files from disk at the start of every session or dynamically when matching file paths are accessed. - Autonomous memory (
MEMORY.mdand topic files). Machine-authored Markdown notes that Claude Code writes quietly to your local user directory. This system records user preferences, confirmed bug fixes, and operational constraints discovered across previous coding runs.
The following comparison details the operational limits and retention behaviors governing Claude Code memory tiers as of October 2026.
This architecture differs completely from Claude.ai Projects. Claude Projects stores documents on Anthropic's hosted servers and uses cloud retrieval-augmented generation. Claude Code operates strictly against local files on your machine.
Related guides
- OpenAI Codex Token Limits: Context Windows, Request Caps, and WorkaroundsThe Codex token limit refers to the maximum number of prompt and generation tokens permitted in a single OpenAI Codex...
- Claude Haiku Context Window: Token Limits, Latency, and WorkaroundsThe Claude Haiku context window provides a 200,000-token input memory buffer for high-speed processing across...
- Claude Memory Limit: Working Memory, Context Allocation, and Long-Term StorageUnderstanding the Claude memory limit requires distinguishing between active working context (200,000 to 1,000,000...
- Claude Code Message Limit: Quotas, Compaction, and Large-Context WorkaroundsClaude Code message limits define the maximum prompt token size and message frequency allowed in a CLI session before...
- Claude 5-Hour Limit Explained: Reset Rules, Token Consumption, and WorkaroundsThe Claude 5 hour limit is Anthropic's rolling rate-limiting mechanism that dynamically restricts user message volume...
- Claude Daily Limit: Usage Caps, Reset Times, and WorkaroundsClaude daily limits refer to the message and token caps imposed on Claude.ai accounts, which operate as fixed 24-hour...
More on this subject: Claude and Claude Code (255 guides)
How to Size CLAUDE.md Files and Prevent Context Bloat
A CLAUDE.md file serves as the project rulebook that Claude Code reads before processing your first prompt. You write it, check it into version control, and use it to pass project conventions that Claude cannot infer directly from syntax.
Claude Code discovers instruction files across multiple scopes. It resolves them in order from broadest authority to most specific local override:
- Managed policy: Located at
/Library/Application Support/ClaudeCode/CLAUDE.mdon macOS,/etc/claude-code/CLAUDE.mdon Linux, andC:\Program Files\ClaudeCode\CLAUDE.mdon Windows. Central IT teams deploy this file to establish organization-wide security boundaries and coding standards. Individual user settings cannot exclude it. - User instructions: Located at
~/.claude/CLAUDE.md. Contains personal preferences applied across all projects on your machine, such as terminal formatting or private tool aliases. - Project instructions: Located at
./CLAUDE.mdor./.claude/CLAUDE.md. Shared across the engineering team via Git, documenting build commands, test suites, and repository layouts. Claude Code also readsAGENTS.mdin this scope when noCLAUDE.mdexists. - Local instructions: Located at
./CLAUDE.local.md. Stores individual developer overrides for the current repository, such as sandbox ports or staging database strings. This file should be added to.gitignore.
When you launch Claude Code inside a nested directory such as src/services/billing/, the client walks upward toward the root filesystem. It discovers every CLAUDE.md along the path and concatenates them into prompt context. Instructions from ancestor directories load first, and instructions closest to your current working directory load last. Within each directory level, CLAUDE.local.md is appended after CLAUDE.md.
Sizing Guidelines and Technical Limits
Anthropic sets practical boundaries on CLAUDE.md files: an advisory guideline of under 200 lines, and a hard technical limit of 4 MiB.
Files exceeding 200 lines consume substantial input tokens on every turn and dilute attention. When instruction files become bloated with dense paragraphs or API documentation, Claude follows instructions less consistently. If a CLAUDE.md file exceeds 4 MiB, Claude Code skips reading the file entirely.
To prevent context bloat, keep your root CLAUDE.md concise. Restrict entries to universal project facts:
- Primary build and test commands (
npm test,cargo build --release) - Strict architectural rules ("API handlers live in
src/handlers/") - Concrete styling constraints ("Use 2-space indentation and single quotes")
- Operational prerequisites ("Run database migrations before starting the test runner")
Organizing Modular Instructions with Path-Scoped Rules
Rather than forcing every instruction into a single root file, use the .claude/rules/ directory to modularize guidance. Rules placed in .claude/rules/*.md support YAML frontmatter with a paths property. These path-scoped rules remain out of context until Claude reads or edits a matching file:
---
paths:
- "src/api/**/*.ts"
- "src/controllers/**/*.ts"
---
### API Endpoint Rules
- All request bodies must validate through Zod schemas before processing
- Return errors using the standardized AppError class
- Do not import database models directly into controller files
Path-scoped rules use glob patterns to target specific modules. Claude Code allocates a budget of 1,000 expanded patterns and 4 MiB for rule evaluation. Unscoped rules load unconditionally at session startup, while path-scoped rules load on demand when matching files are touched, preserving context space for active tasks.
Imports and External References
CLAUDE.md files support @path/to/file import syntax. You can reference supplementary documentation such as @docs/git-workflow.md or @package.json. Claude Code expands imported files inline at session start up to four hops deep.
Imports do not save context tokens. Because Claude Code expands @ imports during session initialization, importing a 500-line markdown file consumes the exact same token budget as writing those 500 lines directly into CLAUDE.md. Use imports for organizational cleanliness, not for context reduction.
To audit instruction files for obsolete commands or conflicting rules, run /doctor prompt-audit inside your session. Claude scans CLAUDE.md, CLAUDE.local.md, and .claude/rules/ to identify contradictory statements and recommends concrete trims.
How Auto-Memory Structures Project Learnings Under the 200-Line Limit
Auto-memory is Claude Code's autonomous persistence mechanism. As you work through bugs, refine shell commands, or specify workflow preferences, Claude records key learnings to disk without requiring manual file edits.
Auto-memory files reside on your local machine under your home directory:
~/.claude/projects/<project-hash>/memory/
├── MEMORY.md # Master index file loaded at every session launch
├── user_role.md # User preferences and role notes
├── feedback_testing.md # Corrected patterns and confirmed approaches
└── project_context.md # Architectural constraints Claude cannot derive from code
The project directory name derives from the repository's Git origin. All Git worktrees and subdirectories within the same repository share a single auto-memory store.
The Two-Layer Storage Architecture
Auto-memory splits persistence into an indexed two-layer system:
- The
MEMORY.mdindex. A concise summary file containing one-line references to discovered facts. The first 200 lines ofMEMORY.md, or the first 25KB, whichever comes first, load into prompt context at the start of every session. - Granular topic files. Dedicated markdown documents covering specific subjects. Each topic file begins with YAML frontmatter specifying its category (
user,feedback,project, orreference) and an ISO 8601modifiedtimestamp.
Topic files do not load into context at session startup. When Claude needs details referenced in MEMORY.md, it uses its standard file-reading tools to inspect the specific topic file on demand. This separation protects working context while preserving detailed historical records.
Index Limits and Self-Compacting Maintenance
Anthropic limits Claude Code auto-memory by loading only the first 200 lines or 25KB of MEMORY.md at session start. Any content recorded beyond that line or byte threshold is dropped from startup context.
To keep the index operational, Claude Code evaluates MEMORY.md after every autonomous write:
- When
MEMORY.mdapproaches the 200-line or 25KB ceiling, Claude Code issues an internal reminder instructing Claude to consolidate entries, move narrative detail into topic files, and delete obsolete notes. - If a write pushes
MEMORY.mdover 200 lines or 25KB, the write lands on disk, but Claude Code returns an error instructing Claude to rewrite and compress the index immediately.
Claude records only facts it cannot deduce directly from source code. It skips directory layouts, dependencies listed in package manifests, and standard syntax rules. If you state an instruction already present in CLAUDE.md, Claude omits it from auto-memory.
Managing and Inspecting Auto-Memory
You can review stored memories at any point. Running /memory opens an interactive menu displaying all active CLAUDE.md files, local overrides, and the auto-memory directory. You can view, edit, or delete any generated topic file directly in your default editor.
To disable auto-memory for environments where autonomous persistence is undesirable, such as automated build sandboxes, use one of three configuration methods:
- Run
/memoryand toggle auto-memory off. This updates your global user configuration in~/.claude/settings.json. - Add
"autoMemoryEnabled": falseto your project's.claude/settings.jsonfile. - Set the shell environment variable
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1.
Extend Claude Code Beyond Local Context Limits
Connect Claude Code to a shared Fast.io workspace over Streamable HTTP for persistent storage, semantic retrieval, and versioned file coordination. Monthly plans start with a 14-day free trial.
What Survives Session Summarization During Context Compaction?
The active context window governs how many tokens Claude Code can evaluate simultaneously during an interactive session. Standard sessions operate with a 200,000-token context window, while extended model configurations provide a 1,000,000-token context window.
Context space is consumed continuously as you work. A standard session startup claims roughly 8,000 to 12,000 tokens before you submit your first prompt:
- System prompt instructions: ~4,200 tokens
- Auto-memory index (
MEMORY.md): ~680 tokens - Environment metadata (OS, Git branch, shell): ~280 tokens
- Deferred MCP tool definitions: ~120 tokens
- Skill index metadata: ~450 tokens
- Global and project
CLAUDE.mdfiles: ~2,000 to 4,000 tokens
Once work begins, file reads dominate context consumption. Reading a 600-line TypeScript file consumes roughly 2,400 tokens. Running test suites, inspecting build traces, and generating diffs quickly push consumption toward the context ceiling.
Automatic Compaction and Progressive Detail Degradation
When token consumption approaches the context ceiling, Claude Code triggers automatic compaction. Compaction condenses earlier conversation turns into a structured summary to free up tokens for new work. You can also trigger this process manually by typing /compact or /compact focus on the API migration.
While compaction keeps the terminal session alive, it causes progressive detail degradation. The compression pass retains high-level semantic intent while shedding granular specifics:
- Variable names, exact stack traces, and code diffs from twenty turns ago disappear from active context.
- Intermediate reasoning steps are discarded.
- Specific constraints stated casually in dialogue get compressed into generic bullet points.
Understanding what survives compaction helps you avoid lost work:
Context Preservation Strategies
To maintain technical precision across extended coding sessions, apply three operational practices:
- Clear context between disparate tasks. When switching from debugging an authentication module to building a reporting dashboard, run
/clear. Retaining old debugging traces wastes tokens and causes prompt interference. - Offload research to subagents. Instead of having Claude Code read twenty source files in your main conversation, instruct it to delegate research to a subagent. The subagent inspects files within an isolated context window and returns a concise 400-token summary to your main session, saving thousands of tokens.
- Commit volatile constraints to disk. Never rely on conversational instructions for critical rules. If an architectural decision must persist across compaction, write it into
CLAUDE.mdor ask Claude to save it to memory.
How to Structure Large Reference Repositories Outside Local Context
As software projects expand, reference materials outgrow local file systems. Enterprise codebases often depend on large external corpora: internal API schemas, multi-megabyte PDF compliance manuals, architectural design documents, and cross-team interface contracts.
Attempting to store this reference material inside repository files creates severe operational friction. Inlining documents into CLAUDE.md triggers immediate context bloat. Storing raw reference documents inside the repository forces Claude Code to exhaust tokens running grep queries and full-file reads.
Conventional Approaches and Their Constraints
Teams typically attempt three workarounds to manage large reference collections:
- Local markdown docsets: Splitting documentation into
.claude/rules/files. While path-scoped rules prevent startup context bloat, Claude must still read the full text into working memory whenever a rule matches, consuming tokens rapidly during complex refactors. - Commodity cloud storage folders: Storing documentation in Google Drive, Dropbox, or Box folders. These repositories serve human file sync well, but coding agents cannot natively index or semantically query them without custom scripts and manual downloads.
- Dedicated vector databases: Deploying specialized RAG infrastructure such as Pinecone, Milvus, or Qdrant. While performant, vector databases require custom ingestion pipelines, chunking heuristics, embedding model maintenance, and API middleware that engineering teams must operate and secure.
Connecting Intelligent Workspaces via Streamable HTTP
An intelligent workspace provides a cleaner architecture. Fast.io serves as an external coordination and knowledge layer where large file collections reside in indexed storage accessible to both humans and autonomous agents.
Rather than stuffing reference documentation into local repositories, teams ingest specification files, client deliverables, and architectural manuals directly into a shared workspace. Files can be uploaded directly or synchronized from existing cloud drives. Cloud sync is supported for Google Drive, Dropbox, Box, and OneDrive on a schedule or on demand.
When Intelligence Mode is enabled on a workspace, files are indexed automatically upon arrival using hybrid search that combines full-text indexing, semantic retrieval, and metadata filtering. This eliminates the need to configure separate vector databases or embedding pipelines.
Claude Code connects directly to Fast.io using Model Context Protocol (MCP) over Streamable HTTP. To add the remote server, execute the following command in your terminal:
claude mcp add --transport http fast-io https://mcp.fast.io/mcp/code
After adding the server, run /mcp inside Claude Code to complete the OAuth sign-in flow in your browser. Alternatively, configure the server at project scope by adding an entry to .mcp.json:
{
"mcpServers": {
"fast-io": {
"type": "http",
"url": "https://mcp.fast.io/mcp/code"
}
}
}
For detailed setup instructions, consult the official MCP setup guide and the machine-readable MCP tooling documentation.
Once connected to https://mcp.fast.io/mcp/code, Claude Code accesses a consolidated toolset including search, execute, and upload. Instead of reading a 20MB API specification into its active context window, Claude Code issues a semantic search query against the workspace. Fast.io performs the retrieval across indexed documents and returns precise, citation-backed excerpts directly into the session.
This workflow preserves the 200,000-token context window for code generation, diff analysis, and test execution. Reference knowledge stays durable, versioned, and centralized in cloud storage rather than fragmenting across developer machines.
Beyond search, the workspace provides team coordination capabilities:
- Per-file version history: Every file update retains a complete version history. If an agent modifies an architecture brief or specification, prior revisions remain accessible and restorable.
- Detailed activity log: Tracks uploads, edits, moves, and deletions, alongside membership and permission changes made by team members and connected agents.
- Structured extraction: For complex contracts or invoices, Metadata Views extract typed attributes into queryable schemas without manual parsing.
- Collaborative notes: Shared workspace notes indexed for AI grounding, where developers and agents draft specifications with version-checked saves.
Monthly plans start with a 14-day free trial, which requires a credit card. Subscriptions are structured into Starter at $9.99/mo (3 seats, 250 GB storage, 5 workspaces, 100,000 credits a month), Business at $49.99/mo (10 seats, 5 TB storage, 50 workspaces, 600,000 credits a month), and Enterprise at $199.99/mo (30 seats included, 25 TB storage, 200 workspaces, 3,000,000 credits a month). Credits meter AI indexing and search operations, with credit overage billed at $10 per 100,000 credits.
Sources
References used to verify factual claims in this guide.
-
Anthropic limits Claude Code instruction files to an advisory target under 200 lines and loads the first 200 lines or 25KB of MEMORY.md at session start.
-
Claude Projects permits an unlimited number of files up to 30MB each, bounded by the overall context window.
Frequently Asked Questions
What is the memory limit in Claude Code?
Claude Code memory operates under three distinct tiers. Active sessions run within a working context window of 200,000 tokens (or 1,000,000 tokens on extended models) before automatic compaction triggers. Static instruction files like `CLAUDE.md` have a hard file ceiling of `4 MiB`, with an advisory target under 200 lines to preserve adherence. The auto-memory index file, `MEMORY.md`, enforces an operational load limit of 200 lines or 25KB at session startup.
How does Claude Code store memory across sessions?
Claude Code stores cross-session memory locally in plain Markdown files. Human instructions live in repository-level `CLAUDE.md` files, user preferences in `~/.claude/CLAUDE.md`, and system policies in managed directory paths. Dynamic agent learnings are written autonomously to `~/.claude/projects/<project-hash>/memory/` inside a `MEMORY.md` index and individual categorized topic files.
How do you prevent Claude Code from running out of memory?
Prevent context exhaustion by keeping instruction files concise (targeting 200 lines or fewer), organizing modular guidance into path-scoped rules under `.claude/rules/`, and running `/clear` between unrelated tasks. For large documentation sets, connect an external workspace over MCP rather than inlining files, and delegate heavy codebase research to subagents with isolated context windows.
What happens when MEMORY.md exceeds 200 lines or 25KB?
When `MEMORY.md` exceeds 200 lines or 25KB, Claude Code drops all content beyond that threshold during session startup. To prevent data loss, Claude Code checks the file after writes and prompts Claude to shorten entries, merge duplicates, and shift detailed notes into standalone topic files.
Does CLAUDE.md survive session compaction?
Yes. Project-root `CLAUDE.md` files and unscoped rules survive compaction because Claude Code re-reads them from disk and re-injects them into the compacted session. However, conversation-only instructions and nested `CLAUDE.md` files in subdirectories do not persist in active context until re-triggered by file activity.
Related Resources
Extend Claude Code Beyond Local Context Limits
Connect Claude Code to a shared Fast.io workspace over Streamable HTTP for persistent storage, semantic retrieval, and versioned file coordination. Monthly plans start with a 14-day free trial.