Agent Architecture: Designing and Implementing the Memory Layer

    This article explains why a thin orchestration framework and thick capability modules are not enough for long-running AI agents, and how a dedicated memory layer fills the gap. It presents a four-tier memory model covering factual, episodic, semantic, and procedural information, a retrieve-before-generate pipeline with filtering and write thresholds, and a pattern for improving behavior without changing capability internals. It also covers consistency, privacy, observability, evaluation metrics, storage choices, and common anti-patterns.

    1. The Starting Point: Determinism Is a Strength, but Not the Whole Story

    A design principle often cited in agent architecture is this: keep the orchestration framework thin and make the capability modules thick. The idea is to consolidate flow control, context management, and tool orchestration into a stable execution kernel, while domain knowledge, task steps, and validation rules are distilled into reusable capability units.

    This principle works well in engineering terms. Capability modules behave like pure functions: the same input produces the same output, behavior is predictable, testable, and rollback-friendly. But when a system needs to run for a long time and serve the same class of scenarios repeatedly, pure determinism exposes a structural gap: the system does not get better through use.

    2. A Common Misreading: Capability Modules Never Forget, but They Also Never Distill

    “Never forgetting” sounds like an advantage. In practice, it describes the property of stateless execution. Every invocation starts from zero, with no causal link to the previous one. The experience from the hundredth task is not carried into the hundred-and-first.

    This is the opposite of how human skills are acquired. A person does not need to recall the fine details of posture from every bicycle ride; they only need to “know how to ride.” That knowing is a disposition filtered and compressed out of a large number of repetitions. Forgetting here is not a defect but a distillation mechanism: low-value details fade, and high-value regularities are retained as intuition.

    So the “thick” in thick capability modules is thick in quantity: write a hundred capability units, and the system has a hundred capabilities. But those capabilities sit side by side rather than accumulating. No preferences or shortcuts grow out of usage.

    3. Restructuring the Picture: Skeleton, Muscle, and Nerves

    Comparing an agent to a human body makes the missing layer easier to locate:

    • The orchestration framework is the skeleton: it determines structure, posture, and direction of action, and constrains what can be executed.
    • Capability modules are the muscle: they determine strength, speed, and the precision of specific movements.
    • The memory layer is the nervous system: it connects skeleton and muscle, carrying feedback from the last action into the next one.

    Muscle without nerves contracts independently every time. Doing a hundred squats works because the tissue undergoes structural change under repeated stimulus; a capability module executing the same task a hundred times does not change at all. The memory layer is responsible for exactly this kind of structural change: extracting dispositions from task trajectories and making experience-based adjustments on top of existing capabilities, rather than continuously adding new ones.

    4. A Layered Model for Memory

    To implement memory, first recognize that it is not a database but at least four kinds of information with different properties:

    1. Factual memory: entities and configuration in the environment, such as the meaning of API fields, directory structure, and data table constraints. Changes slowly and can be stored with strong consistency.
    2. Episodic memory: concrete task trajectories, including inputs, steps, tool calls, results, and failure points. Used for retrospectives and retrieving similar cases.
    3. Semantic memory: rules and preferences induced from multiple episodes, such as “this user prefers short conclusions” or “step three in this scenario tends to skip validation.”
    4. Procedural memory: stable operating routines and preconditions, close to “craft,” existing as process templates or checklists.

    The key design principle is layered writes and layered eviction: episodic memory keeps its raw fidelity but carries time decay; semantic memory requires an evidence threshold and conflict resolution; changes to procedural memory must be auditable and rollback-capable.

    5. Writing and Retrieval: Making Experience Actually Usable

    If memory cannot be retrieved reliably, it is just a log. The recommended engineering chain is “retrieve before generate”:

    1. task input
    2. -> scenario normalization (intent, domain, constraints)
    3. -> memory retrieval (semantic similarity + structured filtering + recency weighting)
    4. -> context assembly (budget trimming, conflict flagging)
    5. -> capability module execution
    6. -> trajectory persistence and quality assessment
    7. -> experience extraction (write to semantic/procedural memory only if it passes the bar)

    A few details that are easy to overlook:

    • Retrieval needs filters. Vector similarity alone will recall old cases that “look similar but have different constraints,” so structured fields (environment, version, permissions) must be applied on top.
    • Context has a budget. During assembly, order by relevance and freshness, and explicitly flag conflicting evidence so the model does not waver between contradictory information.
    • Writing needs a threshold. Only trajectories that succeed and pass validation may be promoted to semantic memory; otherwise incidental errors get frozen into “experience.”

    6. The Right Shape of Progressive Optimization

    Deterministic execution pursues “same input, same output”; a system with memory pursues “same scenario, better than last time.” The two do not conflict; they divide the work:

    • Capability modules own repeatable correctness: interface contracts, parameter validation, and failure retries stay constant.
    • The memory layer owns measurable improvement, for example fewer wasted retrieval rounds, shorter path lengths, and fewer repeated clarifying questions.

    In implementation, there is no need to change the internal logic of capability modules. Instead, do three things around them: adjust retrieval results, adjust parameter defaults, and adjust validation strictness. A sketch:

    1. def run(task, memory, skill):
    2. ctx = memory.retrieve(task, filters=task.filters, budget=4000)
    3. params = memory.tune_defaults(task.domain, base=skill.default_params)
    4. result = skill.execute(task, context=ctx, params=params)
    5. ok = skill.verify(result)
    6. if ok:
    7. memory.extract(task, result, min_evidence=3) # skip the write if evidence is insufficient
    8. return result

    This way, improvement is data-driven and explainable, rather than hardcoding experience into flow branches.

    7. Engineering Constraints: Consistency, Privacy, and Evaluation

    Memory introduces state, and with it the full set of state management problems.

    • Consistency: after the environment changes, old memory may be invalid, so version markers and invalidation propagation are needed; when semantic rules conflict, arbitrate by amount of evidence and recency.
    • Privacy and compliance: episodic memory may contain sensitive data, so field-level masking, per-tenant isolation, deletion, and retention policies should be supported.
    • Observability: record “what was recalled, why it was adopted, and what the result was,” otherwise it is impossible to tell whether the problem is in retrieval or in execution.
    • Evaluation: establish layered metrics — retrieval hit rate, context validity rate, task success rate, average number of steps, and repeated error rate. Improvement must show up in the metrics, not in subjective impressions.
    • Storage selection: use relational storage for structured metadata, object storage plus a retrieval index for trajectories and text, a message queue to decouple asynchronous extraction, and connect runtime metrics to logging and monitoring/alerting services. These are all general capability categories; the specific product form can be chosen from existing cloud resources.

    8. Common Anti-Patterns

    • Stuffing every trajectory into the context indiscriminately: cost goes up and noise drowns out critical constraints.
    • Using memory to override deterministic validation: experience may only influence defaults and ordering, never replace hard validation.
    • Missing an eviction mechanism: memory grows without bound and retrieval quality degrades over time.
    • Tightly coupling extraction with execution: extraction logic blocks the main path, so it should be made asynchronous and allowed to retry on failure.

    9. Conclusion

    A thin orchestration framework and thick capability modules solve “can it be done correctly”; the memory layer solves “can it get better over time.” Treat memory as a nervous system rather than an add-on store, use a layered model to separate factual, episodic, semantic, and procedural information, use filtered retrieval and thresholded writes to protect quality, and validate improvement with clear metrics. Only then can an agent move from repeated execution to accumulated experience. This is neither a rejection of determinism nor an overturning of stateless design; it is filling in the layer that lets an existing architecture keep evolving.