Skip to content

Mastering Claude Code: Memory Management and Context Persistence

5 min read

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 TypeLocationPurposeShared With
Managed policy/Library/Application Support/ClaudeCode/CLAUDE.md (macOS)Organization-wide instructionsAll organization users
Project memory./CLAUDE.md or ./.claude/CLAUDE.mdTeam-shared project instructionsTeam via source control
Project rules./.claude/rules/*.mdModular, topic-specific instructionsTeam via source control
User memory~/.claude/CLAUDE.mdPersonal preferences for all projectsJust you (all projects)
Project local./CLAUDE.local.mdPersonal project-specific preferencesJust 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:

  1. Starts in the current working directory
  2. Recursively checks parent directories up to (but not including) root
  3. Loads any CLAUDE.md or CLAUDE.local.md files found
  4. Discovers nested CLAUDE.md files in subtrees (loaded when those files are accessed)

Example: Running Claude in myproject/src/components/ discovers:

  • myproject/CLAUDE.md
  • myproject/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.

Mermaid diagram

Setting Up Project Memory

Initialize project memory with a single command:

Terminal window
> /init

This 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 conventions

All .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 comments

Without a paths field, rules apply to all files unconditionally.

Glob Patterns

Supported patterns for path-specific rules:

PatternMatches
**/*.tsAll TypeScript files in any directory
src/**/*All files under src/
*.mdMarkdown files in project root only
src/components/*.tsxReact 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.md

Link to shared rule sets across projects:

Terminal window
# Link a shared rules directory
ln -s ~/shared-claude-rules .claude/rules/shared
# Link a specific rule file
ln -s ~/company-standards/security.md .claude/rules/security.md

Circular 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.md

Supported 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 code

User-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 checklist

User-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:

CLAUDE.local.md
## 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 deprecated

CLAUDE.local.md files are automatically added to .gitignore.

Managing Memory During Sessions

View Loaded Memories

Terminal window
> /memory

Shows all memory files currently loaded by Claude Code.

Edit Memory Files

Terminal window
> /memory

Opens memory files in your system editor for extensive additions or reorganization.

Organization-Wide Policies

For teams, deploy centrally managed policies:

  1. 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
  2. Deploy via configuration management (MDM, Ansible, Group Policy)

  3. 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 data

Best 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 naming

Use structure:

## API Development
### Endpoints
- Use RESTful conventions
- Version all APIs (/api/v1/...)
### Error Handling
- Return appropriate HTTP status codes
- Include error details in response body

Keep 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 paths

Organization Strategies

Project SizeStrategy
SmallSingle CLAUDE.md at root
MediumCLAUDE.md + 2-3 rule files
LargeFull .claude/rules/ with subdirectories
MonorepoPer-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 CaseSolution
Project-specific contextMemory (CLAUDE.md)
Personal preferencesUser memory (~/.claude/CLAUDE.md)
Reusable workflowsCommands (~/.claude/commands/)
Specialized expertiseAgents (~/.claude/agents/)
Persistent file-type rulesRules (.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/file syntax

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 conventions

What’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


Written by

Farshad Akbari

Software engineer writing about Java, Kotlin TypeScript, Python, data systems and AI

Keyboard Shortcuts

Navigation

  • Open search ⌘K
  • Next article j
  • Previous article k

Actions

  • Toggle dark mode d
  • Toggle table of contents t
  • Show this help ?
  • Close modal Esc

Shortcuts are disabled when typing in inputs or textareas.