# MemOS Comparison & Greenfield Analysis

## Overview

This document records our analysis of [MemOS](https://github.com/MemTensor/MemOS) (MemTensor, Apache 2.0) against Coda's `@coda/memory` package and the server-side `MemoryService` integration. MemOS is a "Memory Operating System" for LLMs and AI agents that treats memory as a first-class resource managed through a three-layer OS-inspired architecture. The core innovation is **MemCube** — a unified abstraction that encapsulates heterogeneous memory types (plaintext, activation, parametric) with standardized metadata, governance, and lifecycle management.

We evaluated MemOS to identify transferable techniques and assess our memory architecture against MemOS's more ambitious design, as we did with [Stash](stash-comparison.md) (agent memory), [LightRAG](../search/lightrag-comparison.md) (retrieval), and the other [search comparisons](../search/).

---

## How MemOS works

MemOS is organized into three architectural layers, modeled after a traditional operating system's resource management.

### Three-layer architecture

**1. Interface Layer** — parses natural-language requests, identifies memory intents, and translates them into structured memory operation chains via **MemReader**. Invokes standardized Memory APIs (Provenance, Update, LogQuery).

**2. Operation Layer** — the central controller:

| Component        | Role                                                                                                                                     |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **MemScheduler** | Asynchronous background scheduler for storage, indexing, and organization. Pluggable strategies (LRU, semantic similarity, label-based). |
| **MemLifecycle** | State machine managing memory stages: Generated → Activated → Merged → Archived → Expired.                                               |
| **MemOperator**  | Memory organization, search, and transformation operations.                                                                              |
| **MemChat**      | Orchestrates the memory-augmented dialogue loop (retrieve → generate → store).                                                           |

**3. Infrastructure Layer** — foundational services:

| Component               | Role                                                                              |
| ----------------------- | --------------------------------------------------------------------------------- |
| **MemVault**            | Unified access across heterogeneous storage backends (Neo4j, Qdrant, SQLite, S3). |
| **MemGovernance**       | Access permissions, lifecycle policies, compliance tags, audit trails.            |
| **MemStore**            | Publish-subscribe for cross-agent memory sharing.                                 |
| **MemLoader/MemDumper** | Structured memory migration across platforms.                                     |
| **MemFeedback**         | Natural-language memory correction engine.                                        |

### MemCube — the core abstraction

MemCube is the minimal memory unit. It encapsulates:

- **Descriptive metadata**: timestamps, origin signatures, semantic types.
- **Governance attributes**: access permissions, TTL, frequency-based decay, compliance tags.
- **Behavioral indicators**: usage patterns (frequency, relevance) enabling automatic memory transformation.
- **Memory payload**: one of three types — plaintext, activation states, or parameter deltas.

MemCubes support transformation pathways: plaintext can be encoded into model parameters (via fine-tuning), and parametric knowledge can be externalized to plaintext (for sharing).

### Memory types

MemOS defines three core memory substrates:

| Type                  | Description                                                            | Coda analog                                       |
| --------------------- | ---------------------------------------------------------------------- | ------------------------------------------------- |
| **Parametric memory** | Knowledge encoded in model weights (LoRA, fine-tuning)                 | None — Coda uses a managed model (Bedrock Claude) |
| **Activation memory** | Transient cognitive states — hidden activations, KV-caches             | None — delegated to Bedrock                       |
| **Plaintext memory**  | Explicit, editable knowledge: documents, tool traces, user preferences | `Observation` + `Fact` entities                   |

Within plaintext memory, MemOS further subdivides into:

- **Semantic memory**: general facts and concepts (e.g., "royalties are paid quarterly")
- **Episodic memory**: specific experiences with temporal context (e.g., "user ran query X on Jan 15")
- **Procedural memory**: how to perform tasks (e.g., "to check royalties, first search the schema, then query Snowflake")

### Consolidation & lifecycle

MemOS uses an LLM-dependent consolidation pipeline. The MemScheduler processes memories asynchronously, the MemLifecycle state machine manages transitions (Generated → Activated → Merged → Archived → Expired), and the system supports:

- Task auto-summarization into structured, reusable skills
- Automatic deduplication without manual intervention
- Skill evolution — skills improve when new tasks reveal better approaches
- Cross-task skill reuse (claimed 35.24% token savings in benchmarks)
- Version freezing for temporal consistency and auditability

### Retrieval

MemOS combines FTS5 (full-text search) with vector search for hybrid retrieval. MemScheduler dynamically selects memory type (parametric, activation, or plaintext) based on context. Retrieval supports multi-agent memory isolation with controlled sharing.

### Storage backends

- **Neo4j**: graph database for entity relationships
- **Qdrant**: vector database for semantic similarity search
- **Redis Streams**: scheduling and async task management (v2.0)
- **SQLite + FTS5**: lightweight local deployment
- **S3 / Filesystem**: cloud and file-based storage

---

## How our system works

Coda's `@coda/memory` package (`packages/memory/`) provides cross-session learning through a two-stage pipeline: raw observations are consolidated into durable facts with confidence decay, then facts are injected into the system prompt at session start.

### Architecture

```
Tool Execution
  │
  ▼
emitMemoryForToolExecution()    ← fire-and-forget, best-effort
  ├─ emitToolObservations()      [tool_success / tool_failure]
  ├─ emitEntityObservations()    [account, product, schema table access]
  └─ emitQueryPatternObservations()  [domain keyword matching]
  │
  ▼
ObservationLog.append()          ← sorted set, keyed by timestamp
  │
  ▼
[Next session start]
  │
  ▼
MemoryService.loadMemory(identityId)
  │
  ▼
consolidate()
  1. Read checkpoint (last-consolidated timestamp)
  2. Fetch observations since checkpoint
  3. Deduplicate to fact keys (one reinforcement per fact per session)
  4. Reinforce existing facts or create new (confidence 0.5)
  5. Decay unreinforced facts; delete if below 0.1 threshold
  6. Persist updated facts + new checkpoint
  7. Prune old observations (7-day buffer)
  │
  ▼
formatMemorySection()            ← ~300 token budget
  │
  ▼
System prompt injection          ← memory first, then domain instructions
  │
  ▼
Tool ranking via toolAffinities  ← confidence-weighted boost in searchCatalog()
```

### Data model

Two entity types:

| Entity          | Storage                         | Purpose                                       | TTL                                    |
| --------------- | ------------------------------- | --------------------------------------------- | -------------------------------------- |
| **Observation** | Redis sorted set (by timestamp) | Append-only raw events from tool execution    | 7-day buffer after consolidation prune |
| **Fact**        | Redis hash map (by identity)    | Consolidated beliefs with confidence 0.0--1.0 | Exponential decay; expires below 0.1   |

Four observation types: `tool_success`, `tool_failure`, `entity_access`, `query_pattern`.

Five fact categories: `tool_affinity`, `tool_avoidance`, `entity_frequency`, `domain_preference`, `failure_pattern`.

### Decay strategies

Two pluggable `DecayStrategy` implementations behind a common interface:

| Strategy             | Formula                                   | Half-life         | When to use                          |
| -------------------- | ----------------------------------------- | ----------------- | ------------------------------------ |
| **ExponentialDecay** | `confidence * 0.95 ^ days`                | ~13.5 days        | Default; simple time-based decay     |
| **AdaptiveDecay**    | `confidence * 0.95 ^ (days / easeFactor)` | ~17.5--33.75 days | SM-2 inspired; per-fact ease factors |

### System prompt injection

`formatMemorySection()` ranks facts by `confidence * reinforcementCount`, groups by display category (Tool preferences, Frequent entities, Domain focus, Known issues), and assembles markdown under a "What you know about this user" header. Budget: ~300 tokens. Returns empty string if no facts pass the filter.

### Tool affinity integration

`extractToolAffinities()` produces a `Map<string, number>` from `tool_affinity` (positive) and `tool_avoidance` (negative) facts. Consumed by `searchCatalog()` as a tiebreaker boost (max +/-2 points).

---

## Side-by-side comparison

| Aspect                     | MemOS                                                              | Coda `@coda/memory`                                                         |
| -------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| **Problem**                | General-purpose memory OS for any LLM/agent                        | Cross-session learning for a domain-specific AI agent                       |
| **Architecture**           | Three-layer OS metaphor (interface, operation, infrastructure)     | Two-stage pipeline (observations → facts → prompt injection)                |
| **Memory types**           | Parametric, activation, plaintext (semantic/episodic/procedural)   | Plaintext only: observations and facts                                      |
| **Core abstraction**       | MemCube — unified metadata envelope for heterogeneous memory       | `Observation` + `Fact` — typed event → consolidated belief                  |
| **Consolidation**          | LLM-dependent: entity extraction, summarization, skill synthesis   | Deterministic: counting, averaging, decaying. Zero LLM calls                |
| **Decay model**            | Configurable TTL, frequency-based decay, policy-driven expiry      | Exponential or SM-2 adaptive decay with pluggable `DecayStrategy` interface |
| **Retrieval**              | Hybrid: FTS5 + vector semantic search                              | None — facts are loaded in bulk at session start, not searched              |
| **Storage backends**       | Neo4j, Qdrant, SQLite, S3, Redis Streams                           | Redis (sorted sets + hash maps), in-memory fallback                         |
| **Graph support**          | Neo4j for entity relationships                                     | None — no entity relationship graph                                         |
| **Multi-agent support**    | Native: memory isolation + controlled sharing via MemStore pub/sub | None — single agent per tenant                                              |
| **Multi-tenant isolation** | MemCube governance attributes + namespace-based isolation          | `identityId`-keyed storage; SHA256-hashed identity in Redis keys            |
| **Memory correction**      | MemFeedback: natural-language correction engine                    | None — users cannot view, edit, or delete their memory                      |
| **Skill evolution**        | Auto-summarization → procedural memory → cross-task reuse          | None — no procedural memory or skill abstraction                            |
| **Knowledge graph**        | Neo4j entity relationships with structured queries                 | None                                                                        |
| **Version control**        | Rollback, freezing, audit trails                                   | None — facts are mutable, no history                                        |
| **Prompt integration**     | MemChat dialogue loop (retrieve → generate → store)                | `formatMemorySection()` prepends ~300 tokens to system prompt               |
| **LLM dependency**         | Required for consolidation, entity extraction, skill synthesis     | Zero — all processing is deterministic aggregation                          |
| **Latency**                | ~50-200ms (DB queries + embedding)                                 | <100ms (in-memory stores, 500ms timeout with empty fallback)                |
| **Indexing cost**          | High (LLM calls per consolidation + embedding)                     | Zero (pure aggregation)                                                     |
| **Deployment**             | Docker Compose (PostgreSQL/Neo4j/Qdrant + Python service)          | In-process TypeScript (no additional services)                              |
| **Code footprint**         | ~10K+ LoC Python                                                   | ~600 LoC TypeScript (package) + ~300 LoC server integration                 |
| **Access control**         | MemGovernance: permissions, lifecycle policies, compliance tags    | `identityId` scoping only                                                   |
| **Observability**          | Audit trails, MemGovernance logging                                | Fire-and-forget writes; errors silently swallowed (best-effort)             |
| **Maturity**               | Active research project; v2.0 "Stardust" (Dec 2024); arXiv papers  | Production-deployed; ~900 LoC with comprehensive test suite                 |

---

## Where MemOS excels

### 1. Memory type richness

MemOS's three-substrate model (parametric, activation, plaintext) with further plaintext subdivision (semantic, episodic, procedural) provides a principled taxonomy for different kinds of knowledge. Our system has a flat two-tier model: observations (raw events) and facts (beliefs). We have no representation for procedural memory ("how to accomplish X"), semantic memory ("general facts about the domain"), or anything beyond behavioral statistics.

This matters because our current fact categories (`tool_affinity`, `entity_frequency`, `domain_preference`) capture _what_ the user does but not _how_ they do it or _why_. A user who always follows the pattern "search schema → preview data → build aggregation → export CSV" has a procedural workflow that our system cannot represent.

### 2. Knowledge graph integration

MemOS uses Neo4j to store entity relationships — who relates to what, and how. This enables structured queries across memory ("what does the user know about contracts related to label X?"). Our system stores entity access frequency but not entity relationships. We know the user accesses Account A and Table B frequently, but we don't know that Account A _owns_ Table B or that Table B contains revenue data for Account A.

### 3. Memory correction and user agency

MemFeedback allows users to correct memories via natural language ("I no longer work with label X" or "delete what you know about my Snowflake queries"). Our system provides no user visibility into or control over memory. Users cannot see what the agent remembers, correct inaccuracies, or request deletion. This is both a UX gap and a compliance concern (GDPR right to erasure).

### 4. Cross-agent memory sharing

MemStore enables controlled memory sharing across multiple agents via pub/sub. Our system is single-agent: memory is strictly per-identity with no sharing mechanism. If Coda evolves to support multiple specialized agents (e.g., a search agent and a query agent), MemOS's sharing model becomes relevant.

### 5. Skill evolution

MemOS's procedural memory system can summarize successful task completions into reusable "skills" that improve over time. If the agent successfully resolves "how do I check royalty payments for Q3?" across multiple sessions, MemOS would distill this into a procedural skill: "1. Search schema for royalty tables 2. Query STATEMENT_PERIOD for date range 3. Join with CONTRACT for account context." Our system has no mechanism for this kind of knowledge distillation.

---

## Where our system excels

### 1. Zero LLM dependency

Our consolidation pipeline is pure aggregation: counting, averaging, decaying. No LLM calls, no embedding, no external API dependencies. MemOS requires LLM calls for entity extraction, summarization, skill synthesis, and embedding — every consolidation run costs money and introduces non-determinism. For a system where memory is best-effort enhancement (not core functionality), deterministic zero-cost consolidation is the right trade-off.

### 2. Latency and graceful degradation

`MemoryService.loadMemory()` races consolidation against a 500ms timeout and returns empty results on any failure. Memory is strictly additive — if it's slow or broken, the agent falls back to stateless behavior with no degradation in core functionality. MemOS's deeper integration means memory failures have broader blast radius.

### 3. Simplicity and maintainability

The entire memory system is ~900 lines of TypeScript across the `@coda/memory` package and server integration. The data model has two entities (`Observation`, `Fact`). The consolidation algorithm is 90 lines. The decay strategies are 20-40 lines each. This is a system that any developer can understand in 30 minutes.

MemOS has a significantly larger surface area: three architectural layers, five infrastructure components, Neo4j + Qdrant + SQLite backends, LLM-dependent consolidation, a state machine lifecycle model, pub/sub sharing, and a feedback engine. The conceptual weight is high even before code complexity.

### 4. Interface-driven extensibility

Our system uses clean interfaces (`ObservationLog`, `FactRepository`, `CheckpointStore`, `DecayStrategy`) with constructor dependency injection. Swapping storage backends (Redis → Aurora), decay strategies (exponential → adaptive), or adding observation types requires no structural changes. MemOS achieves extensibility through its MemVault abstraction, but the overall system has more moving parts to coordinate.

### 5. Domain-specific design

Our fact categories (`tool_affinity`, `tool_avoidance`, `entity_frequency`, `domain_preference`, `failure_pattern`) are purpose-built for an AI agent that uses tools to query structured data. The system prompt formatter knows exactly how to present these categories to a Claude model in ~300 tokens. MemOS is general-purpose — its memory categories are not tailored to any specific agent type, which means the consumer bears the cost of mapping generic memory to domain-specific prompts.

### 6. Budget-constrained prompt injection

`formatMemorySection()` ranks facts by signal strength (`confidence * reinforcementCount`), groups by category, and truncates to a 300-token budget. This prevents memory from consuming unbounded context window space. MemOS's retrieval returns variable-length results that the consumer must manage — there is no built-in prompt budget mechanism.

---

## Transferable techniques evaluated

### Adopted: None currently

MemOS and Coda's memory system operate at fundamentally different scales of ambition. MemOS is a general-purpose memory OS for arbitrary LLM agents; Coda's memory is a lightweight, domain-specific learning layer for a single agent. The techniques below were evaluated for future applicability.

### Future applicability: Procedural memory for workflow patterns

**MemOS pattern**: Successful task completions are summarized into structured "skills" — step sequences with pitfall warnings and verification checks. Skills improve when new tasks reveal better approaches.

**Assessment**: Our `workflow_pattern` fact category was designed in the original design exploration (see [agent-memory-exploration.md](../../archive/agent-memory-exploration.md)) but not yet implemented. Users who follow consistent patterns (search → preview → query → export) would benefit from procedural memory that guides the agent through established workflows.

**Where this applies**: The agent's system prompt. Instead of generic tool descriptions, the agent could receive user-specific procedural guidance: "This user typically searches Snowflake schema first, then builds aggregation queries. Suggest this workflow proactively."

**Implementation direction**: We would not adopt MemOS's LLM-dependent skill synthesis. Instead, procedural patterns could be derived from tool execution sequences — if `search_snowflake_schema` is consistently followed by `query_snowflake` with >80% success rate, emit a `workflow_pattern` observation. Consolidation would aggregate these into a workflow fact without LLM calls.

**Verdict**: Deferred. The current observation types (`tool_success`, `tool_failure`, `entity_access`, `query_pattern`) provide meaningful signal without workflow analysis. Revisit when usage data shows consistent multi-step patterns that the agent fails to anticipate.

### Future applicability: Memory correction and user visibility

**MemOS pattern**: MemFeedback allows natural-language correction ("forget X", "I no longer work with Y"). Users can inspect, edit, and delete memories.

**Assessment**: Our system has no user-facing memory interface. This was flagged as an open question in the original design exploration ("Should users be able to see/edit/delete their memory?"). For compliance (GDPR right to erasure) and user trust, this becomes important at scale.

**Implementation direction**: A `/memory` API endpoint that returns the user's active facts and supports deletion by fact ID. No natural-language correction — a simple CRUD API is sufficient for our use case.

**Verdict**: Deferred until the privacy/compliance review. The implementation is straightforward (~100 lines for the API endpoint + `FactRepository.delete()` already exists) but requires product decisions about opt-in vs. opt-out behavior.

### Future applicability: Entity relationship graph

**MemOS pattern**: Neo4j stores entity relationships, enabling structured queries across memory ("what entities are related to X?").

**Assessment**: Our `entity_frequency` facts track access frequency but not relationships. We know the user accesses Account A and Table B, but don't know they're related. However, the search service (`apps/search/`) already maintains a schema graph with structurally-derived relationships (type→field, FK inference). Entity relationships in memory would duplicate what the search graph already provides.

**Verdict**: Rejected. Entity relationships belong in the search service's schema graph, not in the memory layer. If memory needs relationship context, it should query the search service rather than maintaining a parallel graph.

### Rejected: Multi-substrate memory model

**MemOS pattern**: Three memory substrates (parametric, activation, plaintext) with transformation pathways between them.

**Assessment**: Coda uses a managed LLM (AWS Bedrock Claude). We cannot access model weights (parametric memory) or KV-caches (activation memory). The only substrate we can control is plaintext — which is exactly what `Observation` + `Fact` provide. The multi-substrate model is architecturally interesting but inapplicable when the model is a black-box API.

**Verdict**: Rejected. Requires model-level access that Bedrock does not provide.

### Rejected: LLM-dependent consolidation

**MemOS pattern**: LLM calls during consolidation for entity extraction, summarization, and skill synthesis.

**Assessment**: Our design principle is zero LLM calls in the memory layer. Consolidation must be deterministic and cheap. LLM-dependent consolidation adds cost ($), latency (100ms+ per call), non-determinism (different outputs per run), and an external dependency. Our deterministic aggregation (counting, averaging, decaying) provides sufficient signal for tool affinity and entity frequency without these costs.

**Verdict**: Rejected. Same rationale as in the [Stash comparison](stash-comparison.md#4-llm-dependent-consolidation-is-architecturally-incompatible).

### Rejected: Multi-agent memory sharing

**MemOS pattern**: MemStore pub/sub for cross-agent memory sharing.

**Assessment**: Coda is a single-agent system. There is no second agent to share memory with. If the architecture evolves toward multiple specialized agents (e.g., separating the search agent from the query agent), this becomes relevant — but that's a speculative future, not a current need.

**Verdict**: Rejected. Revisit if the agent architecture becomes multi-agent.

### Rejected: Neo4j + Qdrant storage stack

**MemOS pattern**: Neo4j for graph queries, Qdrant for semantic search, Redis Streams for scheduling.

**Assessment**: Our memory system stores dozens to low hundreds of facts per tenant, loaded in bulk at session start. The entire fact set for a user fits in a single Redis hash. Graph queries and vector search are solutions for large-scale, query-heavy memory systems — not for a system that loads ~50 facts into ~300 tokens of prompt.

**Verdict**: Rejected. Redis is sufficient. Adding Neo4j + Qdrant would introduce two new infrastructure dependencies for a problem that doesn't exist at our scale.

---

## Greenfield assessment: if we were building memory today

### What we would keep

1. **Observation → Fact two-stage model.** The separation of raw events (append-only, fire-and-forget) from consolidated beliefs (with confidence and decay) is the right abstraction. MemOS's more complex lifecycle (Generated → Activated → Merged → Archived → Expired) adds stages that don't earn their complexity for our use case.

2. **Zero LLM consolidation.** Deterministic aggregation is the right choice for a best-effort enhancement layer. The cost/latency/non-determinism trade-off of LLM-dependent consolidation is not justified.

3. **Pluggable `DecayStrategy` interface.** Clean separation between the consolidation algorithm and the decay model. The `ExponentialDecay` / `AdaptiveDecay` choice provides meaningful flexibility without over-engineering.

4. **Budget-constrained prompt injection.** The 300-token budget with ranked truncation is the right approach. Memory should enhance, not dominate, the system prompt.

5. **Fire-and-forget observation emission.** Memory writes must not block the critical path (tool execution → LLM response). The `emitObservation()` pattern with swallowed errors and `drain()` on shutdown is correct.

6. **`identityId`-scoped isolation.** Memory is per-user, never cross-tenant. This is a hard requirement for our multi-tenant environment.

### What we would change

1. **Add a `workflow_pattern` observation type and fact category.** The original design exploration included `workflow_pattern` but it was cut from the initial implementation. MemOS's procedural memory concept validates the gap: we track _what_ tools users use but not _how_ they chain them. Tool execution sequences (search → query → export) should be observable and consolidatable.

2. **Add a memory visibility API.** MemOS's MemFeedback is over-engineered for our needs, but the core insight — users should be able to see and delete what the agent remembers — is correct. A simple REST endpoint returning active facts and supporting deletion by ID would close the compliance and trust gap.

3. **Add observation type extensibility.** Our current `ObservationType` is a fixed union of four string literals. Adding a new observation type requires modifying the type definition, the `observationToFactKey()` mapping, and the emitter. MemOS's MemCube abstraction handles arbitrary memory types through metadata. We should consider a registry pattern where observation types and their fact-key mappings are registered at initialization, not hard-coded.

4. **Add fact versioning (lightweight).** MemOS has full version control with rollback. We don't need that — but we should track when a fact's content changed, not just when it was last reinforced. Currently, a fact's `content` field is overwritten on each reinforcement with the latest observation's display text. If the display text changes (e.g., entity name updated), we lose the history.

5. **Move from in-memory to real Redis.** The current deployment uses `MemorySortedStore` and `MemoryHashStore` (in-memory AVL trees and Maps) behind the `RedisObservationLog` / `RedisFactRepository` interfaces. This means memory resets on every server restart. The architecture is correct (interfaces allow swapping), but the TODO to wire real Redis sorted sets should be prioritized for memory to provide actual cross-session value.

### What we would not adopt from MemOS

1. **The OS metaphor.** MemOS's three-layer architecture (interface, operation, infrastructure) maps cleanly to OS concepts but introduces significant conceptual overhead for what is, functionally, a store-consolidate-retrieve pipeline. Our two-stage model is simpler and more honest about what the system actually does.

2. **MemCube as universal envelope.** A unified abstraction for parametric + activation + plaintext memory is elegant in theory but irrelevant when only one substrate is accessible. Our typed `Observation` / `Fact` interfaces are more specific and self-documenting.

3. **Graph + vector hybrid retrieval for memory.** Our facts are loaded in bulk (~50 per user, ~300 tokens), not searched. Adding retrieval infrastructure (vector DB, graph DB) solves a problem that doesn't exist at our scale. If fact volume grows to thousands per user, hybrid retrieval becomes relevant — but at that point we should question whether we're consolidating aggressively enough.

4. **Multi-agent sharing infrastructure.** MemStore pub/sub adds infrastructure for a multi-agent world we don't inhabit. If that changes, the sharing mechanism should be designed around the specific agents and their trust boundaries, not adopted wholesale from a generic framework.

---

## Relationship to prior comparisons

| System                                          | Layer     | Relationship to Coda's memory                                                                 |
| ----------------------------------------------- | --------- | --------------------------------------------------------------------------------------------- |
| [Stash](stash-comparison.md)                    | Memory    | Agent memory layer — inspired `@coda/memory` design (observation → fact consolidation, decay) |
| **MemOS**                                       | Memory OS | Full memory operating system — validates our design choices, identifies future gaps           |
| [LightRAG](../search/lightrag-comparison.md)    | Retrieval | Graph-enhanced RAG — search layer, orthogonal to memory                                       |
| [LLM Wiki](../knowledge/llm-wiki-comparison.md) | Knowledge | Pre-compiled knowledge — addresses knowledge accumulation, not agent learning                 |

Stash was the direct inspiration for `@coda/memory` — we adopted the observation → fact consolidation pattern with deterministic (non-LLM) processing. MemOS represents the maximalist version of the same idea: what if memory had the full resource management infrastructure of an operating system? The comparison validates that our lean implementation covers the high-value scenarios (tool affinity, entity frequency, domain preference) while identifying specific gaps (procedural memory, user visibility, fact versioning) worth addressing in future iterations.

---

## Benchmark comparison

### LOCOMO benchmark (MemOS)

MemOS reports first-place results on the LOCOMO (Long-Context Conversation Memory) benchmark:

- Single-hop reasoning: +5% relative improvement over baselines
- Multi-hop reasoning: +7% relative improvement
- Temporal reasoning: +11% relative improvement
- P95 latency: 91% reduction compared to full-context baselines
- Token consumption: ~7,000 tokens per retrieval call

### Coda memory (no formal benchmark)

Coda's memory system has no external benchmark. Effectiveness is measured through:

- Tool affinity accuracy: does the boosted tool match user preference?
- Prompt section token efficiency: facts within ~300 token budget?
- Consolidation latency: under 500ms timeout threshold?
- Graceful degradation: does the agent function normally when memory fails?

These are operational metrics, not retrieval quality metrics. A direct comparison with LOCOMO is not meaningful — MemOS is solving a retrieval problem (find the right memory for this query), while Coda loads all facts and lets the LLM decide relevance.

---

## Project maturity assessment

| Factor             | MemOS                                                                 | Coda `@coda/memory`                                       |
| ------------------ | --------------------------------------------------------------------- | --------------------------------------------------------- |
| **Age**            | Active since 2024; v2.0 "Stardust" released Dec 2024                  | Implemented 2026; ~3 months in production                 |
| **Maintainership** | MemTensor team (multi-person); active GitHub presence                 | Solo team; embedded in monorepo                           |
| **Stars**          | ~7K GitHub stars; active research community                           | Internal project                                          |
| **Publications**   | Two arXiv papers (2507.03724, 2505.22101)                             | Internal architecture docs                                |
| **Code quality**   | Large Python codebase with plugin architecture                        | ~900 LoC TypeScript with comprehensive tests              |
| **Test coverage**  | Not assessed                                                          | Unit + integration tests for consolidation, decay, stores |
| **Dependencies**   | Neo4j, Qdrant, SQLite, Redis Streams, OpenAI-compatible embedding API | Redis (in-memory fallback); zero external dependencies    |
| **Documentation**  | Official docs site, API guides, conceptual overviews                  | Architecture doc + design exploration + inline JSDoc      |

MemOS is a more ambitious project with stronger academic credentials. Coda's memory is a production-deployed, purpose-built system with a deliberately minimal footprint. The maturity comparison is apples-to-oranges: MemOS is a platform; `@coda/memory` is a feature.

---

## Summary

MemOS is a comprehensive memory operating system that treats memory as a first-class resource with OS-inspired lifecycle management, multi-backend storage, governance, and cross-agent sharing. Its MemCube abstraction provides a principled model for heterogeneous memory types with standardized metadata and transformation pathways.

Coda's `@coda/memory` is a lightweight, domain-specific memory layer that consolidates raw tool-execution observations into facts with confidence decay, injecting personalized context into the system prompt at session start. It prioritizes simplicity, zero LLM cost, and graceful degradation over architectural ambition.

The two systems operate at fundamentally different scales: MemOS is a general-purpose platform for any agent system; `@coda/memory` is a 900-line feature for one specific agent. MemOS validates several of our design choices (observation-to-fact consolidation, confidence decay, prompt injection) while identifying legitimate gaps (procedural memory, user visibility, workflow patterns) that merit future work.

**Bottom line**: Our architecture is sound for its scope. The lean implementation was the right starting point — it ships, it works, and it degrades gracefully. The gaps MemOS highlights (procedural memory, memory correction, workflow patterns) should be addressed incrementally as usage data reveals which patterns matter most, not by adopting MemOS's heavier infrastructure. The most actionable next steps are: (1) wire real Redis to persist memory across restarts, (2) add a user-facing memory visibility endpoint, and (3) implement `workflow_pattern` observations for tool-chain tracking.

---

## References

- MemTensor: [MemOS](https://github.com/MemTensor/MemOS) (Apache 2.0)
- MemOS paper: [arXiv 2507.03724](https://arxiv.org/abs/2507.03724) — "MemOS: A Memory OS for AI System"
- MemOS short paper: [arXiv 2505.22101](https://arxiv.org/abs/2505.22101) — "MemOS: An Operating System for Memory-Augmented Generation"
- Stash comparison: [stash-comparison.md](stash-comparison.md)
- Agent memory design exploration: [agent-memory-exploration.md](../../archive/agent-memory-exploration.md)
- Agent memory architecture: [agent-memory.md](../../../architecture/agent-memory.md)
- Memory package: `packages/memory/src/`
- Memory service integration: `apps/server/src/ai/memory/`
