Session Lifecycle: From Boot to Dream

A Claude Code session moves through distinct phases, each with specific responsibilities and background activities. Understanding the lifecycle explains when and why different systems activate.

Phase 1: Startup

startBackgroundHousekeeping initializes all background tasks: - Session memory, auto-compact, cron scheduler, prevent sleep, away summary - Plugin auto-update (git pull for marketplace plugins) - GrowthBook feature flag refresh (6h external, 20min internal) - Expensive operations (old version cleanup, message file cleanup) deferred 10 minutes

System prompt assembly happens on every turn (not just startup): CLAUDE.md (global + project), rules files, auto-memory index (first 200 lines), MCP tool definitions, skill definitions.

Phase 2: Active Interaction

The core loop (query.ts async generator): 1. User sends message → system prompt assembled 2. API call → streaming response begins 3. Tool calls execute as they stream in (StreamingToolExecutor) 4. Post-processing: diminishing returns check (<500 tokens × 3 turns = halt) 5. handleStopHooks fires: extract memories, session memory, auto-compact, speculation

Cost reality: extractMemories doubles per-turn token consumption (26M vs 13M in measured traces). Every turn has hidden background cost.

Phase 3: Idle / Between Messages

The gap between user messages is the most productive time for background work: - Speculative execution predicts next input, pre-executes in copy-on-write overlay - Memory extraction processes recent messages, writes to memory directory - Session memory summarizes for future compaction - Auto-compact triggers if context approaches limit

All background tasks share the parent's prompt cache prefix (the cache constraint).

Phase 4: Session End / Resume

Ending: Session state checkpointed for potential resumption. Background tasks drain (up to 60s in headless mode).

Resuming: --resume / --continue / /resume loads conversation from checkpoint. Known bug: always breaks prompt cache for the entire history, causing 10-20x cost on the first resumed turn.

Phase 5: Dreaming (Inter-Session)

When auto-dream gates pass (≥24h since last consolidation, ≥5 sessions accumulated, no concurrent dream): 1. Orient — read MEMORY.md, scan topic files 2. Gather Signal — grep session transcripts for corrections, saves, themes, decisions 3. Consolidate — absolute timestamps, delete contradicted facts, merge duplicates 4. Prune & Index — rewrite topic files, rebuild MEMORY.md under 200-line cap

Dream is read-only on project code, write-only to memory files. On failure, rolls back.