@meow2149: How Should You Design a Long-Term Memory System When Building Your Own Agent? Recently I studied the memory mechanisms behind Codex, Claude Code, OpenClaw, Hermes Agent, and other products, along with research in the Agent Memory field. If I were to design one, I would build a dedicated memory subsystem (Memory Subsystem) in the Harness, consisting mainly of the following nine parts. 1、Memory Admission Use an LLM with Structured Output to extract user preferences, historical decisions, domain knowledge, and execution experience from authorized historical conversations and task execution records. Filter memories based on long-term value, applicability, and evidence quality, distinguishing between explicit user statements, external observations, and model inferences. Unverified inferences are kept only as candidate memories and are not treated as confirmed facts. Every memory retains its original source and source category. Sensitive information that should not be retained is filtered during the data collection stage, and authorization for retaining historical records is managed separately from authorization for using cross-session memories. 2、Hierarchical Memory Use a three-tier memory structure: ▪︎ L0: Core memory and navigation index. ▪︎ L1: Structured facts, domain knowledge, and task experience. ▪︎ L2: Raw conversations, tool calls, and execution records. Combined with Progressive Disclosure, new sessions load a permission-filtered L0 by default, L1 is retrieved on demand, and L2 is used to trace back to raw evidence the agent has permission to access. A fixed token budget is set for core memory to prevent the resident context from growing continuously as memory volume increases. Memory tier determines how information is loaded, not its credibility. 3、Dual-path Writing When a user explicitly requests saving, correcting, or deleting a memory, changes are submitted synchronously; for normal sessions that have been granted cross-session memory usage authorization, a background Worker extracts memories asynchronously. Each memory contains fields such as ID, content, source, scope, version, and status. Duplicate submissions and concurrent updates are handled through transactions, idempotency keys, and optimistic locking. Fact conflicts are identified by subject, attribute, applicability conditions, and effective time, then adjudicated based on sources and evidence; if no resolution is possible, the disputed status is retained. Borrowing Hermes Agent's Frozen Snapshot mechanism, memory persistence is decoupled from Prompt updates, keeping the prompt prefix containing core memory as stable as possible within a session to facilitate Prompt Cache reuse. Key corrections are synced through incremental context, with snapshot rebuilding when necessary. After a synchronous submission, subsequent reads open a new database read transaction to fetch the latest records. Full-text and vector indexes use eventual consistency — new memories may appear in search results with a delay, but outdated versions can no longer be returned as current facts. 4、Active Memory Retrieval Use Hybrid Retrieval combining BM25 full-text search with Embedding-based vector similarity search, fusing the two ranked result sets via RRF (Reciprocal Rank Fusion). Structured fields are precisely looked up through database indexes. First, define the candidate scope based on current permissions, scope, and usage authorization from authoritative data sources, letting these constraints participate directly in each retrieval path's Top-K recall rather than relying on potentially stale indexed permission fields or post-filtering after a full-database search. Expose three memory tools to the Agent: ▪︎ memory_search: retrieve relevant memories. ▪︎ memory_read: read detailed content of a specified memory. ▪︎ session_search: search historical conversations and raw evidence. The Agent initiates retrieval autonomously based on the current task, supporting multi-turn queries and evidence trace-back, with retrieval budgets in place. Retrieval relevance and memory credibility are evaluated separately. Recall results are also assessed against applicability conditions, target time, evidence quality, and version status to determine whether they apply to the current task. 5、Background Memory Consolidation (Dreaming) Borrowing the idea of Sleep-time Compute, introduce an independent Memory Worker to asynchronously organize cross-session memories. It is mainly responsible for four types of tasks: ▪︎ Consolidation: merging duplicate memories and organizing related knowledge. ▪︎ Reflection: tracing back to raw evidence and correcting erroneous generalizations. ▪︎ Promotion: moving stable, well-evidenced memories that need frequent use into the core layer. ▪︎ Demotion: removing memories no longer suitable for the resident context from the core layer while retaining on-demand retrieval capability. Use a persistent task queue and incremental cursors to process new and changed data, tracing back related memories on demand to avoid repeatedly scanning the entire history. Memory changes and their corresponding background tasks are committed in the same transaction, with task retries, idempotent processing, and recoverable incremental cursors ensuring that even if the process exits abnormally, committed changes can still be reprocessed by the Worker. Memory promotion is based on evidence support and reuse demand rather than simply recall count. Consolidated memories retain their original source and derivation relationships. Provenance Tracking identifies evidence from the same source, preventing a Recall Feedback Loop where the same memory is mistaken for having gained new independent evidence through repeated extraction and consolidation. 6、Temporal Memory & Forgetting For facts that change over time, reference the bitemporal model used by Zep / Graphiti. ▪︎ Valid Time: the time interval during which the fact holds true in the real world. ▪︎ Transaction Time: the time interval from when the fact version was recorded by the system until it is superseded or retracted. Maintain fact evolution through versions and supersedes relationships, supporting queries for current facts, historical facts, and what the system knew at a past point in time. Fact versions are selected based on the time point specified in the query, but access permissions, usage authorization, and deletion status always reflect the current effective state at read time. Introduce decay and fact invalidation mechanisms to handle changes in memory retrieval priority and fact validity, respectively. Memory deletion uses a Tombstone mechanism: first, mark the deletion synchronously to block subsequent reads and context injection, then asynchronously clean up memory content, associated summaries, indexes, caches, and other derived data. Deletion constraints not only reference memory IDs but must also cover excluded raw evidence snippets and their derivation relationships. Background tasks must validate deletion status and current authorization at both the extraction and commit stages, with final validation and writes completed in the same transaction to prevent stale tasks launched before a deletion from rewriting the same memory with a new ID afterward. 7、Memory Scoping & Governance Organize memories along four dimensions — User, Agent, Project, and Team — using composite access control to achieve sharing and isolation across different scopes. The Harness uniformly enforces permission and usage authorization checks for memory writes, retrieval, context injection, background consolidation, and derived data access. When deleting or revoking authorization, affected context snapshots and file views are invalidated synchronously, and context is rebuilt before the next model call, removing restricted memories from historical messages and tool returns. Separate fact credibility from instruction execution authority. Derived memories inherit the original source category and permission constraints; external statements not confirmed by the user cannot be directly converted into user preferences, and memory content cannot elevate its own instruction authority. Through source validation, structured extraction, and controlled writes, reduce the risk of Prompt Injection escalating through memory extraction, background consolidation, and cross-session recall into persistent memory poisoning. 8、Procedural Memory Through Reflection, distill task execution experience that has been practically validated and has stable reuse value into reviewable Skills. Organize SKILL.md according to the Agent Skills specification, along with on-demand scripts and reference resources, clearly defining applicable environments, prerequisites, operation flows, verification methods, and success criteria. Manage reviewed Skill files and version history — free of personal memories and sensitive information — through Git; meanwhile, use SQLite to uniformly maintain each Skill's effective version, enabled status, scope, and authorization information. The Harness loads Skills on demand via Progressive Disclosure based on the effective version recorded in SQLite. File changes in Git do not directly change the Skill version the Agent is currently using. 9、Storage Architecture Use a local-first unified storage architecture. ▪︎ SQLite: the single source of truth for memory records, permissions, and effective status. ▪︎ Markdown: reconstructable views of core memory and detailed knowledge. ▪︎ FTS5: full-text search with BM25 ranking. ▪︎ sqlite-vec: vector storage and similarity search. ▪︎ RRF: fusing ranked results from full-text and vector retrieval. ▪︎ SQLite-backed Task Queue: background task scheduling, incremental processing, and failure retries. ▪︎ Git: Skill file and version history management. All memory records and effective status changes are uniformly committed to SQLite, with Markdown and search indexes updated asynchronously as derived views. All derived views are read through a controlled access layer. Before returning results, fact versions are validated against the query time point, and deletion markers and access authorizations are cross-checked against the latest database state. Derived views may be eventually consistent, but deletions, authorization revocations, and usage authorization changes must take effect immediately in subsequent new reads, avoiding reuse of stale database read transactions or context snapshots. In this local-first architecture, memory storage, full-text search, vector search, and the persistent task queue all run on SQLite, with the Harness managing the memory lifecycle uniformly — no need to deploy a separate vector database, search engine, or message queue service.
Summary
作者在研究 Codex、Claude Code、OpenClaw、Hermes Agent 等产品的记忆机制后,提出了一套包含九个模块的 Agent 长期记忆子系统设计方案,涵盖记忆准入、分层记忆、双路径写入、混合检索、后台整合、时序遗忘、安全治理、程序性记忆与本地优先存储架构。
View Cached Full Text
Cached at: 11/29/26, 12:55 AM
How to Design a Long-Term Memory System for a Self-Built Agent
After researching the memory mechanisms of Codex, Claude Code, OpenClaw, Hermes Agent, and other products, and reviewing research in the Agent Memory domain, I’ve concluded that if I were to design one, I would build an independent Memory Subsystem within the Harness, consisting of the following nine parts.
1. Memory Admission
Using LLM + Structured Output, extract user preferences, historical decisions, domain knowledge, and execution experience from authorized historical conversations and task execution records.
Filter memories based on long-term value, applicability scope, and evidence quality, distinguishing between user-stated facts, externally observed facts, and model inferences. Unverified inferences serve only as candidate memories and are not treated as confirmed facts.
Each memory retains its original source and source category. Sensitive information that should not be persisted is filtered during the data collection phase, and authorization for historical record retention is managed separately from authorization for cross-session memory usage.
2. Hierarchical Memory
A three-tier memory structure:
- L0: Core memory and navigation index.
- L1: Structured facts, domain knowledge, and task experience.
- L2: Raw conversations, tool calls, and execution records.
Combined with progressive disclosure, new sessions load permission-filtered L0 by default, L1 is retrieved on demand, and L2 is used for tracing back to raw evidence the user is authorized to access.
Core memory has a fixed Token budget to prevent resident context from continuously expanding with total memory volume.
Memory hierarchy determines how information is loaded; it does not represent the credibility of the information.
3. Dual-path Writing
When a user explicitly requests saving, correcting, or deleting a memory, changes are submitted synchronously. For regular sessions that have been granted cross-session memory usage authorization, a background Worker extracts memories asynchronously.
Each memory contains fields such as ID, content, source, scope, version, and status.
Duplicate submissions and concurrent updates are handled through transactions, idempotency keys, and optimistic locking. Fact conflicts are identified by subject, attribute, applicable conditions, and effective time, and resolved using source and evidence. When no resolution is possible, a disputed state is retained.
Drawing on Hermes Agent’s Frozen Snapshot mechanism, memory persistence is separated from Prompt updates. Within a session, the stability of the prompt prefix containing core memory is maintained as much as possible to enable Prompt Cache reuse. Critical corrections are propagated through incremental context sync, with snapshot rebuilding when necessary.
After synchronous submission, subsequent reads open a new database read transaction to retrieve the latest records. Full-text and vector indexes use eventual consistency—new memories may appear in search results with a delay, but outdated versions can no longer be returned as current facts.
4. Active Memory Retrieval
Hybrid retrieval is used, combining BM25 full-text search with embedding-based vector similarity search, with results fused via RRF (Reciprocal Rank Fusion). Structured fields are looked up precisely via database indexes.
The candidate scope is first constrained by current permissions, scope, and usage authorization from authoritative data sources. These constraints participate directly in Top-K retrieval across all search paths, rather than relying on potentially stale permission fields in indexes or filtering after a full-database search.
Three memory tools are exposed to the Agent:
memory_search: Search for relevant memories.memory_read: Read the detailed content of a specific memory.session_search: Search historical conversations and raw evidence.
The Agent autonomously initiates retrieval based on the current task, supporting multi-turn queries and evidence tracing, with a retrieval budget in place.
Retrieval relevance and memory credibility are evaluated separately. Recall results must also be assessed against applicable conditions, target time, evidence quality, and version status to determine whether they apply to the current task.
5. Background Memory Consolidation (Dreaming)
Inspired by Sleep-time Compute, an independent Memory Worker is introduced to asynchronously organize cross-session memories.
It is primarily responsible for four types of tasks:
- Consolidation: Merge duplicate memories and organize related knowledge.
- Reflection: Trace back to raw evidence and correct erroneous generalizations.
- Promotion: Move stable, well-evidenced, and frequently needed memories into the core tier.
- Demotion: Move memories no longer suitable for resident context out of the core tier while preserving on-demand retrieval capability.
A persistent task queue and incremental cursors are used to process new and changed data. Associated memories are traced back on demand, avoiding repeated scans of the entire history.
Memory changes and their corresponding background tasks are committed within the same transaction. Through task retries, idempotent processing, and recoverable incremental cursors, committed changes can still be reprocessed by the Worker even if the process exits abnormally.
Memory promotion is based on evidence support and reuse needs, rather than merely relying on recall counts. Consolidated memories retain their original sources and derivation relationships.
Provenance Tracking identifies same-source evidence, preventing a recall feedback loop from causing the same memory to be mistaken for having received new independent evidence through repeated extraction and consolidation.
6. Temporal Memory & Forgetting
For facts that change over time, a bitemporal model (referencing Zep / Graphiti) is adopted:
- Valid Time: The interval during which the fact holds in the real world.
- Transaction Time: The interval from when the fact version was recorded by the system until it is superseded or retracted.
Fact evolution is maintained through versions and supersedes relationships, supporting queries for current facts, historical facts, and what the system knew at a past point in time.
Fact versions are selected based on the time point specified in the query, but access permissions, usage authorization, and deletion status always reflect the currently valid state at read time.
Weight decay and fact invalidation mechanisms are introduced to handle changes in memory retrieval priority and fact validity, respectively.
Memory deletion uses a Tombstone mechanism: deletion is first marked synchronously to block subsequent reads and context injection, then memory content, associated summaries, indexes, caches, and other derived data are cleaned up asynchronously.
Deletion constraints must cover not only the memory ID but also the excluded raw evidence fragments and their derivation relationships.
Background tasks must validate deletion status and current authorization at both the extraction and commit stages. Final validation and writes are completed within the same transaction, preventing tasks started before deletion from re-inserting the same memory with a new ID after deletion.
7. Memory Scoping & Governance
Memories are organized along four dimensions—User, Agent, Project, and Team—with compositional access control to manage sharing and isolation between scopes.
The Harness uniformly enforces permission and usage authorization checks for memory writes, retrieval, context injection, background consolidation, and derived data access.
When a deletion or revocation occurs, affected context snapshots and file views are invalidated synchronously, and the context is rebuilt before the next model invocation, removing restricted memories from historical messages and tool returns.
Fact credibility is separated from instruction execution authority. Derived memories inherit the source category and permission constraints of their original source. External statements not confirmed by the user cannot directly become user preferences, and memory content cannot elevate its own instruction authority.
Through source verification, structured extraction, and controlled writes, the risk of Prompt Injection evolving into persistent memory poisoning via memory extraction, background consolidation, and cross-session recall is reduced.
8. Procedural Memory
Through Reflection, task execution experience that has been validated in practice and has stable reuse value is distilled into reviewable Skills.
Skills are organized following the Agent Skills specification, with SKILL.md and optionally attached scripts and reference resources, clearly defining applicable environments, prerequisites, operational procedures, verification methods, and success criteria.
Skill files and version history that have been reviewed and contain no personal memory or sensitive information are managed via Git. At the same time, SQLite uniformly maintains the effective version, enabled status, scope, and authorization information for each Skill.
The Harness loads Skills on demand via progressive disclosure based on the effective version recorded in SQLite. File changes in Git do not directly change the Skill version the Agent is currently using.
9. Storage Architecture
A local-first unified storage architecture is adopted:
- SQLite: The single source of truth for memory records, permissions, and effective state.
- Markdown: Reconstructable views for core memory and detailed knowledge.
- FTS5: Full-text search with BM25 ranking.
- sqlite-vec: Vector storage and similarity search.
- RRF: Fusion of full-text and vector retrieval rankings.
- SQLite-backed Task Queue: Background task scheduling, incremental processing, and failure retries.
- Git: Skill file and version history management.
All memory record and effective state changes are committed uniformly to SQLite. Markdown and search indexes serve as derived views updated asynchronously.
All derived views are read through a controlled access layer. Before returning results, fact versions are validated against the query time point, and deletion flags and access authorizations are checked against the latest database state.
Derived views allow eventual consistency, but once deletions, revocations, or usage authorization changes are committed, they must take effect immediately in subsequent new reads, avoiding reuse of stale database read transactions or context snapshots.
In this local-first architecture, memory storage, full-text search, vector search, and the persistent task queue are all based on SQLite. The Harness uniformly manages the memory lifecycle, with no need to deploy separate vector database, search engine, or message queue services.
Similar Articles
@chenchengpro: The more fancy "memory" architectures you stack on an LLM Agent, the better the results? Not necessarily. A new paper tested 12 memory systems and found no universal winner. It decomposes Agent memory like a database — representation & storage, extraction, retrieval & routing, and maintenance — and tested Mem0, Letta, Zep, C…
A paper systematically evaluates 12 LLM Agent memory systems, breaks them into four modules, finds no single architecture dominates all scenarios, and reveals cost-performance trade-offs and common issues (e.g., 'past hallucinations').
@Pluvio9yte: https://x.com/Pluvio9yte/status/2070318502016426008
This article delves into the memory architecture of AI agents, using the Hermes four-layer memory model as an example, analyzes the limitations of the Claude Code memory system, and introduces how to add local memory capabilities to agents through open-source frameworks (such as EverOS), providing detailed deployment steps.
@yyyole: Agent memory entrepreneurship is booming! Many teams are working on it, with several mainstream approaches: The first, most brute-force: context expansion. The second, most common: RAG/vector database route, embedding historical content into a vector store for retrieval. The third is product-oriented: memory API route, packaging memory as an API for direct calls. Each approach has its clear pros and cons!
Introduces several mainstream approaches to Agent memory entrepreneurship, recommends the EverMind team's open-source project EverOS, which provides a Markdown-sourced local memory OS supporting dual-track memory, multimodal ingestion, and self-evolution capabilities.
@9hills: After trying many Agent Memory implementations, I found only two that are somewhat useful: 1. Hermes-style strictly length-limited entry-level memory and session recall, used to address personal assistant memory needs. But this has nothing to do with coding. 2. Skills precipitated from trajectories and skill evolution...
The author shares insights after trying various Agent Memory implementations, concluding that only strictly length-limited entry-level memory (like Hermes) and skill evolution based on trajectory precipitation are somewhat useful, while other graph-based or card-based methods are ineffective.
@wquguru: https://x.com/wquguru/status/2069641926752780384
This article comprehensively reviews the complete architectural layering of AI Agent Memory as of mid-2026, including rule files, persistent profiles, historical recall, and evidence chains. It explains the storage methods, loading timings, and governance principles of different memory layers, emphasizing the key role of memory in helping agents achieve cross-session compounding work.