Module 2: Agent Memory and Scopes

1. Module Introduction — The Problem of Ephemeral Memory

1. Module Introduction — The Problem of Ephemeral Memory

Description

Your subagents from the previous module work — the reviewer reviews, the implementer fixes, the tester verifies. But they have a fundamental problem: they're amnesiac. Every time you invoke the reviewer, it starts from scratch. It doesn't remember that last week it flagged the same problematic patterns. It doesn't know that the team decided to use snake_case for all functions. It doesn't retain the architectural decisions that were already discussed. Each run is like hiring a new consultant who has never seen your project.

Memory scopes solve this. They let each subagent persist context across sessions with different levels of reach: user (all your sessions in any project), project (shareable via git with your team), and local (project-specific but private). The difference between an agent without memory and one with well-configured memory is the difference between an external consultant who comes once and a team member who accumulates institutional knowledge.

In this module you're going to configure a memory hierarchy that lets your subagents remember codebase patterns, architecture decisions, and team conventions — and you'll verify that this memory persists across sessions and is shared in a controlled way.


Where Are We in the Guide?

Context in the Path

Phase 1: Advanced Subagents
├── Module 1: Custom Subagents                    ← completed
├── Module 2: Agent Memory and Scopes             ← YOU ARE HERE
└── Module 3: Parallel Sub-Agent Delegation

Phase 2: Agent Teams and Plugins (Modules 4-6)
Phase 3: Orchestration (Modules 7-8)

In Module 1 you created subagents with an identity of their own — roles, restrictions, system prompts. Now you give them memory. Without this module, your agents are powerful but forgetful tools. With it, they become colleagues that learn from your project.

Where are we headed?

This module is the second pillar of Phase 1. The progression is deliberate:

  1. Module 1: Create agents with identity ← completed
  2. Module 2: Give those agents memory ← HERE — solve the amnesia problem
  3. Module 3: Put agents to work in parallel — they need shared memory so they don't make contradictory decisions

Memory is a prerequisite for parallel delegation. Parallel agents without shared context produce inconsistent results — the frontend agent uses camelCase while the backend agent uses snake_case because neither knows what the other decided.


The Problem: Agents That Forget Everything

The frustrating scenario

You run your reviewer subagent on a Python project:

Session 1 (Monday):
reviewer → "I found 3 functions without type hints in src/api/routes.py"
         → "The project convention should be snake_case, I found 2 inconsistencies"

Session 2 (Wednesday):
reviewer → "I found 3 functions without type hints in src/api/routes.py"  ← same issues
         → "I can't determine the project's naming convention"  ← it forgot snake_case

The reviewer detects the same problems because it doesn't remember having flagged them. It doesn't know the team already decided on the naming convention. Each session starts from scratch, repeating analysis and losing valuable context.

The real cost

Without persistent memory:

  • Repetition: The same issues are reported over and over
  • Inconsistency: Each run can produce different recommendations
  • Loss of context: Architectural decisions are forgotten between sessions
  • Inefficiency: The agent re-discovers what it already knew

With persistent memory:

  • Accumulation: The agent learns codebase patterns with each run
  • Consistency: It applies the same conventions every time
  • Context: It remembers previous decisions and respects them
  • Efficiency: It focuses on new issues, not on rediscovering known ones

What is lost without memory

Think about all the valuable context an agent discovers during a session:

20-minute session with the reviewer:

Discoveries:
- "src/api/ uses a service → repository → model pattern"
- "The helper functions are in src/utils/ organized by domain"
- "The project has 3 modules with >500 lines that could be refactored"
- "The naming convention is snake_case for everything except classes"
- "There are 2 deprecated dependencies in requirements.txt"
- "The tests use pytest with fixtures in conftest.py"

All this knowledge → lost when the session closes

Each of those discoveries took time and tokens. Without memory, the agent discovers them again — paying the same cost in time and tokens each time. With memory, it records them once and reuses them always.

The impact on costs

It's not just a quality problem — it's a measurable efficiency problem:

  • Without memory: Each session spends ~30% of tokens rediscovering the codebase
  • With memory: That 30% is invested once and reused in every subsequent session
  • In a project with 5 sessions per week: Memory saves ~120% of tokens per week on redundant work

The analogy

Imagine a development team where every morning everyone loses the memory of the previous day. Each standup is a complete reintroduction. Each PR review starts from "what are our conventions?" That's what happens with subagents without memory — technically capable, but institutionally ignorant.


How Memory Works in Claude Code

The mechanism: MEMORY.md

When you enable memory for a subagent, Claude Code creates a dedicated directory with a MEMORY.md file the agent can read and write. This file is automatically injected into the subagent's system prompt (the first 200 lines), giving it access to its accumulated knowledge at the start of each session.

Subagent without memory:
system_prompt = [your system prompt]

Subagent with memory (user scope):
system_prompt = [your system prompt] + [first 200 lines of ~/.claude/agent-memory/{name}/MEMORY.md]

The subagent can update MEMORY.md during execution — adding discovered patterns, recorded decisions, or codebase insights. These changes persist for the next session.

The three scopes

ScopeLocationWhen to use
user~/.claude/agent-memory/{name}/Universal knowledge: personal conventions, general patterns, preferences
project.claude/agent-memory/{name}/Project knowledge: architecture, team conventions, technical decisions. Shareable via git
local.claude/agent-memory-local/{name}/Project knowledge but private: credentials, personal notes, experiments

The key difference between project and local: project can be committed to git and shared with the team. Local is gitignored — only you see it.


Module Objective

By the end of this module you'll be able to:

  • ✅ Explain the three memory scopes (user, project, local) and when to use each one
  • ✅ Configure the memory field in a subagent's frontmatter to enable persistence
  • ✅ Instruct the subagent to update its memory proactively with patterns and decisions
  • ✅ Verify that context persists across sessions: run, close, reopen, and confirm retention
  • ✅ Design a memory strategy for a project: what goes in user, what in project, what in local
  • ✅ Implement memory curation: keep MEMORY.md relevant, clean, and within the 200-line limit

Professional objective

In your next project, every subagent you create will have memory configured. Your reviewer will remember the codebase patterns. Your implementer will remember the team conventions. When a new member joins the team and clones the repo, the subagents with project scope will bring the institutional knowledge — the architecture, the decisions, the conventions — without anyone having to explain anything.


Module Roadmap

Capsule map

#CapsuleWhat you'll learnType
01Introduction (this one)The problem of ephemeral memory, the three scopes, MEMORY.mdIntro
02Memory Scopes in DepthConfiguring user/project/local, the memory field in frontmatter, curation instructions in system promptsTechnical
03Sharing Memory Across SubagentsStrategies for multiple subagents to access shared context, read-only vs read-write, conventionsTechnical
04Memory ManagementCurating MEMORY.md, rotating stale content, prioritizing relevant context, the 200-line limitTechnical
05Project: Memory HierarchyConfiguring a complete memory hierarchy for a project with 3 subagents and verifying persistenceProject

Learning flow

First you'll understand how to enable memory in a subagent and how the three scopes differ (capsule 02). Then you'll see how multiple subagents can share context — because a reviewer and an implementer that don't share knowledge produce inconsistent results (capsule 03). Next you'll learn how to keep memory useful — because infinite memory confuses more than it helps (capsule 04). Finally, you'll build a complete hierarchy for a real project and verify that everything persists (capsule 05).

The progression is: enable memory → share across agents → keep relevant → build complete system.

Estimated module duration: 1-1.25 hours.


Connection to the Project

This module's mini-project: Memory Hierarchy

In capsule 05 you'll configure a memory hierarchy for the 3 subagents from Module 1:

  • Reviewer with project scope — remembers codebase patterns and shares them with the team via git
  • Implementer with project scope — remembers code conventions and architectural decisions
  • Tester with local scope — remembers previous test results and coverage trends (private, not shared)

You'll verify persistence by running each subagent, closing the session, reopening, and confirming they remember what they learned.

Connection to the final project (Module 8)

The memory configured here is critical for the capstone project. A 5-agent system without shared memory is chaotic — the backend agent doesn't know what the frontend agent decided, the tester doesn't know what changed. Memory scopes are the "shared brain" of the multi-agent system.


Prerequisites

Required knowledge

  • ✅ Module 1 completed — You know how to create custom subagents with YAML frontmatter and system prompts
  • ✅ Basic Git — You understand commits, .gitignore, and why something is or isn't committed
  • ✅ Functional CLAUDE.md — You have a project with active Claude Code configuration

Quick check

If you can answer "yes" to these questions, you're ready:

  1. Do you have at least one custom subagent created in .claude/agents/?
  2. Do you know which fields go in a subagent's YAML frontmatter?
  3. Do you understand the difference between files that are committed to git and files that are gitignored?
  4. Have you experienced the frustration of an agent "forgetting" context from previous sessions?

You don't need

  • ❌ Experience with databases or storage systems — memory is just simple Markdown files
  • ❌ Knowledge of Agent Teams — that's module 4
  • ❌ Automation scripts — everything is configured in the subagent's frontmatter
  • ❌ Experience with caching or persistent state — the concept is simpler than it seems

Module Setup

What you need to have ready

1. Module 1 subagents working:

You should have at least one custom subagent in your project. If you completed Module 1, you have three (reviewer, implementer, tester) in .claude/agents/. Verify:

ls .claude/agents/

If you see your .md files, you're ready. If not, create at least a basic one:

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Grep, Glob, Bash
model: haiku
---

You are a code reviewer. Analyze code changes and provide actionable feedback.

2. Project with git history:

Memory with project scope is committed to git. You need a project with at least 3 commits so the reviewer has something to analyze.

git log --oneline -5

3. Verify the memory directories exist (or can be created):

# These are created automatically when you enable memory,
# but you can verify that you have permissions
mkdir -p .claude/agent-memory
mkdir -p .claude/agent-memory-local
ls ~/.claude/agent-memory/ 2>/dev/null || echo "Will be created automatically"

4. A text editor to inspect MEMORY.md:

During the module you'll verify the content of MEMORY.md manually. Any editor works, but having one handy lets you see the memory your agent accumulates in real time.


Key Concepts We'll Use

Before diving into the technical capsules, make sure these concepts are clear:

  • Memory scope: The reach of a subagent's memory. It defines where it's stored and who can access it. The three scopes are user, project, and local.
  • MEMORY.md: The Markdown file where the subagent stores its accumulated knowledge. It's read automatically at the start of each session (first 200 lines).
  • Persistence: The subagent's ability to retain information across sessions. Without memory, each session starts from scratch.
  • Curation: The process of keeping MEMORY.md relevant — removing stale information, prioritizing what matters, respecting the 200-line limit.
  • Shared memory: When multiple subagents can access the same knowledge, whether by reading the same memory or complementing separate memories.

The relationship between CLAUDE.md and Agent Memory

It's natural to wonder: "Isn't CLAUDE.md enough to provide context?" CLAUDE.md is static — you write it and update it manually. Agent memory is dynamic — the agent builds it while working. They're complementary:

CLAUDE.md = What YOU tell the agent about the project (static)
MEMORY.md = What the AGENT learns about the project (dynamic)

CLAUDE.md: "This project uses FastAPI with PostgreSQL. Follow PEP 8."
MEMORY.md: "src/api/routes.py has 3 functions without type hints.
           The team prefers snake_case. The process_order function
           in src/services/ is the most complex in the codebase."

CLAUDE.md defines the rules. MEMORY.md records what's learned within those rules.


Limits: What Is NOT Covered in This Module

  • ❌ Parallel delegation — Covered in Module 3. Here subagents work in sequence
  • ❌ Agent Teams and task boards — Covered in Module 4. Here coordination is manual
  • ❌ Memory in Agent Teams — An advanced concept touched on when you reach Agent Teams
  • ❌ Databases or external storage — Claude Code's memory uses Markdown files, not DBs
  • ❌ Headless SDK with memory — Covered in Module 6

Evidence of Success

By the end of this module, you'll know you succeeded if:

  • ✅ You can explain the difference between user, project, and local memory scopes in one sentence each
  • ✅ Your reviewer subagent remembers codebase patterns across sessions
  • ✅ When closing and reopening Claude Code, you verify that MEMORY.md contains the accumulated context
  • ✅ You can decide which scope to use for each type of information (credentials → local, conventions → project, preferences → user)
  • ✅ Your MEMORY.md is curated — relevant, within the limit, and free of stale information
  • ✅ A colleague who clones your repo gets the project knowledge via the project memory scope

Quick self-assessment test

If you can answer these questions by the end of the module, you're on the right track:

  1. Where is the memory of a subagent with project scope stored?
  2. How many lines of MEMORY.md are automatically injected into the system prompt?
  3. Why would you use local instead of project for a tester?
  4. What happens if MEMORY.md exceeds 200 lines?
  5. How do you verify that memory persists across sessions?

Note on Compatibility

Agent memory functionality requires Claude Code version 2.1.63 or later. The memory field in the YAML frontmatter is stable functionality (GA). If you're using an earlier version, update before starting this module:

claude --version

# If you need to update
npm update -g @anthropic-ai/claude-code

Last functionality check: March 2026


Summary

  • The subagents from Module 1 are capable but amnesiac — each session starts from scratch
  • Memory scopes solve this with three levels: user (global), project (shareable via git), local (private)
  • The mechanism is MEMORY.md — a file the subagent reads at startup and updates during execution
  • The first 200 lines of MEMORY.md are automatically injected into the system prompt
  • Memory curation is a skill: keeping context relevant, clean, and within the limit
  • The memory configured here is a prerequisite for parallel delegation (Module 3) and Agent Teams (Module 4)

Additional Resources

  1. Subagents — Persistent Memory (Anthropic Docs) — Official documentation of the memory field in subagents
  2. Create Custom Subagents — Complete frontmatter reference including memory
  3. CLAUDE.md Best Practices — Best practices that complement agent memory
  4. Claude Code Overview — General context of persistence in Claude Code
  5. Skills Documentation — Skills that can be combined with memory
  6. Hooks Reference — Hooks that can interact with the memory lifecycle

Next capsule: In capsule 02 you'll configure real memory in your subagents. You'll see how a single field in the frontmatter (memory: project) transforms an amnesiac agent into one that accumulates knowledge — and you'll verify the persistence with your own eyes.