# Memory Architecture Design

> Use when designing or reviewing how an AI agent stores, organizes, and reuses what it learns across tasks and sessions. Covers layered memory architectures, working versus episodic versus semantic versus procedural stores, write paths and consolidation triggers, indexing and retrieval interfaces, capacity budgets, and failure isolation between memory layers, with scoring terms for memory architecture design, agent state management, and long term agent memory.

- Skill: `mizazhaider-ceh/memory-architecture-design` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/memory-architecture-design`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/memory-architecture-design/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/memory-architecture-design

---


Agent memory is not one store, it is a set of stores with different
lifetimes, trust levels, and access patterns. Working memory holds the
current task. Episodic memory holds what happened. Semantic memory
holds durable facts. Procedural memory holds how to do things. Mixing
them into a single flat log is the most common architecture mistake,
because a stale observation then competes on equal footing with a
verified fact, and a how-to note is recalled as if it were evidence.
This skill covers how to separate the layers, how writes flow between
them, and how to keep one failing layer from corrupting the rest.
Schemas live in ../../../memory/MEMORY_SCHEMA.md and lifecycle rules
in ../../../memory/LIFECYCLE.md. Related skills are
../memory-capture/SKILL.md, ../memory-recall/SKILL.md, and
../memory-consolidation/SKILL.md.

## Quick Workflow

1. Name the layers the task actually needs, and leave out the rest.
2. Define the write path for each layer, including who may write and
   what validation runs before the write lands.
3. Define the promotion path, meaning which events move a record from
   episodic to semantic or procedural, and what evidence that requires.
4. Set a capacity budget and a TTL per layer before the store grows.
5. Isolate failures, so a corrupt or poisoned layer degrades to
   "no recall" instead of "wrong recall".
6. Test recall from each layer separately before wiring them together.

## 1. The four layers and what each one is for

Working memory is the current conversation and task state. It is fast,
small, and disposable, and it must never be treated as durable truth.
Episodic memory records dated observations tied to an agent, a host,
or a session. Semantic memory holds facts that survived verification,
with confidence and source links. Procedural memory holds reusable
methods, each with the conditions under which it applies.

A record should carry its layer explicitly, because retrieval, TTL,
and trust rules all key off it. The schema below is the minimum
useful shape for a layered store.

```json
{
  "memory_record": {
    "id": "mem_20261027_0042",
    "layer": "semantic",
    "kind": "fact",
    "agent": "hunter-01",
    "text": "Staging API tokens expire after 3600 seconds.",
    "confidence": 0.92,
    "created": "2026-10-27T05:00:00Z",
    "expires": "2027-01-25T05:00:00Z",
    "sources": ["obs_20261027_0011"],
    "tags": ["staging", "api", "auth"],
    "disputed": false
  }
}
```

Rules that follow from the schema:

- A layer value outside the four known layers is rejected at write
  time, never silently coerced.
- Episodic records always carry a timestamp and an agent id, so a
  later reader can judge freshness and provenance.
- Semantic records require at least one source id. A fact with no
  source is an episodic claim, not a semantic fact.
- Procedural records carry applicability conditions, not just steps,
  so retrieval can filter out methods that do not fit the situation.

## 2. Write paths and promotion rules

Every layer needs its own write path, because the validation differs.
Episodic writes are cheap and frequent. Semantic writes are gated.
Procedural writes require a successful run, not just a plausible plan.
The promotion configuration below makes those gates explicit and
reviewable instead of leaving them as tribal knowledge.

```yaml
# memory-architecture.yaml - promotion and write gates per layer
layers:
  episodic:
    max_records: 100000
    ttl_days: 30
    write_gate: none
    requires_source: false
  semantic:
    max_records: 20000
    ttl_days: 365
    write_gate: two_independent_observations
    requires_source: true
    min_confidence: 0.7
  procedural:
    max_records: 5000
    ttl_days: 365
    write_gate: verified_successful_run
    requires_source: true
    min_confidence: 0.8
promotion:
  episodic_to_semantic:
    trigger: second_matching_observation
    action: create_semantic_record_with_both_sources
  semantic_to_deprecated:
    trigger: contradiction_by_newer_direct_observation
    action: mark_disputed_and_require_review
```

Promotion is where most architectures quietly rot. If promotion is
automatic and ungated, rumours become facts. If promotion never
happens, the semantic layer stays empty and every task re-derives the
same knowledge. Review the promotion log weekly, and treat a semantic
record with a single source as a bug, not a shortcut.

## 3. Retrieval interfaces per layer

Do not expose one generic query over all layers. Working memory is
read in full by the agent loop. Episodic recall is filtered by time
range and agent. Semantic recall is filtered by confidence threshold.
Procedural recall is filtered by applicability tags. The interface
below keeps those contracts separate in code, so a caller cannot
accidentally read episodic noise as semantic truth.

```python
"""Layered retrieval interface. Each layer has its own read contract."""

class LayeredMemory:
    def __init__(self, store):
        self.store = store

    def working(self):
        """Current task state only. Never persisted as fact."""
        return self.store.working_snapshot()

    def episodic(self, query, agent=None, since=None, limit=20):
        """Dated observations, newest first, no confidence filter."""
        return self.store.search(
            layer="episodic", query=query, agent=agent,
            since=since, limit=limit)

    def semantic(self, query, min_confidence=0.7, limit=10):
        """Verified facts only. Low-confidence rows never surface."""
        rows = self.store.search(
            layer="semantic", query=query, limit=limit * 3)
        return [r for r in rows if r.confidence >= min_confidence][:limit]

    def procedural(self, query, applies_to, limit=5):
        """Methods whose applicability tags match the situation."""
        rows = self.store.search(layer="procedural", query=query, limit=limit)
        return [r for r in rows if applies_to in r.applies_to]
```

## 4. Capacity budgets and failure isolation

A memory store without a budget becomes a liability, slow to query,
expensive to back up, and hard to audit. Set per-layer caps, and
define what happens at the cap before it is reached. Eviction should
remove the lowest value records first, meaning expired rows, then
low-confidence episodic rows, then old procedural rows that have not
been used. Semantic facts are evicted only by explicit review, never
by an automatic cap.

```sql
-- Capacity report: one row per layer, with oldest and lowest value rows
SELECT layer,
       COUNT(*) AS record_count,
       MIN(created) AS oldest_record,
       SUM(CASE WHEN confidence < 0.5 THEN 1 ELSE 0 END) AS low_confidence
FROM memory_records
GROUP BY layer
ORDER BY record_count DESC;

-- Eviction candidates: expired episodic rows first, never disputed facts
SELECT id, layer, created, confidence
FROM memory_records
WHERE layer = 'episodic'
  AND (expires IS NOT NULL AND expires < CURRENT_TIMESTAMP)
ORDER BY created ASC
LIMIT 1000;
```

Failure isolation means each layer fails closed. If the semantic
index is corrupt, semantic recall returns an explicit error and the
agent proceeds without it, rather than falling back to episodic rows
and presenting them as facts. If the episodic store is unavailable,
the agent still works from working and semantic memory. Log every
degraded-recall event, because silent degradation is how wrong
answers become normal.

## Edge cases

- A task needs only working memory. Do not build the full stack.
  A single-session script with no cross-task reuse needs no semantic
  layer, and adding one creates retention obligations for no benefit.
- Two agents share one store. Scope semantic facts by tenant or
  project, and never let one agent's episodic noise promote into
  another agent's semantic facts.
- A record is both a fact and a method. Store it once, in the layer
  that matches its primary use, and cross-reference it from the other
  layer instead of duplicating the text.
- The store must work offline. Keep the layered schema in SQLite so
  the architecture survives without a vector database or a remote
  service, and treat embeddings as an optional index, not the store.
- Promotion evidence is deleted. A semantic record whose sources are
  gone is demoted to episodic until fresh evidence arrives, and the
  demotion is logged with the reason.

## Key references

- CWE-200 (Exposure of Sensitive Information to an Unauthorized
  Actor): why layer scoping and access control matter for memory.
- SQLite documentation: https://sqlite.org/docs.html
- Python sqlite3 module: https://docs.python.org/3/library/sqlite3.html
- ../../../memory/MEMORY_SCHEMA.md and ../../../memory/LIFECYCLE.md
  in this repo.

