Four-Tier Memory and Core Documents: Engineering AI Agents for Production

    AI agent demos often impress but fail in daily use—not because of weak models, but because of three engineering gaps: context drift, unstructured experience, and missing execution constraints. This article presents a production-ready architecture built on a four-tier memory system (conversation clustering, execution distillation, semantic preference modeling, and skill consolidation), two feedback loops, three core documents that anchor agent behavior, and practical guidance on retrieval ranking, metrics, common pitfalls, and deployment. Readers will learn how to make agents remember reliably, stay within constraints, and reuse skills as they operate over time.

    1. The Starting Problem: Why Agents Impress in Demos but Fail in Daily Use

    After integrating an agent framework, many teams share the same experience: stunning in demos, unreliable in daily work. The root cause is usually not the model itself but three engineering gaps:

    1. Context gap: As conversations grow longer, early constraints get pushed out of the window, and behavior starts to drift.
    2. Experience gap: Mistakes made last time get repeated this time, because failure trajectories are never captured in a structured way.
    3. Constraint gap: Without explicit execution rules, the model “improvises”—producing plausible-looking output that cannot be reproduced.

    So the core question of agent engineering is not “switch to a stronger model,” but turn memory into a system, turn constraints into documents, and turn experience into reusable skills.

    2. Overall Architecture: Four-Tier Memory + Two Loops

    Organize memory bottom-up into four tiers, each addressing a different level of granularity:

    1. L1 Conversation clustering — denoise, compress, and archive raw interactions
    2. L2 Execution distillation — extract reusable lessons from tool-call trajectories
    3. L3 Deep semantic understanding — summarize user preferences, boundaries, and long-term goals
    4. L4 Skill consolidation — crystallize frequent, stable experience into callable skills

    Above the four tiers sit two closed loops:

    • Memory loop: L1 → L2 → L3, becoming more abstract, sparser, and more stable as you move up.
    • Skill loop: L3 → L4 → execution → new trajectories flowing back into L1, improving with use.

    The design principle is “remember less, but remember well“: the bottom tier keeps everything but can evict; the top tier keeps only a small number of high-confidence, high-reuse entries. Retrieval should be weighted by tier so that massive low-quality memory doesn’t drown out key constraints.

    3. L1: Conversation Clustering and Compression

    The goal of L1 is not just to store interactions, but to store them retrievably. Three steps:

    • Segment: Split sessions by task boundary, not fixed length—one goal, one fragment.
    • Cluster: Apply semantic clustering to fragments; merge multi-round corrections for the same task into one cluster.
    • Summarize: Generate a structured summary per cluster (goal, constraints, result, failure points); keep the original text only as a reference.
    1. {
    2. "cluster_id": "c_0031",
    3. "task": "batch rename files",
    4. "constraints": ["preserve extensions", "no overwriting existing files"],
    5. "corrections": 2,
    6. "result": "success",
    7. "raw_ref": "obj://session-log/2026-08-12/c_0031"
    8. }

    In engineering terms, apply time-based decay and capacity limits: evict low-value entries on a schedule, move raw logs to low-cost storage such as object storage, and keep only summary indexes at the retrieval layer.

    4. L2: Distilling the Execution Process

    L2 captures how things get done, sourced from tool-call trajectories: what was called, with what parameters, how many failures, and how they were recovered. Distill one-off operations into experience entries of the form “trigger condition + action sequence + constraints + outcome”:

    1. {
    2. "id": "mem_0031",
    3. "layer": "L2",
    4. "type": "execution_lesson",
    5. "trigger": "batch file changes required and cannot be rolled back",
    6. "action": ["small-sample trial run", "sample validation", "generate rollback checklist", "full execution"],
    7. "constraint": ["must leave a rollback path before making changes"],
    8. "outcome": "passed on first attempt",
    9. "confidence": 0.82,
    10. "expire_at": "2026-09-12"
    11. }

    The key constraint: confidence must be outcome-driven. Successful, reused experience gains weight; failed or user-rejected experience loses weight until evicted—preventing “self-reinforcing bad habits.”

    5. L3: Deep Semantic Understanding and the Preference Boundary Table

    L3 deals with what the user actually wants—and explicitly does not want. Instead of piling up natural-language entries, use a paired boundary table (P and non-P) to express preferences:

    • The user expresses P (a want) → the system infers non-P (what to avoid and where the boundary lies) → recorded as a table → looked up directly next time.
    • P and non-P are semantically opposed but symmetric: if the user later prefers non-P, a reverse lookup handles it—no new entry needed.
    1. {
    2. "pair_id": "pref_07",
    3. "P": "conclusion first",
    4. "non_P": "no long preambles or background recaps",
    5. "hits": 12,
    6. "last_used": "2026-08-20"
    7. }

    The benefit: every correction automatically converges into a single boundary entry, growth stays controlled, and “preference reversal” scenarios are natively supported.

    6. L4: Skill Consolidation and the Skill Pyramid

    A skill is executable, encapsulated experience. At minimum it contains a trigger condition, inputs and outputs, steps, validation checkpoints, and failure fallback. Rather than a flat list, organize skills into a pyramid by call frequency and value:

    Tier Rough share Examples Characteristics
    Foundation ~55% File operations, command execution, web reading Used daily, stable
    General ~30% Troubleshooting, planning, code review Used frequently
    Specialized ~15% Data processing, design output, version management Scenario-specific
    Experimental ~5% Draft skills, newly validated ideas Low-frequency trial and error

    Add a promotion mechanism (example thresholds—calibrate to your team):

    • Experimental → Specialized: effectively invoked 3 times within 30 days with positive feedback;
    • Specialized → General: reused across 3 different projects without modification.

    The pyramid is a dynamic analytical lens, not a static label: regularly track hit rates and failure rates per tier, and let skills move up or down based on usage data.

    7. Core Documents: Constraints Before Capabilities

    From an execution-architecture standpoint, writing good core documents matters more than adding new skills. Maintain at least three:

    1. Master guide (e.g., AGENT_GUIDE.md): The hub linking all other documents—execution flow and rules, skill orchestration, reporting format, memory tiering, and fault-tolerance and escalation paths. It is the single entry point; other documents are referenced from it.
    2. Skill pyramid document (e.g., SKILL_LADDER.md): Records tier ratios, promotion/demotion rules, and an index of skill cards.
    3. Preference boundary document (e.g., PREFERENCE_TABLE.md): Maintains P/non-P paired entries with hit statistics.

    Three principles for writing these documents: executable (every rule maps to an action), verifiable (with acceptance criteria), and evolvable (with versions and change logs).

    8. Retrieval and Ranking: Making Memory Actually Useful

    Four-tier memory without a ranking strategy is effectively no memory at all. A practical scoring function:

    1. def score(item, query, now):
    2. base = 0.60 * semantic_sim(query, item) \
    3. + 0.25 * item.confidence \
    4. + 0.15 * recency(item, now)
    5. return base * LAYER_WEIGHT[item.layer] # higher weights for L3/L4

    Practical advice: keep injected entries to single digits per turn, prioritize L3 boundaries and L4 skill cards, and expand L1/L2 only on demand. Also record whether each injection was actually adopted, and use adoption rates to tune the parameters.

    9. Metrics and Common Pitfalls

    Recommended metrics: constraint violation rate, first-pass task success rate, manual rework rounds, average injected token count, and skill hit rate. Without measurement, a memory system degrades into a pile of logs.

    Common pitfalls:

    • Store without distillation: L1 grows unbounded; retrieval noise drowns the signal.
    • No experience down-weighting: bad practices get repeatedly reused.
    • Documents decoupled from implementation: the docs changed, but orchestration didn’t.
    • Linear growth of preference entries: use paired boundaries and reverse lookups to control scale.

    10. Deployment and Operations

    For production, deploy the memory index and skill repository on a container platform, keep raw logs and cold data in object storage, decouple task events through a message queue, feed run trajectories into a logging service, and set monitoring alerts with thresholds for spikes in constraint violations or rising skill failure rates. In cloud environments such as Baidu AI Cloud, these commodity capabilities (container platform, object storage, message queue, logging service, monitoring and alerting) can be combined directly, without building the full infrastructure stack yourself.

    Conclusion

    Agent reliability comes from structure, not from any single model capability. Four-tier memory solves “remembering”; three core documents solve “staying on track”; the skill pyramid and its promotion mechanism solve “reusing.” Once the three combine into the dual-loop system, it keeps improving with use—instead of just getting noisier.