Listen to today's AI briefing

Daily podcast — 5 min, AI-narrated summary of top stories

Stop Losing Agent Context: Implement Session Memory Files in Your Claude
AI ResearchScore: 94

Stop Losing Agent Context: Implement Session Memory Files in Your Claude

A simple pattern using structured markdown files to persist session state across context windows, preventing Claude Code agents from redoing work or making inconsistent decisions.

Share:
Source: dev.tovia devto_claudecodeSingle Source

The Technique — Session Memory Files

Adding memory to your agentic applications using AgentCore Memory | by ...

Your Claude Code agent just spent 45 minutes understanding your codebase, making decisions, and tracking progress. Then the context window compacts. All that accumulated knowledge disappears. The next session starts fresh, potentially redoing work or making contradictory decisions.

This is solved with session memory files — structured, append-only markdown files that persist across sessions. Unlike CLAUDE.md (for stable instructions) or outputs/ (for final results), session memory files capture ephemeral session state.

Why It Works — Separating Context from Memory

Claude Code agents have two distinct resources:

  • Context: What's in the current session window. Fast, powerful, but disappears on compaction.
  • Memory: What's written to disk. Persists across sessions but requires explicit structure.

Session memory files bridge this gap by converting valuable context into persistent memory at regular checkpoints. This follows Anthropic's design philosophy for CLAUDE.md — providing persistent context — but applies it to runtime state rather than project configuration.

How To Apply It — Step-by-Step Implementation

1. Create Your Session Memory File Structure

Create a markdown file with these sections:

# Session Memory — [task_name]

## Decisions Made
- [timestamp] — [decision with reasoning]

## Progress Markers
- COMPLETED: [what's been done]
- IN_PROGRESS: [where you stopped]
- PENDING: [what's left]

## Key Discoveries

![How To Implement Spring Security Session Authenticat…](https://miro.medium.com/v2/resize:fit:500/1*oeULlIXKDhZr0YVWd-JX-g.png)

- [timestamp] — [important fact about the codebase]

## Next Session Start
[Exactly what to do when resuming]

2. Add Checkpoint Functions to Your Workflow

Add this shell function to your task scripts or CLAUDE.md:

checkpoint() {
    local NOTE="$1"
    local SESSION_MEM="working/${TASK_ID}/session_memory.md"
    echo "- $(date -u +%Y-%m-%dT%H:%MZ) — $NOTE" >> "$SESSION_MEM"
}

3. Integrate with Claude Code Sessions

At session start, add this to your prompt:

SESSION_PROMPT=""
if [[ -f "working/${TASK_ID}/session_memory.md" ]]; then
    SESSION_PROMPT="Read working/${TASK_ID}/session_memory.md first. Apply all decisions and progress markers before starting new work."
fi

# Then in your Claude Code command:
claude code "$SESSION_PROMPT Continue with the task: [your task description]"

4. Call Checkpoints at Natural Breakpoints

Instruct your agent to call the checkpoint function when:

  • Making a decision that constrains future work
  • Completing a logical unit (e.g., processing 10 files)
  • Discovering something that changes how future work proceeds
  • Encountering an edge case that needs remembering

Example in CLAUDE.md:

## Session Memory Protocol

Before context compacts or session ends:
1. Write current progress to working/{task_id}/session_memory.md
2. Record any decisions made in the last 30 minutes
3. Update "Next Session Start" section with exact next action
4. Write completion status of current logical unit

On session start:
1. Read working/{task_id}/session_memory.md if it exists
2. Apply all decisions without re-evaluating them
3. Start from the progress marker labeled "Next Session Start"
4. Do not re-do work marked as COMPLETED

5. Handle Multi-Session Tasks

For tasks spanning multiple sessions, the session memory file becomes your audit trail. When the task completes, you have a complete record of:

  • Every decision made and why
  • The exact progression of work
  • All discoveries about the codebase
  • When each checkpoint occurred

This is invaluable for debugging agent behavior and understanding how complex tasks unfolded over time.

Real-World Example: Codebase Migration

Imagine migrating 500 files from one framework to another. Without session memory:

  • Session 1: Processes files 1-150, discovers framework-specific edge cases
  • Session 2: Starts fresh, rediscovers edge cases, potentially processes files 1-150 again
  • Result: Duplicate work, inconsistent decisions, wasted time

With session memory:

  • Session 1: Processes files 1-150, writes decisions and discoveries to session_memory.md
  • Session 2: Reads session_memory.md, starts at file 151, applies previous decisions
  • Result: Continuous progress, consistent decisions, no wasted work

Advanced Tips

Version Your Memory Files

For long-running tasks, create dated versions:

SESSION_MEM="working/${TASK_ID}/session_memory_$(date +%Y%m%d).md"

Add Compaction Awareness

Monitor context usage and trigger checkpoints before compaction:

# In your agent's operating instructions
When context approaches 80% full:
1. Write all pending decisions to session_memory.md
2. Update progress markers
3. Write clear "Next Session Start" instructions

Use Structured Formats for Parsing

If you need programmatic access to session state, consider JSON:

{
  "decisions": [
    {"timestamp": "2024-06-15T10:30Z", "decision": "Don't modify auth.yaml", "reason": "Used by 3 services"}
  ],
  "progress": {
    "completed": ["files_001-050"],
    "in_progress": "files_051-060",
    "pending": ["files_061-100"]
  }
}

What This Changes

Session memory files transform Claude Code from a single-session tool to a multi-session workflow engine. You can now:

  • Run agents overnight without losing progress
  • Schedule cron jobs that build on previous runs
  • Handle tasks too large for one context window
  • Maintain decision consistency across team members' sessions
  • Create audit trails for complex agent tasks

The pattern is simple but powerful: convert ephemeral context to persistent memory at regular intervals. Start implementing it today for any Claude Code task that might span multiple sessions.

Following this story?

Get a weekly digest with AI predictions, trends, and analysis — free.

AI Analysis

Claude Code users should immediately implement session memory files for any task lasting more than 30 minutes or spanning multiple sessions. Here's what to do differently: 1. **Create a session memory template** in your project's `working/` directory. For every new task, copy this template and name it with your task ID. The template should have the four key sections: Decisions Made, Progress Markers, Key Discoveries, and Next Session Start. 2. **Modify your CLAUDE.md** to include session memory protocols. Add instructions for when to checkpoint (every 15 minutes or at logical breakpoints) and how to resume. This ensures consistency across all team members using the same project. 3. **Change how you start sessions**. Instead of just `claude code "fix the auth bug"`, first check for a session memory file and prepend it to your prompt. This small change prevents hours of redundant work. 4. **For scheduled agents**, make session memory reading the first step in your cron script. This turns disconnected runs into a continuous workflow where each session builds on previous progress. The key insight: Context is temporary, memory is permanent. Start treating your agent's discoveries and decisions as valuable data that needs preservation, not ephemeral chat history.

Mentioned in this article

Enjoyed this article?
Share:

Related Articles

More in AI Research

View all