Back to Patterns

State Handoff and Memory

Prompt Patterns

Summary

State handoff and memory is a pattern for managing agent state across turns and sessions. Instead of keeping all state in the prompt (which wastes tokens and leaks context), state is persisted externally and only the relevant portion is rehydrated each turn.

How it works

  1. Store state externally -- task progress, intermediate results, and conversation history live in a database or key-value store.
  2. Rehydrate relevant context each turn -- on each invocation, load only the subset of state needed for the current query.
  3. Compact periodically -- summarize or prune old state to prevent unbounded growth.

State types

  • Working memory: Current task state, intermediate variables, in-progress results. Cleared when the task completes.
  • Session memory: Conversation history and preferences for the current session. Cleared when the session ends.
  • Long-term memory: User preferences, learned patterns, persistent facts. Retained across sessions.

Best practices

  • Event sourcing: Record every state mutation as an event for audit and replay capability.
  • Compaction: Periodically merge or summarize old events to keep storage bounded.
  • Conflict resolution: When multiple agents modify the same state, use last-writer-wins or merge strategies.

Build This Pattern

Copy this prompt and paste it into Claude Code, OpenCode, Codex, or Cursor to implement this pattern.

Build me a state handoff and memory system. Architecture: maintain task state in an external store (PostgreSQL, Redis). On each turn, rehydrate only the relevant context: current goal, progress summary, key decisions, pending actions. Error handling: handle state corruption, concurrent access conflicts. Edge cases: handle session expiry, state too large to rehydrate, conflicting updates. Best practices: use event sourcing for audit trail, compact state periodically. Testing: verify correct state rehydration across multiple turns.