Sleep-Time Compute for Agent Memory: A Practical Guide to Layered Memory Architecture
Long-horizon agent tasks generate massive interaction histories that overflow context windows and inflate costs. This article introduces a brain-inspired "sleep-time compute" approach: lightweight logging during interaction and offline memory consolidation during idle periods. It details a four-layer memory architecture (raw events, structured episodes, semantic knowledge, task working context), the offline "dreaming" consolidation pipeline, and practical engineering recommendations for implementation.
1. Why Agents Need to “Sleep”
Long-horizon agent tasks—such as multi-turn game exploration, repository-level code refactoring, or multi-day operations—generate large volumes of interaction records. Mainstream architectures typically handle memory in one of two ways, both with significant drawbacks:
- Stuffing everything into the context window: The full conversation history grows linearly with each task turn, increasing inference latency and per-call token costs. Once the window limit is exceeded, truncation becomes unavoidable, and critical early information is lost entirely.
- Coarse summarization or vector retrieval: Compressing history into long-text summaries, or recalling content via RAG. The former discards precise details (such as a specific configuration value or path identifier); the latter returns fragments lacking logical chains, leaving the agent able to “know the pieces but fail to assemble the whole picture.”
The human brain offers an inspiration: the vast experiences rapidly recorded during the day are “replayed,” compressed, and reorganized in batches by the hippocampus and cortex during sleep, filtering out noise and consolidating key memories. A frontier research team has transferred this idea into agent systems, forming a two-phase memory mechanism of “real-time recording + offline organization”—only lightweight writes happen during interaction, while the organization process starts during idle periods. The industry commonly refers to this kind of idle-period computation as sleep-time compute.
2. The Four-Layer Memory Architecture
This architecture divides agent memory into four layers, each with clear responsibilities and increasing levels of abstraction:
1. Raw Event Layer
Raw interaction fragments—user instructions, tool calls and their returns, environment state snapshots—are appended in chronological order. Write costs are extremely low, similar to a logging service, with the sole guarantee of durability. This layer serves as the traceable source of truth for all upper-layer memory.
2. Structured Episode Layer
During idle periods, offline tasks scan raw events and extract them into structured episode units: “under what conditions, what action was taken, what result was obtained, and what experience can be generalized.” Compared to raw fragments, the episode layer removes noise such as small talk, retries, and error traces, while preserving causal chains.
3. Semantic Knowledge Layer
Patterns that recur across the episode layer are generalized a second time into reusable knowledge entries, such as “all water obstacles in this map region can be crossed with a specific skill.” This layer answers “what rules have I learned” and is the source of cross-task transfer capability.
4. Task Working Layer
The short-term context of the currently active task, retaining only memory relevant to the subgoal in progress—including recent episodes and references to related knowledge entries. Only this layer is loaded at inference time, fundamentally controlling context length.
3. How the “Dreaming” Process Works
“Dreaming” is the umbrella term for idle-time organization, centered on an offline consolidation pipeline:
def dreaming(memory):episodes = extract_episodes(memory.raw_events) # events -> episodesinsights = consolidate(memory.episodes, episodes) # episodes -> knowledgeprune(memory) # demote or evict low-value, superseded memoriesindex(memory) # rebuild retrieval indexes and knowledge graph linksreturn memory
Trigger points include: the user going offline, gaps between interaction turns, and task completion. The consolidation process can run in offline batches using higher-throughput, lower-cost invocation methods, reserving the expensive online inference window for turns that genuinely require real-time decisions.
Key design points:
- Consolidation, not overwrite: When new knowledge conflicts with old knowledge, the evidence chain is preserved and confidence levels are annotated; adjudication is deferred until validated by subsequent tasks, preventing a single erroneous generalization from contaminating long-term memory.
- Detail anchors: The episode layer retains precise information such as key values, IDs, and paths, which are backfilled into the working layer on demand during retrieval—addressing the “lost details” flaw of summarization approaches.
- Memory lifecycle: Each memory carries a timestamp, reference count, and confidence score. Memories that remain unreferenced for long periods with low confidence are demoted to archive, preventing unbounded memory store growth.
4. Engineering Implementation Recommendations
- Decouple writes from consolidation: Raw event writes go through an asynchronous message queue, while consolidation tasks are triggered by scheduled jobs, avoiding blockage of the online path.
- Hybrid retrieval strategy: Working-layer recall uses a dual-channel approach of “knowledge entries + associated episodes”—retrieve the rule first, then the supporting evidence—to keep logical chains intact.
- Observability: Use logging services with monitoring and alerting to track memory hit rates and context length changes as the basis for tuning. For example, overly coarse episode extraction granularity leads to detail loss, while overly fine granularity raises consolidation costs.
- Storage selection: Raw events suit object storage or cold storage in log services; the episode and knowledge layers suit a combination of structured storage plus vector indexes, balancing exact matching with semantic recall.
5. Conclusion
The essence of the “dreaming” mechanism is shifting memory organization from an expensive online process to a cheap offline one: record during interaction, digest during idle time. Combined with the idle-time consolidation pipeline, the four-layer memory architecture preserves precise details and transferable experiential knowledge while controlling context length and invocation costs—providing a practical engineering path for memory management in long-horizon agent tasks.
