Mastering Claude Code: Memory Management and Context Persistence
The Memory Hierarchy
In Part 4, we connected Claude Code to external services through MCP connectors and plugins. Now we’ll explore the foundation that ties everything together: Claude Code’s complete memory system—a hierarchical structure that enables context persistence across sessions, teams, and organizations.
Memory in Claude Code isn’t just configuration. It’s persistent context that shapes how Claude understands your projects, preferences, and workflows.
Memory Types and Locations
Claude Code supports five levels of memory, each serving a distinct purpose:
| Memory Type | Location | Purpose | Shared With |
|---|---|---|---|
| Managed policy | /Library/Application Support/ClaudeCode/CLAUDE.md (macOS) | Organization-wide instructions | All organization users |
| Project memory | ./CLAUDE.md or ./.claude/CLAUDE.md | Team-shared project instructions | Team via source control |
| Project rules | ./.claude/rules/*.md | Modular, topic-specific instructions | Team via source control |
| User memory | ~/.claude/CLAUDE.md | Personal preferences for all projects | Just you (all projects) |
| Project local | ./CLAUDE.local.md | Personal project-specific preferences | Just you (this project) |
Priority Order: Higher levels take precedence. Organization policies override everything, while local preferences are most specific.
How Memory Discovery Works
When Claude Code launches, it discovers memories through a recursive process:
- Starts in the current working directory
- Recursively checks parent directories up to (but not including) root
- Loads any
CLAUDE.mdorCLAUDE.local.mdfiles found - Discovers nested
CLAUDE.mdfiles in subtrees (loaded when those files are accessed)
Example: Running Claude in myproject/src/components/ discovers:
myproject/CLAUDE.mdmyproject/src/CLAUDE.md(if it exists)myproject/src/components/CLAUDE.md(if it exists)~/.claude/CLAUDE.md
This allows you to have general project instructions at the root and more specific instructions in subdirectories.
Setting Up Project Memory
Initialize project memory with a single command:
> /initThis creates a bootstrapped CLAUDE.md tailored to your codebase. Here’s what to include:
# Project: My Application
## Commands- `npm run dev` - Start development server- `npm run test` - Run test suite- `npm run build` - Production build
## Architecture- React 18 with TypeScript- State management: Zustand- Styling: Tailwind CSS
## Conventions- Use functional components with hooks- Prefer named exports- Tests live next to source files (*.test.ts)
## Important Patterns- All API calls go through `src/lib/api.ts`- Authentication state in `src/stores/auth.ts`Modular Rules with .claude/rules/
For larger projects, modular rules provide organization:
your-project/├── .claude/│ ├── CLAUDE.md # Main project instructions│ └── rules/│ ├── code-style.md # Code style guidelines│ ├── testing.md # Testing conventions│ ├── security.md # Security requirements│ └── api/│ ├── rest.md # REST API conventions│ └── graphql.md # GraphQL conventionsAll .md files in .claude/rules/ are automatically loaded with project-level priority.
Path-Specific Rules
Apply rules only to specific files using YAML frontmatter:
---paths: - "src/api/**/*.ts"---
# API Development Rules
- All API endpoints must include input validation- Use the standard error response format- Include OpenAPI documentation commentsWithout a paths field, rules apply to all files unconditionally.
Glob Patterns
Supported patterns for path-specific rules:
| Pattern | Matches |
|---|---|
**/*.ts | All TypeScript files in any directory |
src/**/* | All files under src/ |
*.md | Markdown files in project root only |
src/components/*.tsx | React components in specific directory |
Multiple patterns and brace expansion:
---paths: - "src/**/*.{ts,tsx}" - "{src,lib}/**/*.ts" - "tests/**/*.test.ts"---Organizing Rules with Subdirectories
.claude/rules/├── frontend/│ ├── react.md│ └── styles.md├── backend/│ ├── api.md│ └── database.md└── general.mdSharing Rules with Symlinks
Link to shared rule sets across projects:
# Link a shared rules directoryln -s ~/shared-claude-rules .claude/rules/shared
# Link a specific rule fileln -s ~/company-standards/security.md .claude/rules/security.mdCircular symlinks are detected and handled gracefully.
CLAUDE.md Imports
Import additional files using @path/to/import syntax:
See @README for project overview and @package.json for npm commands.
# Additional Instructions- Git workflow: @docs/git-instructions.md- API docs: @docs/api-reference.mdSupported paths:
- Relative:
@docs/git-instructions.md - Absolute:
@~/.claude/my-project-instructions.md
Limitations:
- Maximum import depth: 5 hops
- Imports not evaluated inside markdown code spans/blocks
- Recursive imports supported
User-Level Memory
Personal preferences in ~/.claude/CLAUDE.md apply to all projects:
# My Preferences
## Workflow- Always create a plan before implementation- Summarize results after completion- Don't commit unless asked directly
## Code Style- Use functional programming patterns where appropriate- Prefer immutable data structures- Use descriptive variable names
## Communication- Be concise in explanations- Include code examples- Reference file:line when discussing codeUser-Level Rules
Create personal rules in ~/.claude/rules/ that apply everywhere:
~/.claude/rules/├── preferences.md # Personal coding preferences├── workflows.md # Preferred workflows└── security.md # Personal security checklistUser-level rules load before project rules, so project rules take priority when there’s a conflict.
Project-Local Memory
For personal project-specific preferences that shouldn’t be shared:
## My Local Environment- Development server runs on port 3001 (not default 3000)- Using local PostgreSQL on port 5433- Test database: myproject_test_local
## Personal Notes- Focus on the checkout module this sprint- Remember: the legacy API is being deprecatedCLAUDE.local.md files are automatically added to .gitignore.
Managing Memory During Sessions
View Loaded Memories
> /memoryShows all memory files currently loaded by Claude Code.
Edit Memory Files
> /memoryOpens memory files in your system editor for extensive additions or reorganization.
Organization-Wide Policies
For teams, deploy centrally managed policies:
-
Create the managed memory file at the Managed policy location:
- macOS:
/Library/Application Support/ClaudeCode/CLAUDE.md - Linux:
/etc/claude-code/CLAUDE.md - Windows:
C:\Program Files\ClaudeCode\CLAUDE.md
- macOS:
-
Deploy via configuration management (MDM, Ansible, Group Policy)
-
All developers automatically receive consistent instructions
Example organization policy:
# Organization Standards
## Security Requirements- Never commit secrets or API keys- Use environment variables for configuration- Follow OWASP security guidelines
## Code Review- All changes require PR review- Include tests for new functionality- Update documentation when APIs change
## Compliance- Log all data access operations- Respect data retention policies- Follow GDPR requirements for user dataBest Practices
Writing Effective Memory
Be specific:
# Good- Use 2-space indentation- Maximum line length: 100 characters- Use camelCase for variables, PascalCase for components
# Vague- Format code properly- Use good namingUse structure:
## API Development
### Endpoints- Use RESTful conventions- Version all APIs (/api/v1/...)
### Error Handling- Return appropriate HTTP status codes- Include error details in response bodyKeep rules focused:
# testing.md - focused on one topic---paths: - "**/*.test.ts" - "**/*.spec.ts"---
# Testing Standards- Use describe/it blocks for organization- Mock external dependencies- Aim for 80% coverage on critical pathsOrganization Strategies
| Project Size | Strategy |
|---|---|
| Small | Single CLAUDE.md at root |
| Medium | CLAUDE.md + 2-3 rule files |
| Large | Full .claude/rules/ with subdirectories |
| Monorepo | Per-package CLAUDE.md + shared rules via symlinks |
Review and Maintenance
- Review periodically - Update memories as your project evolves
- Remove obsolete rules - Outdated instructions cause confusion
- Test path patterns - Verify rules apply to intended files
- Document rule purpose - Future you will thank present you
Memory vs. Commands vs. Agents
Understanding when to use each:
| Use Case | Solution |
|---|---|
| Project-specific context | Memory (CLAUDE.md) |
| Personal preferences | User memory (~/.claude/CLAUDE.md) |
| Reusable workflows | Commands (~/.claude/commands/) |
| Specialized expertise | Agents (~/.claude/agents/) |
| Persistent file-type rules | Rules (.claude/rules/) |
Memory provides context. Commands provide actions. Agents provide expertise.
Conclusion
Claude Code’s memory system is the connective tissue that makes everything else work. By understanding the five-level hierarchy—from organization policies to project-local preferences—you can build configurations that scale from personal projects to enterprise deployments.
Key takeaways:
- Memory is hierarchical: Organization → Project → Rules → User → Local
- Discovery is recursive: Claude finds memories from current directory up to home
- Rules are modular: Path-specific rules apply only to matching files
- Imports extend reach: Reference external files with
@path/to/filesyntax
Well-structured memory reduces the context you need to provide in every conversation. Your standards, conventions, and project knowledge persist automatically.
Complete Memory Structure
Here’s the complete memory hierarchy for a well-configured setup:
/Library/Application Support/ClaudeCode/└── CLAUDE.md # Organization policy
~/.claude/├── CLAUDE.md # Personal global preferences└── rules/ ├── preferences.md # Personal coding style └── workflows.md # Personal workflows
your-project/├── CLAUDE.md # Project instructions (shared)├── CLAUDE.local.md # Personal project prefs (not shared)└── .claude/ ├── CLAUDE.md # Alternative location └── rules/ ├── code-style.md # Team code standards ├── testing.md # Testing conventions ├── security.md # Security requirements └── frontend/ ├── react.md # React-specific rules └── styles.md # Styling conventionsWhat’s Next
With memory, commands, agents, and plugins in place, there’s one frontier remaining: the browser.
In Part 6, we’ll explore Chrome browser automation:
- Live debugging - Claude reads console errors and fixes code in real-time
- Design verification - Build UI and verify it directly in the browser
- Web app testing - Automated form validation and user flow testing
- Authenticated workflows - Interact with Google Docs, Gmail, Notion without API setup
- Session recording - Capture browser interactions as GIFs
Next in series: Chrome Browser Automation - Bridging terminal and browser