Agent Memory Engineering with a Dual-System Architecture

    This article presents a dual-system architecture for agent memory, splitting memory processing into an online, low-latency pipeline and an offline, high-compute pipeline. It explains the role boundaries, data formats, and implementation details of both pipelines, covering append-only raw traces, structured fact extraction, layered profile updates, rolling summarization, mental model extraction, knowledge graph construction, and intent prediction. It also discusses consistency, cost control, and a phased rollout plan for teams building reliable agent memory.

    1. The Problem: Why Agent Memory Is Easy to Write but Hard to Process

    In the engineering practice of AI agent applications, the memory module is often the most underestimated part, yet it has the biggest impact on the final user experience. Most early implementations simplify memory to “append the conversation to a list and concatenate it into the prompt at retrieval time.” This looks usable in the short term, but as the number of conversation turns grows, three problems quickly surface:

    1. Context bloat: Historical text accumulates linearly, and token cost and latency rise at the same time.
    2. Information dilution: Key constraints get buried under a large amount of small talk and repeated statements, so the model cannot grasp the main point.
    3. Lack of structure: Memory is a pile of unordered fragments and cannot support questions that require summarization and reasoning, such as “what does this user prefer” or “why did they abandon the approach last time.”

    Drawing on the dual-system idea of “fast thinking / slow thinking” from cognitive science, a more reasonable engineering paradigm is to split memory processing into two pipelines: one online and low-latency, responsible for faithful recording and immediate organization; one offline and high-compute, responsible for summarization, modeling, and prediction. This article calls this approach a dual-system memory architecture and expands on its responsibility boundaries, data shapes, and implementation points layer by layer.

    2. Overall Architecture: A Day Shift and a Night Shift

    • Online system (day shift): Triggered immediately after each user input, with the goal of “lose no information and stay available at any time.” It performs four types of actions: writing raw traces, extracting structured facts, updating the user profile, and compressing conversation history. The constraint is latency sensitivity, usually requiring completion within milliseconds to hundreds of milliseconds, so the logic must be deterministic, incremental, and idempotent.
    • Offline system (night shift): Runs in batch or streaming micro-batch mode, with the goal of “distilling models, building associations, and predicting the next step.” It performs three types of actions: extracting mental models (abstractions of user goals, habits, and cognitive level), building a knowledge network (graphing entities and relationships), and predicting intent (producing a probability distribution of possible next requests). The constraint prioritizes throughput and quality, allowing calls to stronger models, multiple rounds of validation, and deduplication.

    The two pipelines are decoupled through shared storage: the day shift is only responsible for “append and update,” and the night shift is only responsible for “rewrite and aggregate,” avoiding long transactions and unpredictable latency in the online path.

    1. User input
    2. │
    3. ├─► Online pipeline ──► Raw trace store (append-only)
    4. │ ──► Fact table (structured, searchable)
    5. │ ──► User profile (incremental update)
    6. │ ──► Conversation summary (rolling compression)
    7. │
    8. └─► Offline pipeline ──► Mental model (abstract profile / goal tree)
    9. ──► Knowledge network (entity-relation-event)
    10. ──► Intent prediction (candidate set + confidence)

    3. Online Pipeline: Engineering Details of the Four Actions

    3.1 Write Raw Traces (Append-Only Log)

    Raw traces are the “negatives” of memory. They must be lossless, timestamped, tagged with the source, and append-only. Each record should contain at least the session ID, turn index, role, original text, timestamp, and references to the retrieval fragments hit in that turn. The value of keeping the negatives is that any later extraction logic can be re-run, so you do not have to worry about permanent information loss when upgrading models or adjusting prompts.

    3.2 Fact Extraction

    Extract stable, reusable statements from the conversation, such as “the deployment environment is a container platform,” “data is retained for 30 days,” or “reports are sent every Monday.” There are three engineering points:

    • Structured fields: subject, predicate, object, effective time, confidence, and source turn;
    • Idempotent writes: merge by the key of “subject + predicate,” and overwrite by time and new evidence on conflict;
    • Invalidation support: set an expiration or version for facts to avoid expired constraints polluting the context over the long term.
    1. {
    2. "subject": "Project A",
    3. "predicate": "deployment target",
    4. "object": "container platform",
    5. "valid_from": "2024-05-01T10:00:00Z",
    6. "confidence": 0.92,
    7. "source_turn": 17
    8. }

    3.3 Profile Update

    The profile is a set of long-term stable preferences and constraints. The difference from facts is that it is more abstract and changes more slowly. A “layered + decay” strategy is recommended: divide the profile into four layers—identity attributes, technical preferences, interaction habits, and forbidden constraints; use different update frequencies and confidence thresholds for each layer; and apply weight decay to items that have not been verified for a long time, so that stale preferences do not keep affecting output.

    3.4 Rolling Summarization

    When the number of turns exceeds a threshold, rolling compression is triggered: the oldest segment of the conversation is folded into a structured summary (goals, confirmed conclusions, open questions, rejected options), while the most recent turns are kept in original text to preserve detail. The summary should explicitly mark “rejected” items. This is a point that many implementations ignore but is extremely critical—if the model does not know that an approach has already been rejected, it will keep recommending it.

    4. Offline Pipeline: A Three-Level Leap from Records to Cognition

    4.1 Extract Mental Models

    A mental model is not a restatement of the profile, but an abstraction of “how the user understands problems and makes decisions.” You can induce the following from history: commonly used terms and abbreviations, acceptable solution complexity, requirements for certainty, and verification habits. The recommended output form is “hypothesis + evidence + confidence,” and it should be allowed to be overturned by new evidence, avoiding rigid stereotypes that cannot be corrected.

    4.2 Build a Knowledge Network

    Connect facts, entities, and events into a graph: nodes are entities (services, datasets, metrics, people), and edges are relationships (dependency, ownership, causality, temporal order). The benefit of graphing is that it supports multi-hop queries, for example, “which services share common dependencies with last week’s incident.” For implementation, a hybrid index of adjacency lists + vector retrieval can be used: structured relationships go through exact matching, fuzzy semantics go through similarity recall, and then a unified ranking is applied.

    4.3 Intent Prediction

    Based on the recent behavior sequence and the knowledge network, generate candidate next requests and score them. Engineering does not need to pursue a complex model; a lightweight combination of “rule templates + behavior frequency statistics + similarity retrieval” can get the loop running first, and stronger sequence modeling can be introduced gradually. Prediction results should not be executed directly, but only injected as hints and candidates, to avoid false triggering.

    5. Consistency and Cost Control

    • Write-read separation: The online path only writes, and the offline path reads and then rewrites, reducing lock contention;
    • Idempotence and deduplication: Both extraction and profile updates are merged by stable keys, so repeated runs produce consistent results;
    • Tiered storage: Raw traces go to object storage, structured facts go to relational storage, and vectors and graphs go to retrieval-oriented storage; hot and cold tiers reduce costs;
    • Budget constraints: Set strict token and call-count limits for the online path, and degrade to “write raw traces only” on timeout;
    • Observability: Establish logging services and monitoring alerts for metrics such as extraction hit rate, profile conflict rate, summary compression ratio, and prediction accuracy.

    In the first phase, make “negatives + facts + rolling summaries” solid; these three items alone can significantly alleviate context bloat. In the second phase, add profile layering and conflict resolution. In the third phase, introduce the knowledge network and intent prediction. Every phase retains re-run capability: because raw traces are lossless, any iteration of extraction logic can be replayed and validated offline. This is also the biggest engineering dividend of the dual-system architecture compared with “single-line concatenation.”