← Back to list

Context and Memory Management in Claude Code

Claude Code has no memory by default. Here is how to give it one — and how to stop running out of it mid-task.

Amit Naik in ExpertMinds · 2026-05-27 17:36 · 0 claps · 9.7 min read
#claude #claude-code #anthropic-claude #claude-ai #anthropic-claude-code
Open on Medium ↗
Wiki topics: LLM · Large Language Models BIZ · Business Strategy 🏃 · Running & Endurance

Context and Memory Management in Claude Code

Claude Code has no memory by default. Here is how to give it one — and how to stop running out of it mid-task.

Here is something most developers discover the hard way.

You are halfway through a complex feature. Claude Code has been doing well — it knows your stack, it is following your conventions, the code it is producing fits your codebase. Then the conversation gets long. You ask Claude to make another change, and it starts doing something slightly wrong. It forgets a constraint you mentioned earlier. It suggests a dependency you already told it not to use. It contradicts a decision you made three sessions ago.

This is what context window exhaustion looks like in practice. And it is not just about length — it is about what is in that limited space, how long it stays there, and whether the things Claude needs to know are actually available when it needs them.

This article covers the four tools that solve this problem: the context window itself, CLAUDE.md, Skills, and SubAgents. Together, they form a complete memory architecture for serious AI-assisted development.

Part 1: The Context Window

What it is

Every Claude Code session has a context window — a finite amount of space that holds everything Claude can “see” at once: your conversation history, the files you have added, Claude’s previous outputs, system instructions, everything.

Think of it as working memory. A brilliant colleague who can only remember the last N pages of notes. Once something scrolls off the edge, it is gone from Claude’s awareness — even if it matters.

The context window in Claude Code is large by modern standards, but it is not infinite. And because it holds code (which is verbose), outputs (which can be long), and files (which you keep adding), it fills up faster than you expect.

What happens when it fills up

When the context window gets full, Claude Code does not crash or stop. Something subtler happens: it starts losing track of earlier parts of the conversation. Decisions made at the start of the session become invisible. Constraints you set get quietly forgotten. The code starts to drift.

This is the root cause of most of the frustrating, inconsistent behavior people blame on “the AI being wrong.” It is usually not the model failing — it is context saturation.

Managing it deliberately

Claude Code gives you three tools for managing the context window:

**/status** — Shows how much of the context window is currently in use. Run this periodically during long sessions. When it starts getting high, act before it hits the limit.

**/compact** — Compresses the conversation history into a summary. The full transcript is gone, but a condensed version of what happened stays in context. Use this when you are continuing the same work but need to free up space.

**/clear** — Wipes the context entirely. Use this when you are switching to a different task or starting something new. Cleaner than you might think — because the things Claude actually needs between sessions live in CLAUDE.md and Skills, not in the chat history.

The key mindset shift: treat the context window like RAM. Only load what is relevant to the current task. Add files deliberately, not indiscriminately. And clean up regularly.

Part 2: CLAUDE.md — The Persistent Brain

What it is

CLAUDE.md is a special Markdown file that Claude Code reads automatically at the start of every session. It is your project's persistent memory — the things Claude should always know, regardless of what is in the current conversation.

It lives in your project root:

your-project/
├── CLAUDE.md        ← Claude reads this first
├── src/
├── package.json
└── ...

Why it matters

Without CLAUDE.md, every session starts cold. You explain your stack, your conventions, your constraints — again. The AI has no idea what decisions were made last week, what patterns your team follows, or what is off-limits.

With CLAUDE.md, every session starts informed. Claude knows the codebase before you type a single word.

What to put in it

A well-written CLAUDE.md covers five things:

1. Project overview — What is this? What does it do? One paragraph is enough.

## Project overview
A B2B SaaS platform for construction project management.
Backend is Node.js + PostgreSQL. Frontend is Next.js 14.
Multi-tenant — every query must be scoped to a tenant_id.

2. Tech stack — The exact libraries, versions, and tools in use.

## Tech stack
- Runtime: Node.js 20, TypeScript 5.3
- Database: PostgreSQL 16, Drizzle ORM (not Prisma)
- Auth: Clerk (not NextAuth — this was migrated in Jan 2024)
- Testing: Vitest + Testing Library
- Styling: Tailwind CSS 3.4

3. Coding conventions — The patterns your team follows. This is where most of the value lives.

markdown

## Conventions
- All API routes use Zod for input validation — never trust raw req.body
- Database queries go through /lib/db, never inline SQL
- Error handling: throw typed errors from /lib/errors/index.ts
- All React components are functional — no class components
- Use async/await throughout, never .then() chains

4. Architecture decisions — The “why” behind important choices, so Claude does not suggest alternatives.

## Architecture decisions
- We use tRPC, not REST — all new endpoints go in /server/routers
- Redis is used for session storage and rate limiting only, not as a cache
- File uploads go to S3 via presigned URLs — never through our API server

5. Do-not-do list — Explicit constraints that Claude should never violate.

## Do not
- Install new npm packages without asking first
- Modify files in /migrations — these are write-once
- Use process.env directly — always go through /lib/config
- Add any external API calls without rate limiting

Keeping it current

CLAUDE.md is a living document. Treat it like that. When your team makes a significant architectural decision, add it. When a library gets replaced, update the stack section. When a new "do not" emerges from a painful lesson, write it down.

A stale CLAUDE.md is worse than none — it gives Claude incorrect information confidently. Set a reminder to review it monthly, or just make updating it part of your "done" criteria whenever a significant change lands.

Project vs sub-directory CLAUDE.md

You can have multiple CLAUDE.md files — one in the root, and additional ones in subdirectories. Claude reads all of them, with the more specific ones taking precedence. This is useful for large monorepos where the frontend and backend have different conventions:

my-monorepo/
├── CLAUDE.md           ← global conventions
├── packages/
│   ├── api/
│   │   └── CLAUDE.md   ← backend-specific rules
│   └── web/
│       └── CLAUDE.md   ← frontend-specific rules

Part 3: Skills — Reusable Encoded Knowledge

What they are

Skills are reusable knowledge packages that you build once and reference across multiple projects or sessions. Where CLAUDE.md is project-specific context, Skills are portable expertise.

A Skill is a directory containing a SKILL.md file — a structured document that teaches Claude how to do a specific thing in your environment. Claude reads it when you reference the skill, and it stays in context for the duration of that task.

What Skills are good for

Skills shine when you have recurring tasks that require specific, non-obvious knowledge. Common examples:

  • Deployment procedures — The exact sequence of steps to deploy your application, including the flags, the order, the health checks, the rollback procedure.
  • Testing patterns — How your team writes tests, what utilities are available, what patterns are required, what to avoid.
  • Database migration workflows — The right way to create and apply migrations in your codebase.
  • Code review standards — What your team looks for in a code review, what will always get flagged.
  • API integration patterns — How to authenticate with and call your internal services.

What a Skill looks like

# SKILL: Database Migrations

## When to use this skill
Whenever creating or modifying database migrations.

## Our migration tool
We use Drizzle Kit. Never write raw SQL migrations by hand.

## Creating a migration
1. Make changes to the schema file in /db/schema.ts
2. Run: npm run db:generate - this creates the migration file
3. Review the generated file in /db/migrations before applying
4. Run: npm run db:migrate - applies pending migrations

## Critical rules
- Never edit a migration file after it has been committed
- Always generate migrations from schema changes, never write them manually
- Test migrations on a local database before committing
- Migration files are named by timestamp - do not rename them

## Common mistakes
- Running db:migrate before db:generate (no-op, confusing)
- Editing schema without generating a migration (schema and DB diverge)

How to reference a Skill

In Claude Code, you add a Skill to your context with the @ syntax:

@skills/database-migrations.md 
I need to add a new `subscription_tier` column to the users table. 
Walk me through creating the migration.

Claude reads the Skill, understands your migration workflow, and guides you correctly — without you having to re-explain it every time.

Building your Skill library

Think of Skills as your team’s institutional knowledge, codified. Every time someone has to explain a process more than twice, that process is a candidate for a Skill. Every onboarding document that lives in Notion and never gets updated is a candidate for a Skill.

Start small — one or two Skills for your most repeated workflows — and add to the library over time. The ROI compounds as the library grows.

Part 4: SubAgents — Solving the Scale Problem

The problem SubAgents solve

Even with a well-managed context window, CLAUDE.md, and Skills, some tasks are simply too large for a single session. A full feature spanning multiple files, a refactor across a large codebase, a task that requires researching and then building — these tasks push against the context window before the work is done.

The naive solution is to just keep prompting, reprompting, and hoping Claude holds the thread. It does not. Context gets saturated, decisions get forgotten, and the code drifts.

SubAgents are the structural solution. Instead of one Claude session trying to hold everything in a single context window, SubAgents break the work into focused, independent tasks — each running in its own context, each fully focused on one piece of the problem.

How SubAgents work

When you invoke a SubAgent in Claude Code, you are spinning up a separate Claude instance for a specific, bounded task. That instance has its own fresh context window. It does its work. It returns a result. The orchestrating session (the main Claude Code context) receives that result and continues.

The mental model: you are a senior developer. SubAgents are junior developers you can delegate to. You do not give each junior developer the entire project context — you give them a clear, scoped task and the specific files they need. They return their work. You review it and integrate it.

What SubAgents are good for

Research tasks. Gather information about a library, an API, or an approach — without cluttering the main implementation context with all that exploratory noise.

Parallel work. Multiple SubAgents can work simultaneously on independent parts of the same feature — one handles the backend endpoint, another handles the frontend component, a third writes the tests.

Large file analysis. When you need Claude to read and understand a very large file, doing it in a SubAgent preserves the main context for actual implementation work.

Isolated refactors. Refactoring a module is a contained task. Put it in a SubAgent, get a clean result, integrate it.

A concrete example

Suppose you are building a new user notification system. The work involves:

  • A database schema change for notification records
  • A backend service to create and queue notifications
  • An API endpoint to fetch a user’s notifications
  • A frontend component to display them
  • Tests for all of the above

In a single session, by the time you finish the backend, the context is crowded with schema discussions, migration outputs, and implementation notes — and there is barely room to think about the frontend without losing the thread.

With SubAgents:

Main session: Plan the notification system architecture.

SubAgent 1: Create the database schema and migration.
SubAgent 2: Build the backend notification service.
SubAgent 3: Build the API endpoint.
SubAgent 4: Build the frontend notification component.
SubAgent 5: Write tests for the service and API.
Main session: Review all outputs, integrate, resolve conflicts.

Each SubAgent works with a clean, focused context. The main session acts as the integrator, not the implementer. The total work is the same — but nothing gets lost, nothing gets confused, and every piece is fully focused.

SubAgents and token cost

SubAgents also help with cost. When a single context window fills up and Claude starts re-reading the entire history on every response, token usage spikes. SubAgents avoid this: each one starts fresh, does focused work, and exits. The token cost per task stays proportional to the task size, not to the total session length.

How the Four Layers Work Together

These four tools are not independent — they form a layered architecture where each one compensates for the limits of the others.

The context window is your working memory: fast, powerful, but finite and temporary. CLAUDE.md is your project's long-term memory: persistent, always available, survives every session reset. Skills are your institutional knowledge library: portable expertise you encode once and reuse forever. SubAgents are your delegation mechanism: the way you scale past what any single context window can hold.

A mature Claude Code workflow uses all four:

  • CLAUDE.md loaded automatically, keeping every session informed from the start
  • Skills referenced explicitly when a recurring workflow is involved
  • Context window managed deliberately — files added with intention, /compact used before it gets critical
  • SubAgents invoked for any task that is too large, too parallel, or too exploratory for one session

Together they give you something that vibe coding never delivers: a working relationship with an AI that actually knows your project, follows your conventions, stays within your constraints, and scales to the complexity of real work.

What’s Next

The next article in this series goes into the tools that extend Claude Code beyond the core workflow: MCP, Hooks, and Plugins — how to connect Claude Code to external services, automate behavior around Claude’s actions, and build a customized environment that fits your specific development needs.

This is article 3 in a series on mastering Claude Code. Article 1 covers why structured AI coding beats vibe coding. Article 2 covers setup, slash commands, making changes, and image context. Article 4 covers extending Claude Code with MCP, Hooks, and Plugins.


메타데이터
post_id
d59bb696473f
slug
context-and-memory-management-in-claude-code-d59bb696473f
url
https://medium.com/expertminds/context-and-memory-management-in-claude-code-d59bb696473f
canonical_url
https://medium.com/expertminds/context-and-memory-management-in-claude-code-d59bb696473f
author_url
https://medium.com/@amit-naik
status
ok
fetched_at
2026-06-11 05:11:55