Agent Memory Architecture: How Offline "Dreaming" Makes Memory Persistent Across Sessions
This article breaks down a layered agent memory architecture in which online capture stays lightweight while an offline "dreaming" process consolidates raw interaction logs into trustworthy long-term memory. It explains how a biological hippocampus-cortex analogy maps to engineering design, how a four-layer memory structure (episodic log, memory notes, representation, injected context) is organized, and how a five-stage dreaming pipeline—replay, consolidation, verification, revision and forgetting, plus scheduling and budgeting—turns noisy logs into reusable experience. Practical code examples for capture gating and dream cycles are included, along with guidance on injection, conflict resolution, observability, cost control, permissions and data deletion. The intended takeaway: treat memory as a lifecycle-managed engineering object with a minimal three-step starting loop, rather than relying on summary replacement or weight updates to simulate continuity.
1. Why Multi-Turn Conversation Is Not Long-Term Memory
When building task-oriented agents, the most common gap teams encounter is this: the agent performs well within a single session but behaves like a different person across sessions. When a user returns with the same type of request, the agent must re-ask for background and may repeat mistakes that were already corrected the previous time. The reason is not mysterious — the so-called multi-turn capability of most agent frameworks essentially relies only on the context window carried by the current request, and that context is reset to zero when the session ends.
To be precise, agent memory strictly refers to the experience an agent gains during its interactions with users and tasks that persists across sessions and can be re-activated later in the form of plain-text context read back into a prompt. This definition deliberately excludes three things that are often confused with memory:
- Updates to model weights: Memory is not retraining and not parameter-level fine-tuning.
- In-context learning within a single conversation: It is only effective in the current session and disappears once you exit.
- Compressing old conversations into a summary and swapping the whole context with it: Summary replacement solves “it doesn’t fit,” not “it remembers and uses the right thing.”
Once those three are stripped away, the real difficulty of memory becomes clear: how to decide, from massive and noise-dense interaction logs, what is worth keeping, at what granularity to keep it, how to retrieve it accurately in later tasks, and how to revise old conclusions when facts change.
2. Borrowing from Biology: The Hippocampus–Cortex Split and Emotional Tagging
The human brain offers a remarkably instructive answer. Daily experiences are first captured quickly by the hippocampus, forming immediately usable temporary memory; during offline states such as sleep and deep rest, the hippocampus replays recent experiences repeatedly, distills and integrates the important parts into the cerebral cortex, and turns them into long-term knowledge. Two key design ideas can be mapped directly onto engineering:
First, separate online capture from offline consolidation. The online stage pursues low latency and low cost and only does “record as-is”; real understanding, generalization and correction are left to the offline stage. This closely mirrors the classic layering of online transaction systems versus offline data warehouses: don’t expect to perform deep reflection within the few hundred milliseconds a user waits for a reply.
Second, importance tagging determines replay strength. Emotional or chemical signals tag memories at critical moments, and tagged experiences are replayed more times during sleep, so they are remembered more firmly. The engineering counterpart is a salience score: explicit corrections, strong preference expressions from the user, task failures with retries, and rare but reusable solutions should all be assigned higher weight, so they earn more rounds of replay and finer-grained processing.
3. A Layered Memory Architecture: Four Layers with “Dreaming” Running Across Them
A deployable memory system can be organized into four layers, with the dreaming mechanism running horizontally across all of them and improving the expression quality at each layer.
Layer 0: Episodic log (raw records)
Structured retention of every interaction: task goal, sequence of tool calls and their parameters, observed results, failure points, and user feedback. The principle is that it must be traceable, replayable and append-only — never overwritten — because it is the factual baseline for all later processing and auditing.
Layer 1: Memory notes
Short items extracted from the raw records, shaped as a three-part “constraint — action — outcome.” The key design requirement is atomicity: one note covers exactly one thing and carries a stable identifier, a source reference and a timestamp, so it can be located and revoked easily.
Layer 2: Memory representation
Organize notes into structured knowledge: collections grouped by domain or task type, entity and preference profiles, and common failure patterns with their corresponding handling strategies. This layer addresses “retrieval efficiency” and “maintainability” and typically uses a hybrid organization of item lists plus vectorized semantic indexes.
Layer 3: Injected context
Before inference actually starts, assemble once per task in a task-oriented way: pick only the handful of notes relevant to this goal, add necessary sources and confidence levels, and splice them into the system context. Controlling injected volume is a hard constraint — prefer less and more accurate, so attention is not diluted by irrelevant memory.
Raw interaction logs ──► Memory notes ──► Memory representation ──► Injected context▲ ▲ ▲└──── Dreaming: replay / reorganize / verify / revise ────┘
4. Online Writes: Capture Should Be Thin and Precise
The capture stage must avoid heavy work above all. The recommended approach is that after each turn ends, a lightweight extraction step decides “whether there is any signal worth remembering in this turn”; if it hits, it writes exactly one candidate note, with no merging and no edits or deletions. The signal can come from two parts — rules and a model:
def should_capture(turn) -> bool:# Rule layer: low cost, explainable, prioritizes intercepting high-value signalsif turn.explicit_correction: # User explicitly correctsreturn Trueif turn.retry_count >= 1: # A failed retry occurredreturn Trueif turn.user_preference_detected: # Preference expressed (format/tone/prohibited items)return Trueif turn.tool_call_failed: # Tool or data pipeline anomalyreturn Truereturn Falsedef capture(turn, store):if not should_capture(turn):returnstore.append_note(text=turn.distill(), # Atomic: constraint — action — outcomerefs=[turn.id], # Traceable back to the raw recordsalience=turn.salience(), # Salience, which determines later replay countsts=turn.ts,status="candidate" # Unverified, must not be injected directly)
Three engineering details are easy to overlook: first, notes must carry source references, otherwise their truthfulness cannot be verified later; second, salience must be computable and explainable, and rule-based scoring as the primary method with model scoring as a supplement is recommended; third, all newly written items are first set to “candidate” status and never go straight into the injection pool — this is the first gate against memory pollution.
5. Offline Dreaming: Replay, Reorganization and Self-Correction
Dreaming is the core of the value of this architecture and can be split into five independently orchestrable and separately observable stages.
Replay
Weighted sampling of candidate notes by salience, with high-salience items replayed for more rounds. This corresponds to the biological mechanism where “tagged experiences get more replay,” and it directly determines which experiences are ultimately consolidated.
Consolidation
Merge scattered notes under the same topic, abstract them into more general rules, deduplicate and raise their level. For example, multiple notes saying “a certain class of input requires extra field validation” should converge into one general practice plus several instance references.
Verification
Dreaming is not free improvisation. Every memory being reinforced must go back to the raw records to find supporting evidence: those with no evidence are dropped outright, those with insufficient evidence are downgraded to low confidence, and those with contradictory evidence enter a conflict queue. This step is the source of the whole mechanism’s credibility and is also the most fundamental difference from the traditional “summary replacement” — summaries only compress, while dreaming must make judgments.
Revision and forgetting
Facts change, and old conclusions must be overridable. A “new evidence first + versioned retention” strategy is recommended: keep historical versions but exclude them from injection, and mark notes with their applicable scope and effective time to avoid misuse of outdated conclusions.
Orchestration and budget
Dreaming needs idle compute, so it requires an explicit scheduling policy: trigger on idle windows, trigger on memory growth increments, or run scheduled batches; at the same time, set caps per round of replay, total duration and invocation budget, so offline tasks do not crowd out online service capacity. A simple scheduling sketch:
def dream_cycle(store, budget):notes = store.sample_candidates(by="salience", weighted=True, limit=budget.max_replay)for n in notes:evidence = store.fetch_sources(n.refs)verdict = verify(n, evidence) # keep / downgrade / conflict / dropstore.apply_verdict(n, verdict)store.merge_duplicates(by="topic")store.rebuild_index()return store.metrics() # Memory count, confidence distribution, conflict count
6. Injection and Conflict Resolution: Making Memory Actually Change Behavior
Well-written memory does not take effect automatically; the injection stage decides success or failure. Three practices from experience:
Retrieve by task, don’t stuff everything in. Do semantic recall based on the current goal, then layer structured filtering on top (domain, task type, time freshness, confidence threshold) and take a small number of best entries.
Annotate memory with meta-information. Attach source, generation time and confidence to each injected item, so the model knows during reasoning whether “this is an experiential inference” or “this is a verified fact,” which significantly lowers the chance of misuse.
Handle conflicts explicitly. When contradictory memories are retrieved, don’t silently pick one; instead, order them by “new evidence first, higher confidence first, more specific applicable scope first,” and write the conflict into the next processing queue for the dreaming stage.
Introduce closed-loop feedback. If the task fails again this round, or the user corrects again, this should trigger a downgrade of that memory and a re-replay, forming a “use — feedback — revise” cycle instead of a one-time write that stays effective forever.
7. Engineering Considerations and Common Pitfalls
Account for cost by layer. Online capture should be as cheap as possible (rules primary, small models secondary); offline processing can be expensive but must have a budget; injected volume must be controlled, because it consumes both context and attention.
Observability cannot be skipped. At minimum, monitor: candidate note production volume, replay/merge/eviction ratios per round, conflict queue length, memory hit rate, and changes in task success rate and retry rate after injection. Without this set of metrics, it is hard to judge whether the memory system is helping or getting in the way.
Permissions and data boundaries come before features. Memory is essentially cross-session user data accumulation, so tenant isolation, per-user access control, exportability and thorough deletion are all mandatory. Deletion must be real deletion, including notes, indexes and derived representations.
Give memory a “cooldown period.” Observe newly written notes for a few rounds before raising their confidence, to avoid solidifying a one-off, occasional conclusion into a long-term rule.
Typical pitfalls list: treating summary compression as memory; injecting candidate notes without verification; not deduplicating, causing memory bloat and rising retrieval noise; old conclusions that cannot be overridden; injected content lacking sources and therefore unauditable; offline tasks occupying compute without limit.
8. Conclusion
The value of this mechanism lies not in making the context “hold more,” but in treating memory as an engineering object with a lifecycle to be managed: online does only lightweight capture; offline distills noise-heavy logs into trustworthy experience through replay, consolidation, verification and revision; then it is injected on demand to change the next decision. This gives agents continuity and self-correction ability in cross-session scenarios, and because the whole process is based on plain text, traceable and deletable, its deployment cost is far lower than parameter-level approaches. For teams building their own task-oriented agents, start with a three-step minimal loop of “raw records + atomic notes + offline verification,” then gradually add memory representation and conflict resolution — the payoff usually arrives faster than expected.
