Skip to content

Chapter 7 · Multi-turn Sessions and Context Management ​

Chapter goals: Master Claude Code's session persistence mechanism, understand context window limits and compaction strategy, learn to use --continue/--resume to restore history, and formulate context management strategies for long tasks.

7.1 Session Lifecycle ​

Every interaction in Claude Code is a session. Understanding its lifecycle is prerequisite for efficient use:

text
New session starts
   │
   ├── Load CLAUDE.md → inject project context
   ├── Load settings.json → apply permission rules
   ├── Scan directory structure → build code map
   │
   ▼
User input ──→ Claude thinks ──→ Tool calls ──→ Result feedback
   │                                          │
   │         (loop until task completes)       │
   │                                          │
   ▼                                          ▼
User continues conversation          Session ends (auto-saved)

Each session is automatically saved to the local ~/.claude/projects/ directory and can be restored even if the terminal closes.

7.2 --continue and --resume ​

bash
# Method 1: --continue to resume the most recent session
claude --continue

# Shorthand -c
claude -c

# Append a new instruction to the resumed session
claude --continue "Was that bug fixed?"

# Method 2: --resume to select a specific historical session
claude --resume

# Restore a specific session ID directly
claude --resume <session-id>
FlagBehavior
-c / --continueOpens the most recent session when no argument is given
-c "instruction"Opens the most recent session and immediately executes the new instruction
-r / --resumeShows a session list for selection
-r <id>Restores the session with the specified ID

Use Cases

  • Cross-day work: half-done yesterday, claude -c to continue today;
  • Multi-task switching: switch between sessions for different projects with --resume;
  • Code review tracing: find previous discussion records with --resume.

7.3 Context Window and Compaction ​

Claude's context window is finite (about 200K tokens). During long conversations, when approaching the limit, compaction is triggered:

text
Context usage
│
│ ████████████████████████░░░░░░░░░░ 75% ← Normal working区
│
│ ██████████████████████████████░░░░ 90% ← Compaction begins
│    ↑
│    Claude automatically summarizes early messages,
│    preserving key decisions and current state,
│    freeing space for subsequent operations.

Compaction behavior:

  1. Compresses early messages into a structured summary;
  2. Preserves the original text of recent messages;
  3. Maintains a "current task state" snapshot.

Manual Trigger Compaction ​

bash
# In interactive mode
> /compact

# With custom summary focus
> /compact Focus on: database schema changes, API interface design decisions, unfinished TODO list

7.4 Strategies for Long Conversations ​

For complex tasks spanning multiple days, compaction alone is insufficient. The following strategies are recommended:

Strategy 1: Externize Progress to Files ​

Have Claude write key information to disk files instead of relying on conversation memory:

markdown
<!-- PROGRESS.md -->
# Task Progress

## Done
- [x] Database schema design (see docs/schema.md)
- [x] User auth module (commit abc123)

## In Progress
- [ ] Orders API: CRUD done, pending payment callback

## Decision Log
- ORM choice: SQLAlchemy 2.0 (team vote)
- No Redis cache introduced (current traffic doesn't need it)

Convent in CLAUDE.md:

markdown
## Workflow Convention
Read PROGRESS.md at the start of each session to understand current state.
Update PROGRESS.md before the end of each session.
Write important architecture decisions to DECISIONS.md with rationale.

Strategy 2: Task Decomposition and Session Isolation ​

bash
# Don't do everything in one session
# ❌ claude "Refactor the entire project"

# ✅ Split into independent sessions
claude -p "Analyze test coverage of the auth module"
claude -p "Write unit tests for utils/date.py"
claude -p "Fix the memory leak mentioned in issue #42"

One small task per session; avoid performance degradation from context bloat in a single ultra-long conversation.

Strategy 3: Use Git as a State Anchor ​

bash
# Have Claude commit at key checkpoints
> Please commit current progress; message: "WIP: user auth module 80% done"

Git commits are the most reliable "checkpoint" — even if the session is lost, the code state is not.

7.5 Diagnosing Context Issues ​

bash
# Check current context usage
> /cost

# Output example:
# Total cost: $0.45
# Context used: 45,230 / 200,000 tokens (22.6%)

Common problems and remedies:

SymptomCauseSolution
Replies slow downContext too large/compact or open a new session
Forgets previous decisionsCompaction lost detailsExternize with progress files
Re-does already-done workNew session has no memoryCLAUDE.md + PROGRESS.md
Cost spikesLong conversation accumulates tokensPeriodically open new sessions

Chapter Summary ​

  • claude -c quickly resumes the last conversation; --resume selects from a list;
  • Compaction auto-compresses early conversations, preserving recent content and task snapshots;
  • Complex tasks use PROGRESS.md + DECISIONS.md to externize key information;
  • Small tasks split into independent sessions are more efficient than one ultra-long conversation;
  • Git commits are the most reliable progress anchor.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the difference between claude -c and claude --resume?

2. What is compaction?

3. Why is it recommended to externize task state via PROGRESS.md rather than relying on conversation memory?

4. Which approach best reduces context cost for long tasks?

🛠️ Hands-on Practice ​

  1. Use claude -c to resume yesterday's conversation and have it summarize what was done.
  2. Create a PROGRESS.md file,约定 read/write rules in CLAUDE.md, and observe cross-session效果.
  3. Complete the same task using both a single long session and three short sessions; compare the费用 difference in /cost output.

After completing the exercises, proceed to Chapter 8: Git Integration and Code Review.