Claude CodeContext & Memory
Context & Memory
How Claude Code builds its system prompt, loads CLAUDE.md files, manages auto-memory, and provides context to the model at every turn.
System Prompt Assembly
1
Default System Prompt
Base Claude instructions (2000+ tokens). Tool definitions dynamically generated from all registered tools. MCP server instructions. Agent definitions. Skill/command discovery hints. Model-specific variants (Opus: full, Sonnet: abbreviated if >50 tools).
2
User Context
Working directory, platform, shell, git status (branch, recent commits, truncated to 2000 chars). Additional directories permissions. Project metadata. Prepended to messages via prependUserContext().
3
System Context
Available resources, MCP server capabilities, coordinator context (if multi-agent mode). Appended via appendSystemContext().
4
Memory Mechanics
If auto-memory enabled, injects memory mechanics prompt with instructions for reading/writing to memory directory.
// Final assembly in QueryEngine.ts:
const systemPrompt = asSystemPrompt([
...(customPrompt ? [customPrompt] : defaultSystemPrompt),
...(memoryMechanicsPrompt ? [memoryMechanicsPrompt] : []),
...(appendSystemPrompt ? [appendSystemPrompt] : []),
])CLAUDE.md Loading
CLAUDE.md files provide project-specific instructions. They're loaded from multiple locations and concatenated into the user context:
// Load order (all concatenated):
1. ~/.claude/CLAUDE.md → User's global instructions
2. <project>/.claude/CLAUDE.md → Project instructions (checked in)
3. <project>/CLAUDE.md → Project root (convenience)
4. ~/.claude/projects/<path>/CLAUDE.md → Project-specific user instructions
// Each CLAUDE.md section labeled with source path:
"Contents of /Users/user/.claude/CLAUDE.md (user's private global):"
"Contents of /project/CLAUDE.md (project instructions, checked in):"
// Injected as <system-reminder> tags in conversation context
// Available to model at every turnAuto-Memory System (memdir/)
Persistent project-scoped memory stored at ~/.claude/projects/<path>/memory/. Four memory types with structured format.
// Directory structure:
~/.claude/projects/<path>/memory/
MEMORY.md # Index (200 lines max, 25KB max)
user/
profile.md # Role, preferences
preferences.md
feedback/
testing_policy.md # Corrections & validations
project/
current_sprint.md # Ongoing work context
reference/
slack_channels.md # External system pointers
// Memory file format (frontmatter):
---
name: {{memory name}}
description: {{one-line description}}
type: user | feedback | project | reference
---
{{content — fact, then **Why:** and **How to apply:** lines}}
// MEMORY.md is always loaded into conversation context
// Lines after 200 are truncated
// Each entry is one line, under 150 charsMemory Extraction Pipeline
// extractMemories.ts — runs after each query loop
1. Triggered by handleStopHooks at end of query
2. Runs as forked agent (lightweight, cache-sharing)
3. initExtractMemories() — one-time closure initialization
4. Detects memory writes by main agent (skips range)
5. Extracts anything model missed
6. Two prompt modes:
- buildExtractAutoOnlyPrompt() — auto-memory only
- buildExtractCombinedPrompt() — private + team memory
7. Saves to auto-memory directory with proper typing
// Session Memory (separate service):
- Runs periodically via background forked agent
- Different cadence: init threshold vs. update threshold
- Templates loaded from prompts directory
- Feature-gated (tengu_passport_quail)AppState Store
Central application state using Zustand-like pattern with DeepImmutable for type safety:
// AppStateStore.ts — key state fields:
{
// Settings & Models
settings, mainLoopModel, mainLoopModelForSession
// Permissions
toolPermissionContext: {
mode: 'default' | 'auto' | 'plan' | 'bypass'
additionalWorkingDirectories: Map
alwaysAllowRules, alwaysDenyRules, alwaysAskRules
}
// MCP Integration
mcp: { clients, tools, commands, resources }
// Plugin System
plugins: { enabled, disabled, installationStatus }
// Agent Features
thinkingEnabled, promptSuggestionEnabled, speculation
// Coordinator Mode
coordinatorTaskIndex, workerTools, workerSandboxPermissions
// Team Swarms (KAIROS feature)
teamContext, standaloneAgentContext, inbox
// UI State
expandedView, footerSelection, fastMode, effortValue
}
// Mutation: setAppState(prev => ({ ...prev, field: newValue }))
// Triggers UI re-render in REPL modeMessage Types
// API-compatible types:
UserMessage → user input, tool results, text content
AssistantMessage → model response, thinking blocks, tool_use blocks
SystemMessage → various metadata subtypes
// Synthetic types (stripped before API call):
SystemLocalCommandMessage → local command output
TombstoneMessage → marks orphaned partial messages
CompactBoundaryMessage → marks session summary boundaries
ToolUseSummaryMessage → generated summary of tool batch
// Session persistence:
~/.claude/sessions/[sessionId]/transcript.jsonl
// Records every turn for crash recovery via /resume