Project Memory
Location: ./CLAUDE.md
Shared team knowledge - architecture, standards, workflows
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
:
{ "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:
The fastest way to add memory is using the #
shortcut:
# Always use snake_case for Python variables
Claude prompts you to select which memory file should store this instruction, making documentation effortless during development.
Initialize with /init
command
claude> /init
Claude analyzes your project and generates a comprehensive CLAUDE.md template.
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
Add project-specific context Include information that saves repeated explanations:
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 WorkflowFollow 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):
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:
/project/CLAUDE.md
(parent)/project/packages/frontend/CLAUDE.md
(current)Structure memories to reflect service boundaries:
## Authentication Service- Port: 3001- Database: auth_db- Key endpoints: - POST /login - POST /refresh - POST /logout
## TestingRun tests with: `npm test -- --service=auth`
## Dependencies- JWT library: @auth0/node-jsonwebtoken- Password hashing: bcrypt
Example:
# API Error HandlingAlways 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
Bad example:
# Code StyleMake sure the code is clean and follows best practices
Use /memory
command to inspect loaded memories:
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:
Memory files cascade from general to specific:
# Root CLAUDE.mdAll 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 REQUIREMENTSMANDATORY: All PII must be encrypted at rest and in transitMANDATORY: Log all data access with user ID and timestampMANDATORY: Run security scan before any deployment
# Automated Compliance HooksWhen 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
# PERFORMANCE REQUIREMENTS- API responses must return within 200ms (p95)- Database queries must use indexes (no table scans)- Frontend bundle size < 250KB gzipped
# Performance Patterns## Database Queries@./docs/query-optimization.md
## Caching Strategy- Redis for session data (15 min TTL)- CDN for static assets (1 year TTL)- API responses cached for 5 minutes
## Monitoring- Add performance.mark() for key operations- Log slow queries (>100ms) to monitoring- Alert on memory usage >80%
# SECURITY PROTOCOLSCRITICAL: Never commit credentials or secretsCRITICAL: All user inputs must be sanitizedCRITICAL: Use prepared statements for all SQL
# Authentication Standards@~/.claude/security-standards.md
# Security ChecklistBefore any PR:[ ] Run `npm audit` and fix vulnerabilities[ ] Verify no hardcoded secrets (use scanner)[ ] Check authentication on all new endpoints[ ] Validate and sanitize all inputs[ ] Update security documentation
# Incident ResponseOn security incident:1. Notify security team immediately2. Don't attempt fixes without approval3. Document all actions in incident log
Combine memory with hooks for intelligent automation:
{ "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:
const fs = require('fs');const path = require('path');
const memoryPath = '.claude/memory.json';const memory = JSON.parse(fs.readFileSync(memoryPath, 'utf8'));
// Update last modified filesconst 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 ResponsesAll 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 Development1. 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
CLAUDE.md
(case-sensitive)pwd
to confirm current directory/memory
- Lists all loaded memory files# Debug import issues1. Absolute paths must exist: @/absolute/path/file.md2. Relative paths from memory file location: @../docs/api.md3. Home directory expansion works: @~/documents/notes.md4. Max depth is 5 levels of imports
Monitor token usage if experiencing slowdowns:
# Check memory token consumptionclaude> /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:
project/├── CLAUDE.md # Shared├── CLAUDE.local.md # Personal (gitignored)└── .gitignore # Contains CLAUDE.local.md
project/├── CLAUDE.md # Contains: @~/.claude/project-personal.md└── ~/.claude/ └── project-personal.md # Personal settings
Benefits of the new approach:
Hooks Automation
Trigger memory updates automatically with hooks
Team Workflows
Implement memory strategies for large teams
Performance Tuning
Optimize memory for faster Claude responses