Skip to content

Claude Code Memory System

Claude Code’s memory system transforms project context management from a manual burden into an intelligent, hierarchical knowledge base. By leveraging CLAUDE.md files and strategic memory placement, you create persistent context that makes Claude understand your project as deeply as you do.

Claude Code uses a sophisticated multi-tier memory system that loads automatically at startup:

Project Memory

Location: ./CLAUDE.md
Shared team knowledge - architecture, standards, workflows

User Memory

Location: ~/.claude/CLAUDE.md
Personal preferences applying to all projects

Persistent Memory

Location: .claude/memory.json
Dynamic memory that Claude updates during sessions

Local Memory

Location: ./CLAUDE.local.md
Personal project-specific settings (deprecated - use imports)

Claude Code can maintain persistent memory across sessions using .claude/memory.json:

.claude/memory.json
{
"project_facts": {
"internal_library": "We use LibraryY for all HTTP calls",
"deployment_server": "Production deploys to AWS us-east-1",
"test_database": "Test DB resets daily at 3 AM UTC"
},
"session_context": {
"current_feature": "Implementing OAuth2 integration",
"blocked_by": "Waiting for security team approval",
"last_error": "Redis connection timeout in staging"
},
"team_patterns": {
"pr_reviewer": "Alice reviews all auth changes",
"deploy_schedule": "Tuesdays and Thursdays only"
}
}

This memory persists between sessions and can be updated programmatically through Claude or hooks.

Claude Code employs a recursive search strategy for maximum flexibility:

graph TD A[Current Directory] --> B{CLAUDE.md exists?} B -->|Yes| C[Load into context] B -->|No| D[Check parent directory] D --> E{Reached root /?} E -->|No| B E -->|Yes| F[Stop searching] C --> G[Search subdirectories] G --> H[Load on-demand when accessing files]

The fastest way to add memory is using the # shortcut:

Terminal window
# Always use snake_case for Python variables

Claude prompts you to select which memory file should store this instruction, making documentation effortless during development.

  1. Initialize with /init command

    Terminal window
    claude> /init

    Claude analyzes your project and generates a comprehensive CLAUDE.md template.

  2. Structure your memory hierarchically

    # Project Architecture
    - Frontend: Next.js 14 with App Router
    - Backend: Node.js Express API
    - Database: PostgreSQL with Prisma ORM
    # Build Commands
    - `npm run dev` - Start development server
    - `npm run build` - Production build
    - `npm test` - Run test suite
    # Coding Standards
    - Use TypeScript strict mode
    - Prefer named exports over default exports
    - All API responses follow { data, error } pattern
    # Key Files
    - `/src/lib/auth.ts` - Authentication utilities
    - `/src/db/schema.prisma` - Database schema
    - `/docs/API.md` - API documentation
  3. Add project-specific context Include information that saves repeated explanations:

    • Common gotchas and workarounds
    • Deployment procedures
    • Testing strategies
    • Performance considerations

CLAUDE.md files support powerful import functionality using @path/to/file syntax:

# See @README.md for project overview
# API docs: @docs/api/endpoints.md
# Database schema: @src/db/schema.sql
## Git Workflow
Follow our branching strategy @docs/git-workflow.md

Enable individual preferences without repository pollution:

# Team Configuration
- Shared standards: @docs/team-standards.md
- Individual settings: @~/.claude/project-name-personal.md

Team members create their own ~/.claude/project-name-personal.md:

# My Development Environment
- Local API URL: http://localhost:3001
- Test database: postgresql://user@localhost/myapp_test
- Preferred test user: alice@example.com

Imports can reference other imports (max depth: 5):

  • DirectoryCLAUDE.md (imports @config/base.md)
    • Directoryconfig/
      • Directorybase.md (imports @config/tools.md)
        • Directorytools.md (imports @config/shortcuts.md)
          • shortcuts.md

For complex monorepos, leverage hierarchical memory:

project/
├── CLAUDE.md # Root-level standards
├── packages/
│ ├── frontend/
│ │ └── CLAUDE.md # Frontend-specific patterns
│ ├── backend/
│ │ └── CLAUDE.md # API conventions
│ └── shared/
│ └── CLAUDE.md # Shared utilities docs

When running Claude from packages/frontend/, it loads:

  1. /project/CLAUDE.md (parent)
  2. /project/packages/frontend/CLAUDE.md (current)
  3. Subdirectory memories on-demand

Structure memories to reflect service boundaries:

services/auth/CLAUDE.md
## Authentication Service
- Port: 3001
- Database: auth_db
- Key endpoints:
- POST /login
- POST /refresh
- POST /logout
## Testing
Run tests with: `npm test -- --service=auth`
## Dependencies
- JWT library: @auth0/node-jsonwebtoken
- Password hashing: bcrypt
  • Specific commands with exact syntax
  • Architecture decisions with rationale
  • Common patterns your team uses
  • Gotchas and workarounds for known issues
  • File locations for key components
  • Testing procedures and requirements
  • Deployment checklists

Example:

# API Error Handling
Always wrap database calls in try-catch:
- Return { error: error.message, code: 'DB_ERROR' }
- Log full error to monitoring service
- Never expose stack traces to clients
  1. Review quarterly - Set calendar reminders to update memories
  2. Version with git - Track changes to shared CLAUDE.md files
  3. Test effectiveness - Ask Claude to perform tasks using only memory
  4. Gather feedback - Survey team on missing or confusing instructions
  5. Prune regularly - Remove outdated or unused instructions

Use /memory command to inspect loaded memories:

Terminal window
claude> /memory
Loaded memory files:
1. /Users/you/.claude/CLAUDE.md (451 tokens)
2. /project/CLAUDE.md (823 tokens)
3. /project/frontend/CLAUDE.md (312 tokens)
Total memory tokens: 1,586
Select a file to edit: [1-3]

In large monorepos, Claude Code supports sophisticated hierarchical memory patterns:

  • Directorymonorepo/
    • CLAUDE.md (root-level standards)
    • Directorybackend/
      • CLAUDE.md (backend-specific patterns)
      • Directoryservices/
        • Directoryauth/
          • CLAUDE.md (auth service specifics)
        • Directorypayments/
          • CLAUDE.md (payment processing rules)
    • Directoryfrontend/
      • CLAUDE.md (frontend conventions)
      • Directoryapps/
        • Directoryweb/
          • CLAUDE.md (web app specifics)
        • Directorymobile/
          • CLAUDE.md (mobile patterns)
    • Directoryshared/
      • CLAUDE.md (shared library guidelines)

Memory files cascade from general to specific:

backend/services/auth/CLAUDE.md
# Root CLAUDE.md
All services use error format: { code: string, message: string }
Override for auth: Include `retryAfter` field for rate limits

Claude automatically applies the most specific memory for the current working context.

# COMPLIANCE REQUIREMENTS
MANDATORY: All PII must be encrypted at rest and in transit
MANDATORY: Log all data access with user ID and timestamp
MANDATORY: Run security scan before any deployment
# Automated Compliance Hooks
When editing files in /src/api/user/*:
- Ensure all endpoints have @RequireAuth decorator
- Verify input validation on all POST/PUT requests
- Check for SQL injection vulnerabilities
# GDPR Compliance
- User data deletion must cascade to all services
- Export user data in JSON format within 30 days
- Maintain audit log for 7 years

Combine memory with hooks for intelligent automation:

.claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "node scripts/update-memory.js '$CLAUDE_FILE_PATHS'"
}]
}
],
"Stop": [
{
"hooks": [{
"type": "command",
"command": "node scripts/save-session-context.js"
}]
}
]
}
}

Example memory update script:

scripts/update-memory.js
const fs = require('fs');
const path = require('path');
const memoryPath = '.claude/memory.json';
const memory = JSON.parse(fs.readFileSync(memoryPath, 'utf8'));
// Update last modified files
const files = process.argv[2]?.split(',') || [];
memory.session_context.last_modified = files;
memory.session_context.last_update = new Date().toISOString();
fs.writeFileSync(memoryPath, JSON.stringify(memory, null, 2));
# Tech Stack
- Frontend: React 18 + TypeScript + Vite
- State: Zustand for global, React Query for server
- Backend: Express + TypeScript
- Database: PostgreSQL + Prisma
- Auth: JWT with refresh tokens
# Development
- Install: `npm install` in root (runs all workspaces)
- Dev mode: `npm run dev` (starts all services)
- Type check: `npm run type-check`
- Database: `npm run db:push` (sync schema)
# Architecture Patterns
## API Responses
All endpoints return: `{ success: boolean, data?: T, error?: string }`
## Frontend Data Fetching
- Use React Query for all API calls
- Implement optimistic updates for mutations
- Cache invalidation keys: ['users'], ['posts', postId]
## Database Queries
- Always use Prisma's `include` for relations
- Implement soft deletes (deletedAt field)
- Add indexes for frequent WHERE clauses
# Testing Strategy
- Unit tests: Critical business logic only
- Integration: API endpoints with test database
- E2E: Critical user flows with Playwright
# ML Pipeline Overview
- Data processing: Apache Spark on Databricks
- Training: PyTorch with Weights & Biases logging
- Serving: TorchServe behind API Gateway
- Monitoring: Prometheus + Grafana
# Environment Setup
@~/.claude/ml-credentials.md # Personal API keys
# Model Development
1. Data exploration: notebooks/exploration/
2. Feature engineering: src/features/
3. Model training: src/models/
4. Evaluation: src/evaluation/
# Key Commands
- `make dataset` - Build training dataset
- `make train MODEL=transformer` - Train model
- `make evaluate` - Run evaluation suite
- `make deploy ENV=staging` - Deploy model
# Code Standards
- Type hints required (mypy strict)
- Docstrings with Examples section
- Unit tests for all transforms
- Reproducibility: Set all random seeds
  1. Check file name - Must be exactly CLAUDE.md (case-sensitive)
  2. Verify location - Run pwd to confirm current directory
  3. Test with /memory - Lists all loaded memory files
  4. Check permissions - File must be readable
# Debug import issues
1. Absolute paths must exist: @/absolute/path/file.md
2. Relative paths from memory file location: @../docs/api.md
3. Home directory expansion works: @~/documents/notes.md
4. Max depth is 5 levels of imports

Monitor token usage if experiencing slowdowns:

Terminal window
# Check memory token consumption
claude> /memory stats
Memory Usage Summary:
- Project memories: 2,341 tokens
- User memory: 567 tokens
- Imported files: 1,823 tokens
- Total: 4,731 tokens (4.7% of context)
Largest files:
1. ./CLAUDE.md (1,234 tokens)
2. ~/.claude/CLAUDE.md (567 tokens)

The deprecated CLAUDE.local.md pattern is replaced by imports for better git workflow support:

Terminal window
project/
├── CLAUDE.md # Shared
├── CLAUDE.local.md # Personal (gitignored)
└── .gitignore # Contains CLAUDE.local.md

Benefits of the new approach:

  • Works across multiple git worktrees
  • Centralizes personal configuration
  • Eliminates gitignore management
  • Enables selective imports per project

Hooks Automation

Trigger memory updates automatically with hooks

Team Workflows

Implement memory strategies for large teams

Performance Tuning

Optimize memory for faster Claude responses