Agent Memory Architecture: A Practical Guide to Two-Tier Memory Design

    This article breaks down a practical two-tier memory architecture for AI agents: a daily append-only log for short-term working memory and a single consolidated file for long-term semantic memory. It explains why stateless LLMs need memory built at the engineering layer, compares this lightweight approach with full-context stacking and vector retrieval, and covers context assembly order, token budgets, write and consolidation flows, and engineering concerns such as consistency, auditability, privacy, and fallback behavior. Readers will learn how clear lifecycle-based layering can keep memory simple, auditable, and cost-efficient.

    1. Background: Stateless LLMs and the Memory Gap

    LLM inference is inherently stateless. Every session is a fresh forward pass, and the model does not automatically retain information from the previous turn, let alone the previous second. What looks like “remembering” is really the caller stitching prior content back into the input. As a result, an agent’s memory is not a built-in model capability; it is something designed at the engineering layer.

    Two common approaches in the industry each have clear weaknesses.

    The first is full-context stacking: appending the raw conversation history to the context window until the length limit is hit. It has three problems. Token consumption grows roughly linearly with the number of turns, so cost and latency rise together. Key information gets diluted in a long context, causing “middle forgetting” where constraints from earlier text stop applying later on. And the history is mixed with a lot of ineffective small talk and repeated content, giving a low signal-to-noise ratio.

    The second is vector-retrieval memory: writing history slices into a vector store and recalling them by similarity. This adds extra storage and operational components and lengthens the pipeline. More importantly, recall quality is unstable. Semantic similarity does not mean the current task needs it, so it tends to retrieve fragments that “look relevant but are useless,” and it struggles to precisely express time decay and the priority of explicit instructions.

    This article discusses a lighter route: explicitly splitting memory into a “flow” tier and a “consolidated” tier, carried by two plain-text files and assembled into the system prompt through an agreed read/write process. Its value is not structural complexity but clear separation of responsibilities, auditability, and portability.

    2. Core Design: Splitting Responsibilities Between the Flow Tier and the Consolidated Tier

    Flow tier (daily records): Markdown files with a date granularity, one per day, append-only with no modification. Content includes factual events of the day, decisions made, tasks completed, and unfinished items. Its role is short-term working memory, answering “what happened recently.”

    Consolidated tier (long-term memory): a single Markdown file that stores stable information distilled from the flow: long-term user preferences, recurring project background, key technology choices and their reasons, and pitfalls already encountered along with how to avoid them. Its role is long-term semantic memory, answering “which conclusions about this user and this project remain valid over the long term.”

    This split mirrors the basic pattern of human memory: what you had for lunch yesterday is forgettable flow, while “no cilantro, allergic to seafood” is consolidation that must be retained long-term. Mixing the two in one structure inevitably leads to either context bloat or important constraints being missed during retrieval.

    A suggested directory layout:

    1. agent_memory/
    2. ├── daily/
    3. │ ├── 2026-02-11.md
    4. │ ├── 2026-02-12.md
    5. │ └── 2026-02-13.md
    6. ├── MEMORY.md
    7. └── archive/ # Archive area for expired flow

    3. Context Assembly: Read Order and Budget Control

    The recommended assembly order at session start is: system role and tool descriptions → long-term memory → today’s flow → the last N turns of conversation → the user’s current input. Placing long-term memory near the front takes advantage of the model’s stronger adherence to earlier instructions; placing today’s flow close to the user input ensures the timeliness of recent facts.

    Budget control needs to be explicit rather than “read everything in”:

    1. def build_system_prompt(today_notes: str,
    2. long_term: str,
    3. notes_budget: int = 1500,
    4. memory_budget: int = 2000) -> str:
    5. def clip(text: str, budget: int) -> str:
    6. return text if len(text) <= budget else text[-budget:] # Keep the latest content at the tail of the flow
    7. return (
    8. "You are the user's long-term assistant. The memory below has two tiers:\n"
    9. "[Long-term memory] Stable preferences and key conclusions, with higher priority than the flow.\n"
    10. f"{clip(long_term, memory_budget)}\n"
    11. "[Today's flow] Recent facts, for context reference only.\n"
    12. f"{clip(notes_budget and today_notes, notes_budget)}\n"
    13. "On conflict, explicit constraints in long-term memory take precedence."
    14. )

    Two key points: when long-term memory is too long, trim by item priority rather than simple truncation; when the flow is too long, keep the tail, because information closer to the current moment is more relevant.

    4. Writing and Consolidation: Making Consolidation Actually Happen

    Flow writing should be triggered after each task turn ends, using append mode with timestamps and structured subheadings for easier later parsing:

    1. ## 14:20 Task: Adjust retrieval ranking
    2. - Decision: Lower the recall threshold from 0.75 to 0.68 to observe false recalls
    3. - Fact: About 120,000 records; rebuilding the index took 3 minutes
    4. - Todo: Add a control evaluation set tomorrow

    Consolidation is best run on a fixed cycle (such as at the end of each day or every N turns). The input is the day’s flow plus the existing long-term memory, and the output is a set of “add/modify/delete” items rather than a full rewrite. Having the model emit structured operations can significantly reduce information drift caused by repeatedly rewriting long-term memory:

    1. [
    2. {"op": "add", "section": "preferences", "text": "Prefers compact JSON in API responses, no extra fields"},
    3. {"op": "update", "section": "project background", "target": "ranking strategy", "text": "Threshold 0.68, false recalls acceptable"},
    4. {"op": "drop", "section": "to confirm", "target": "caching approach"}
    5. ]

    Long-term memory itself also needs capacity constraints and a layered structure, for example partitioned into “preferences / project background / technical decisions / pitfall records,” with each section limited in item count and character cap. When exceeded, merge and deduplicate first, then evict low-value items. Flow files are archived by time, keeping only the most recent several days within the assemblable range.

    5. Engineering Implementation Notes

    • Consistency: Use single-file append for writes to avoid concurrent overwrites; route long-term memory consolidation through a single-writer model to prevent multiple instances from rewriting simultaneously.
    • Auditability: Both tiers are plain text and can be put under version control directly; the diff is the change history, so when a “memory error” occurs you can quickly locate which consolidation step introduced it.
    • Privacy and compliance: Define which fields may be retained long-term, mask sensitive information or set expiration times, and provide one-click clear and export capabilities.
    • Failure fallback: On read failure, start with empty memory rather than interrupting the session; on consolidation failure, keep the day’s flow and wait for the next retry.
    • Evaluation: Build a small evaluation set with three case types—“long-term preference adherence,” “cross-day fact recall,” and “conflict resolution”—and compare pass rates and token cost across different assembly strategies.
    • Cloud deployment: The storage layer can use object storage or file storage to hold Markdown; scheduled consolidation can be triggered by task scheduling or a message queue; the runtime can sit on a container platform, with logging and monitoring/alerting services to observe call volume and failure rates. Baidu AI Cloud offers corresponding product categories for these general capabilities that can be combined as needed.

    6. Boundaries and Applicable Scenarios

    This approach is not a cure-all. It fits scenarios with a limited number of users and projects, interaction mainly about advancing tasks, and a need for strong explainability, such as personal assistants, operations assistants, and domain Q&A bots. When you need fuzzy semantic matching across massive history, or when the user base reaches a million with highly independent memory for each, the management cost of a pure file approach rises. In that case, you can add retrieval capability on top of the consolidated tier, but the mainstay of “separating flow from consolidation” should stay unchanged.

    What is truly worth borrowing is not a specific implementation but that design principle: first layer memory by lifecycle, then discuss storage medium and retrieval algorithms. Once the layering is clear, the implementation can be minimal, and cost and controllability actually improve.