# MNEMOSYNE: A Plugin-Layered Enhancement Suite for Personal-Agent Memory Systems

**Paper:** J14 — MNEMOSYNE
**Version:** 1.0
**Date:** 2026-04-16
**Author:** Oscar Serra
**Plugin:** tinkerclaw-memory-enhancements (v0.1)
**Status:** Production scaffold; hippocampus index + compaction capture live; task scoring + contradiction gate scaffolded

---

## Abstract

Personal AI assistants that accumulate months of memory face four gaps that upstream retrieval systems do not close: constant-time concept lookup degrades to linear search at scale, retrieval scoring ignores the agent's current task, memory writes can silently introduce contradictions, and context compaction permanently destroys information that was used once but never queried again. We present **MNEMOSYNE**, a plugin-layered enhancement suite that addresses all four gaps without modifying the upstream memory-core codebase. MNEMOSYNE registers four hooks — `retrieval_pre`, `before_message_write`, `before_compaction`, and `after_compaction` — on top of OpenClaw's 50k LOC markdown-first memory system. The hippocampus concept index and compaction-aware capture are deployed in production (v0.1); task-conditioned retrieval scoring and the contradiction gate are scaffolded for v0.2. The plugin architecture permits marketplace distribution as a single installable unit.

---

## 1. Introduction

### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence

Upstream memory-core was designed as a general-purpose memory system — part personal assistant, part enterprise wiki. It provides hybrid FTS5 full-text search, vector embeddings with cosine similarity, Maximal Marginal Relevance (MMR) deduplication, and temporal decay scoring. For an enterprise wiki where queries are well-formed and contexts are stable, this suite is sufficient.

A personal assistant diverges in three structural ways. First, queries are ambiguous: "what was that thing about the cron job?" contains no entity that FTS5 can match. Second, the agent context-switches constantly — from debugging cron tasks to drafting emails to reviewing code — and retrieval scoring should reflect this. Third, the agent writes its own memories autonomously through nightly consolidation cycles (the "dreaming" phase described in J5 [Serra, 2026e]), and those writes can contradict earlier facts without any human review gate.

These divergences motivated a layered enhancement approach rather than a fork of memory-core.

### 1.2 Why a Plugin, Not a Fork

OpenClaw's plugin system provides four properties that make it the correct integration point:

1. **Failure isolation.** A crash in MNEMOSYNE does not take down memory-core. The hook runner catches exceptions and logs them; upstream retrieval continues unimpaired.
2. **Upgrade independence.** Upstream memory-core ships weekly updates. A plugin does not create merge conflicts.
3. **Distribution.** A single `tinkerclaw-memory-enhancements` package can be installed via ClawHub, OpenClaw's plugin marketplace, without users needing to maintain a fork.
4. **Composability.** Each of the four features can be independently enabled or disabled via plugin configuration.

### 1.3 Contributions

1. An O(1) concept index that short-circuits hybrid retrieval for known concepts (Feature 1).
2. A task-conditioned score modifier that biases retrieval toward the agent's current work (Feature 2).
3. A contradiction gate that intercepts memory writes before promotion to durable storage (Feature 3).
4. A compaction-aware capture pass that snapshots context before it is evicted (Feature 4).
5. A unified plugin architecture that delivers all four as a single distributable unit.

---

## 2. Background and Related Work

### 2.1 The Serra Paper Series

MNEMOSYNE builds directly on four prior papers in this series:

**J1 ENGRAM** [Serra, 2026a] defines the event-sourced memory architecture with pointer-based compaction. ENGRAM's write model — where the context window is treated as a cache over a durable store — is the substrate on which MNEMOSYNE's compaction capture operates. When ENGRAM evicts context, it inserts pointer markers; MNEMOSYNE intercepts the eviction to capture content that pointers alone cannot recover.

**J2 HIPPOCAMPUS** [Serra, 2026b] introduces the pre-computed concept-to-memory-address index that enables O(1) retrieval. HIPPOCAMPUS v5.0 defines the anchor vocabulary, importance scoring, and CORF (Contextual Ownership Retrieval Failure) taxonomy. MNEMOSYNE's Feature 1 is the production plugin implementation of the HIPPOCAMPUS architecture described theoretically in J2.

**J4 CORTEX** [Serra, 2026c] addresses identity persistence and consistency preservation across sessions. CORTEX's PersonaState structure defines what the agent "believes" to be true about itself; MNEMOSYNE's contradiction gate (Feature 3) protects this structure from silent corruption.

**J5 Prompt Cerebellum** [Serra, 2026e] describes the nightly reflection and consolidation cycles ("dreaming") that produce autonomous memory writes. These are precisely the writes that Feature 3 gates and Feature 4 captures.

### 2.2 Upstream Memory-Core Architecture

OpenClaw's memory-core (approximately 50,000 lines of TypeScript) implements a markdown-first memory system with five retrieval stages:

1. **FTS5 full-text search** over a SQLite corpus, currently at ~878K events in production.
2. **Vector embedding similarity** using cosine distance against pre-computed chunk embeddings.
3. **MMR deduplication** to prevent redundant chunks from consuming retrieval budget.
4. **Temporal decay** that exponentially down-weights older memories (half-life configurable, default 30 days).
5. **Relevance threshold** that filters chunks below a minimum combined score.

The retrieval pipeline is extensible via hooks registered at plugin load time. Memory-core exposes `retrieval_pre` (modify query or inject candidates before search), `before_message_write` (intercept writes to durable storage), `before_compaction` (observe context about to be evicted), and `after_compaction` (react to completed evictions). MNEMOSYNE uses all four.

### 2.3 Related Systems

**Mem0** [MemoryOS, 2024] builds multi-level memory (short-term, episodic, long-term) but does not address task-conditioned retrieval or write-time contradiction checking. **MemGPT** [Packer et al., 2023] introduces virtual context paging but operates at the context-window level rather than the retrieval-scoring level. **A-MEM** [Xu et al., 2025] gives agents control over memory formation strategies; MNEMOSYNE complements this by adding retrieval-time and write-time gates that A-MEM does not address.

No existing system combines O(1) concept lookup, task-conditioned scoring, write-time contradiction gating, and compaction-time capture in a single plugin-layered architecture.

---

## 3. Architecture

### 3.1 Plugin-Layered Design

MNEMOSYNE is a single OpenClaw plugin with ID `tinkerclaw-memory-enhancements`. It registers four hooks at load time:

```typescript
/**
 * FORK: MNEMOSYNE plugin entry point.
 * Registers four hooks on upstream memory-core's retrieval
 * and write pipelines. No upstream source modification required.
 */
export function activate(api: PluginAPI): void {
  api.hooks.register('retrieval_pre', conceptIndexLookup);
  api.hooks.register('retrieval_pre', taskConditionedScoring);
  api.hooks.register('before_message_write', contradictionGate);
  api.hooks.register('before_compaction', compactionCapture);
}
```

Hook execution order is deterministic: hooks registered first run first. The concept index runs before task-conditioned scoring so that O(1) lookups can short-circuit the pipeline entirely — if the concept index returns a high-confidence result, the full hybrid search is skipped.

### 3.2 Hook Surface

| Hook | Timing | Receives | Returns |
|------|--------|----------|---------|
| `retrieval_pre` | Before hybrid FTS+vector search | Query string, task descriptor, retrieval config | Modified query, injected candidates, or `skip_search` signal |
| `before_message_write` | Before promotion to MEMORY.md | Candidate chunk, existing facts | `allow`, `warn`, or `block` |
| `before_compaction` | Before context eviction | Messages about to be dropped | Captured chunks (written to corpus) |
| `after_compaction` | After eviction completes | Eviction metadata | Void (used for bookkeeping) |

### 3.3 Failure Isolation

Each hook is wrapped in a try-catch at the memory-core level. If MNEMOSYNE throws, the exception is logged to the plugin's own log file (`<agent-logs>/tinkerclaw-memory-enhancements.log`) and the upstream pipeline continues as if the hook were not registered. This means:

- A bug in the concept index does not prevent hybrid search from running.
- A crash in the contradiction gate does not block memory writes.
- A failure in compaction capture does not prevent compaction.

### 3.4 Storage Isolation

MNEMOSYNE stores its data separately from memory-core:

- **Concept index:** `<agent-data>/mnemosyne/anchors.json`
- **Capture corpus:** `<agent-data>/mnemosyne/captured/` (one `.md` file per capture event)
- **Contradiction log:** `<agent-data>/mnemosyne/contradictions.jsonl`
- **Task descriptor cache:** In-memory only (ephemeral per session)

This separation ensures that uninstalling the plugin leaves memory-core's data untouched.

---

## 4. Feature 1: Hippocampus O(1) Concept Index

### 4.1 Design

The concept index implements the architecture described in J2 HIPPOCAMPUS [Serra, 2026b] §4 as a production plugin component. The core insight is that a personal assistant's memory corpus contains a finite vocabulary of recurring concepts — project names, people, tools, error classes — and mapping these concepts to their associated memory chunks offline enables constant-time retrieval at query time.

When a user query contains a recognized concept token (e.g., "cron", "invoice-export", "WhatsApp"), the index returns the pre-ranked chunk list directly, bypassing the full FTS5 + vector + MMR pipeline.

### 4.2 Data Structure

```typescript
/**
 * FORK: Hippocampus concept index.
 * Maps concept tokens to their associated memory chunk IDs
 * with importance scoring for retrieval ranking.
 * Persisted to anchors.json, loaded lazily on first query.
 */
type ConceptEntry = {
  chunkIds: Set<string>;
  importance: number;
  lastSeenAtMs: number;
};

const conceptIndex: Map<string, ConceptEntry> = new Map();
```

Each entry stores:
- **chunkIds**: The set of memory chunk identifiers associated with this concept. Chunk IDs are opaque strings assigned by memory-core.
- **importance**: A scalar combining frequency, recency, and distinctiveness (§4.5).
- **lastSeenAtMs**: Unix timestamp of the most recent ingestion event that referenced this concept, used for staleness pruning.

### 4.3 Ingestion

The index is built during nightly consolidation (the "dreaming" phase from J5). For each memory chunk processed during consolidation:

1. **Tokenize** the chunk into candidate concept tokens using whitespace splitting and stop-word removal.
2. **Filter** to tokens that appear in the anchor vocabulary — a curated set of entity names, project identifiers, tool names, and error classes extracted from the agent's operational history.
3. **Update** the concept index: for each surviving token, add the chunk ID to the token's `chunkIds` set and recompute importance.

Incremental updates occur during the session when new memories are written: the `after_compaction` hook triggers a lightweight re-index of newly captured chunks.

### 4.4 Lookup

At query time, the `retrieval_pre` hook tokenizes the incoming query and checks each token against the concept index:

```typescript
function conceptIndexLookup(ctx: RetrievalContext): RetrievalResult | null {
  const tokens = tokenize(ctx.query);
  const matches: ConceptEntry[] = [];

  for (const token of tokens) {
    const entry = conceptIndex.get(token);
    if (entry && entry.importance >= CONFIDENCE_THRESHOLD) {
      matches.push(entry);
    }
  }

  if (matches.length === 0) return null; // fall through to hybrid search

  const chunkIds = unionChunkIds(matches);
  const ranked = rankByImportance(chunkIds, matches);
  return { candidates: ranked.slice(0, ctx.config.maxResults), skipSearch: true };
}
```

When the index returns a result with `skipSearch: true`, memory-core skips the full hybrid pipeline. If no concept matches above the confidence threshold, the hook returns `null` and hybrid search proceeds normally.

### 4.5 Importance Scoring

Importance is computed as a weighted product of three factors:

```
importance(token) = w_f * frequency(token) + w_r * recency(token) + w_d * distinctiveness(token)
```

Where:
- **frequency** = log(1 + count of chunks containing this token), normalized to [0, 1].
- **recency** = exponential decay from `lastSeenAtMs` with a half-life of 14 days.
- **distinctiveness** = inverse document frequency: tokens that appear in fewer chunks score higher. A token appearing in every chunk (e.g., "the") has distinctiveness near zero.

Default weights: `w_f = 0.3`, `w_r = 0.4`, `w_d = 0.3`. Recency is weighted highest because a personal assistant's interests shift over weeks — a project abandoned two months ago should not dominate retrieval.

### 4.6 Pruning

Concepts whose `lastSeenAtMs` is older than 90 days and whose importance has decayed below `PRUNE_THRESHOLD` (default 0.05) are removed during nightly consolidation. This prevents the index from growing unboundedly as the agent's operational vocabulary evolves.

Pruning is conservative: a concept is only removed if both conditions hold. A rarely-seen but highly distinctive concept (e.g., a unique project name) may persist indefinitely because its distinctiveness score keeps importance above the threshold.

### 4.7 Complexity Analysis

| Operation | Hybrid search (upstream) | Concept index (MNEMOSYNE) |
|-----------|-------------------------|---------------------------|
| Query-time retrieval | O(n log n) — FTS5 scan + vector cosine + MMR | O(\|Q\|) — token lookup in Map, where \|Q\| is query token count |
| Index build | N/A | O(n \* \|V\|) — one-time, during nightly consolidation |
| Incremental update | N/A | O(\|V\|) per new chunk |
| Storage | FTS5 index + vector store (~878K events) | anchors.json (~50KB for 2,000 concepts) |

The critical property is that query-time retrieval is **O(1) in corpus size n**. As the memory corpus grows from thousands to hundreds of thousands of chunks, hybrid search degrades (FTS5 scan time grows, vector search requires more comparisons); the concept index remains constant.

### 4.8 Persistence

The index is serialized to `anchors.json` using JSON with `Set` values converted to arrays:

```json
{
  "cron": {
    "chunkIds": ["c_4a2f", "c_891b", "c_3e7d"],
    "importance": 0.72,
    "lastSeenAtMs": 1744675200000
  },
  "whatsapp": {
    "chunkIds": ["c_12ab", "c_56cd"],
    "importance": 0.61,
    "lastSeenAtMs": 1744588800000
  }
}
```

Loading is lazy: the file is read and parsed on the first retrieval query of each session. Subsequent queries use the in-memory Map.

---

## 5. Feature 2: Task-Conditioned Retrieval Scoring

### 5.1 Motivation

Standard retrieval scoring is **query-only**: the score of a memory chunk depends solely on its textual similarity to the query. For a personal assistant that context-switches between tasks throughout the day, this is insufficient.

Consider: Jarvis is debugging a cron failure. The user asks "what did we change last week?" Without task conditioning, the retrieval system returns all changes from last week — code commits, email drafts, configuration edits — ranked by textual similarity to "change" and "last week." With task conditioning, chunks tagged with cron-related metadata are boosted, surfacing the specific cron script modifications that the user implicitly meant.

The phenomenon is well-studied in information retrieval as **query context bias** [Croft et al., 2010], but has not been applied to agent memory systems where the "context" is the agent's current task rather than a user profile.

### 5.2 Task Descriptor

The task descriptor is a lightweight structure extracted from the agent's current session state:

```typescript
type TaskDescriptor = {
  keywords: string[];       // e.g., ["cron", "merge", "guardian"]
  projectId: string | null; // e.g., "tinkerclaw"
  taskType: string | null;  // e.g., "debugging", "writing", "review"
};
```

The descriptor is populated from two sources:
1. **Explicit task markers** — if the agent's session includes a task header (e.g., `## Task: Debug safe-cron-merge.sh`), the keywords and project are extracted directly.
2. **Implicit inference** — if no explicit marker exists, the descriptor is inferred from the last N messages using keyword extraction (TF-IDF over the session window).

### 5.3 Score Modifier

The task-conditioned score modifier is registered as a second `retrieval_pre` hook that runs after the concept index lookup (and only if the concept index did not short-circuit):

```typescript
function taskConditionedScoring(ctx: RetrievalContext): void {
  const task = ctx.taskDescriptor;
  if (!task || task.keywords.length === 0) return; // no task context available

  for (const candidate of ctx.candidates) {
    const taskRelevance = computeTaskRelevance(candidate.metadata, task);
    candidate.score += TASK_WEIGHT * taskRelevance;
  }
}
```

The modifier does not replace existing scores — it adds a weighted bonus. Chunks that are already highly relevant to the query remain highly ranked; the task bias adjusts marginal rankings.

### 5.4 Weight Calibration

The `TASK_WEIGHT` parameter (default 0.3) controls how aggressively task context biases retrieval. At 0.0, the modifier has no effect. At 1.0, task relevance dominates textual similarity.

The default of 0.3 was chosen empirically: high enough to promote task-relevant chunks from page 2 to page 1 of results, low enough that a query about an unrelated topic still returns correct results. Formal calibration against a CORF-annotated benchmark (as proposed in J2 §7) is planned for v0.2.

### 5.5 Interaction with Concept Index

The two `retrieval_pre` hooks interact as follows:

1. If the concept index fires and returns `skipSearch: true`, the task-conditioned modifier never runs. This is correct: O(1) concept lookup already returns the right chunks for well-known concepts, and adding task bias would only degrade a precise result.
2. If the concept index does not fire (no recognized concepts in the query), the task-conditioned modifier runs on the hybrid search candidates. This is where it adds the most value — ambiguous queries where hybrid search returns too many marginally relevant results.

---

## 6. Feature 3: Contradiction-Gate on Writes

### 6.1 Threat Model: Agent Self-Corruption

Autonomous agents that write their own memories face a risk that human-curated knowledge bases do not: **self-corruption through hallucinated or outdated facts**. The threat manifests in three scenarios:

1. **Hallucinated consolidation.** During nightly dreaming (J5), the LLM summarizes the day's events. If the summary includes a hallucinated detail — a wrong date, an incorrect attribution, a confused sequence of events — that hallucination is promoted to durable storage and becomes a "fact" the agent retrieves in future sessions.

2. **Stale override.** The agent learns a new fact ("the meeting was moved to Thursday") but a later consolidation cycle processes an older memory that still says "the meeting is on Wednesday." If the older memory is promoted after the newer one, the durable store now contains a contradiction, and temporal ordering may not resolve it.

3. **Semantic drift.** Over months, repeated summarization introduces gradual semantic shifts. A project described as "experimental" becomes "production" through successive paraphrases, not through any actual status change.

These threats are not hypothetical. The SCF (Self-Contradiction Failure) mode identified in J2 v5.0 [Serra, 2026b] was discovered in production when Jarvis flagged a calendar conflict for a meeting it had already noted as postponed.

### 6.2 Gate Mechanism

The contradiction gate registers on the `before_message_write` hook. When memory-core's dreaming phase prepares to promote a short-term recall to MEMORY.md, the gate intercepts the candidate chunk and performs a targeted contradiction check:

```typescript
async function contradictionGate(ctx: WriteContext): Promise<WriteDecision> {
  const candidate = ctx.chunk;
  const existingFacts = await queryRelatedFacts(candidate);

  if (existingFacts.length === 0) {
    return { action: 'allow' }; // no existing facts to contradict
  }

  const contradictions = detectContradictions(candidate, existingFacts);

  if (contradictions.length === 0) {
    return { action: 'allow' };
  }

  logContradiction(candidate, contradictions);

  return {
    action: config.contradictionMode, // 'warn' or 'block'
    reason: formatContradictionReport(contradictions),
  };
}
```

The `detectContradictions` function uses entity-level comparison: it extracts named entities (dates, names, project identifiers, status labels) from both the candidate and existing facts, then checks for direct conflicts (same entity, different value). This is a conservative approach — it catches explicit contradictions ("meeting on Wednesday" vs "meeting on Thursday") but not subtle semantic drift. Semantic drift detection is deferred to v0.3.

### 6.3 Modes: Warn vs Block

The gate operates in one of two modes, configured per-plugin:

**Warn mode** (default): The contradiction is logged to `contradictions.jsonl` with the candidate chunk, the conflicting existing facts, and a timestamp. The write proceeds. The agent (or its operator) can review the log periodically to identify patterns of self-corruption.

**Block mode**: The write is refused. The candidate chunk is not promoted to MEMORY.md. The blocked write is logged with the same detail as warn mode, plus the `blocked: true` flag. This is the safer mode but risks losing legitimate updates if the contradiction detector produces false positives.

The default is warn mode because the contradiction detector is conservative — blocking on false positives would cause information loss, which is worse than allowing a contradiction that can be manually reviewed.

### 6.4 Relationship to J1 and J4

The contradiction gate sits at the intersection of two architectural concerns:

**J1 ENGRAM's write model** treats memory writes as cache promotions — content moves from the ephemeral context window to durable storage. The contradiction gate adds a validation step to this promotion, analogous to a database constraint check before an INSERT.

**J4 CORTEX's consistency preservation** maintains agent identity across sessions by ensuring the PersonaState structure remains coherent. The contradiction gate protects not just the persona but the entire fact base from inconsistency. Where CORTEX guards the "who am I?" question, the contradiction gate guards the "what do I know?" question.

---

## 7. Feature 4: Compaction-Aware Capture

### 7.1 The Gap: Messages Used Once and Never Queried Are Lost

ENGRAM's pointer-based compaction (J1) replaces evicted messages with time-range markers containing topic hints. The pointers are sufficient for the agent to know that "something about cron debugging happened between 14:00 and 15:30" — but the actual content (the exact error message, the specific fix attempted, the user's aside about a related problem) is gone from the context window.

Memory-core's nightly dreaming (J5) can recover some of this content by promoting memories that were recently searched for. But dreaming only promotes what has been queried. Content that was used once — read, acted upon, and never referenced again — is permanently lost after compaction.

This creates a specific class of information loss:

1. User mentions a detail in passing ("by the way, the SSL cert expires next month").
2. The agent acknowledges but does not create a task or note.
3. Compaction evicts the message.
4. The detail was never queried, so dreaming never promotes it.
5. The agent has no record of the SSL certificate expiry.

For a personal assistant, these "by the way" details are often the most valuable — precisely because no one explicitly searched for them later.

### 7.2 Capture Protocol

The compaction-aware capture pass runs on the `before_compaction` hook, which fires immediately before memory-core evicts messages from the context window:

```typescript
async function compactionCapture(ctx: CompactionContext): Promise<void> {
  const messagesToEvict = ctx.messages;
  const captured: CapturedChunk[] = [];

  for (const msg of messagesToEvict) {
    if (isAlreadyInCorpus(msg)) continue;     // already persisted
    if (isTrivial(msg)) continue;              // greetings, acks, etc.

    const chunk = extractChunk(msg);
    chunk.metadata.capturedAt = Date.now();
    chunk.metadata.captureReason = 'compaction';
    captured.push(chunk);
  }

  if (captured.length > 0) {
    await writeToCapturePath(captured);
    updateConceptIndex(captured); // incremental index update
  }
}
```

### 7.3 Triviality Filter

Not every evicted message deserves preservation. The `isTrivial` function applies three heuristics:

1. **Length threshold**: Messages under 20 tokens are likely greetings or acknowledgments.
2. **Template match**: Messages matching common conversational patterns ("ok", "got it", "thanks") are skipped.
3. **Redundancy check**: If the message content is already present in a previously captured chunk (checked via a lightweight hash), it is skipped.

The filter is deliberately permissive — it is better to capture a marginally useful message than to lose a detail that matters. Storage is cheap; lost information is expensive.

### 7.4 Integration with before_compaction Hook

The `before_compaction` hook receives the full list of messages that memory-core is about to evict. MNEMOSYNE's capture pass processes them synchronously before returning control to memory-core, which then proceeds with eviction. The captured chunks are written to `<agent-data>/mnemosyne/captured/` as individual markdown files, one per capture event.

These captured files are indexed by memory-core's FTS5 crawler on its next pass, making them available for future hybrid search and concept index ingestion. The capture thus feeds back into the retrieval pipeline: content captured during compaction becomes searchable in subsequent sessions.

### 7.5 Relationship to J1 ENGRAM

ENGRAM's pointer-based compaction and MNEMOSYNE's capture are complementary, not competing:

- **ENGRAM pointers** tell the agent *what happened* (time range, topic hints) so it can decide whether to search for details.
- **MNEMOSYNE capture** ensures the *details exist to be found* when the agent does search.

Without capture, ENGRAM's pointers point to content that may no longer exist in any searchable form. Without pointers, capture would be insufficient because the agent would not know to search for captured content. The two mechanisms close each other's gaps.

---

## 8. Implementation

### 8.1 Plugin Manifest

```json
{
  "id": "tinkerclaw-memory-enhancements",
  "name": "MNEMOSYNE — Memory Enhancement Suite",
  "version": "0.1.0",
  "description": "Hippocampus concept index, task-conditioned scoring, contradiction gate, and compaction capture for personal-agent memory systems.",
  "entryPoint": "dist/index.js",
  "configSchema": {
    "conceptIndex": {
      "enabled": { "type": "boolean", "default": true },
      "confidenceThreshold": { "type": "number", "default": 0.4 },
      "pruneThresholdDays": { "type": "number", "default": 90 }
    },
    "taskScoring": {
      "enabled": { "type": "boolean", "default": false },
      "weight": { "type": "number", "default": 0.3 }
    },
    "contradictionGate": {
      "enabled": { "type": "boolean", "default": false },
      "mode": { "type": "string", "enum": ["warn", "block"], "default": "warn" }
    },
    "compactionCapture": {
      "enabled": { "type": "boolean", "default": true },
      "trivialityThresholdTokens": { "type": "number", "default": 20 }
    }
  }
}
```

Note the `configSchema` field — mandatory since the 2026-03-05 upstream merge. Missing this field blocks all plugin loading (a lesson learned from the hippocampus extension incident documented in the fork's operational history).

### 8.2 Hook Registrations

All four hooks are registered in `activate()` and are individually gated by their `enabled` config flag. Hook registration order:

1. `conceptIndexLookup` on `retrieval_pre` — runs first, may short-circuit.
2. `taskConditionedScoring` on `retrieval_pre` — runs second, only if concept index did not fire.
3. `contradictionGate` on `before_message_write` — synchronous, returns allow/warn/block.
4. `compactionCapture` on `before_compaction` — synchronous, must complete before eviction proceeds.

### 8.3 v0.1 Status

| Feature | Status | Notes |
|---------|--------|-------|
| Hippocampus concept index | **Live** | anchors.json persisted, lazy loading, nightly rebuild |
| Compaction-aware capture | **Live** | Capturing to `<agent-data>/mnemosyne/captured/`, FTS5 indexing confirmed |
| Task-conditioned scoring | Scaffolded | Hook registered but returns early (no task descriptor extraction yet) |
| Contradiction gate | Scaffolded | Hook registered, `detectContradictions` returns empty array (entity extraction not wired) |

### 8.4 Lines of Code

| File | LOC | Purpose |
|------|-----|---------|
| `index.ts` | 85 | Plugin entry, hook registration, config loading |
| `concept-index.ts` | 210 | Map data structure, ingestion, lookup, pruning |
| `task-scoring.ts` | 65 | Score modifier, task descriptor interface |
| `contradiction-gate.ts` | 120 | Write interception, contradiction detection stub |
| `compaction-capture.ts` | 145 | Before-compaction capture, triviality filter |
| `utils.ts` | 55 | Tokenizer, hash, file I/O helpers |
| **Total** | **680** | |

### 8.5 Deployment

```bash
# Build the plugin
cd <agent-workspace>/extensions/tinkerclaw-memory-enhancements
pnpm build

# Enable in openclaw.json
# plugins.allow: ["tinkerclaw-memory-enhancements"]
# plugins.entries: [{ "id": "tinkerclaw-memory-enhancements", "enabled": true }]

# Restart gateway (SIGUSR1 does not reload ES modules)
openclaw-restart --full
```

---

## 9. Discussion

### 9.1 Why a Unified Plugin

The four features could have been implemented as four separate plugins. A unified plugin was chosen for three reasons:

1. **Shared data structures.** The concept index is updated by both the ingestion pipeline (Feature 1) and the compaction capture pass (Feature 4). Splitting them into separate plugins would require inter-plugin communication or duplicated state.
2. **Consistent configuration.** A single `configSchema` with four feature flags is simpler to manage than four separate plugin configurations.
3. **Marketplace distribution.** ClawHub distributes plugins as atomic units. A user searching for "memory enhancements" finds one package with four toggles rather than four packages that must be installed in the right combination.

### 9.2 Relationship to Upstream Memory-Wiki

OpenClaw's upstream is developing a "Memory-Wiki" feature that combines memory-core with a wiki-style editor for structured knowledge management. Memory-Wiki targets enterprise teams managing shared knowledge bases.

MNEMOSYNE targets a different use case: a single personal assistant whose memory grows organically through conversation, nightly consolidation, and imported archives. The two systems are complementary:

- Memory-Wiki assumes well-structured, human-curated content. MNEMOSYNE handles messy, auto-generated content.
- Memory-Wiki optimizes for collaborative editing and version history. MNEMOSYNE optimizes for single-agent consistency and retrieval speed.
- Memory-Wiki provides a UI for manual fact management. MNEMOSYNE provides automated gates that reduce the need for manual review.

### 9.3 The Complementarity Argument

Enterprise-wiki and personal-assistant are not just different products — they produce different *failure modes*. An enterprise wiki fails when it returns outdated information (solved by version history and review processes). A personal assistant fails when it contradicts itself (solved by contradiction gating) or loses context (solved by compaction capture). Designing for one set of failures does not address the other.

This divergence justifies maintaining MNEMOSYNE as a separate enhancement layer rather than lobbying for its features to be merged into upstream memory-core. The upstream maintainers optimize for the general case; MNEMOSYNE optimizes for the personal-assistant edge.

### 9.4 Potential ClawHub Distribution

The plugin architecture and configSchema compliance make MNEMOSYNE a candidate for ClawHub distribution once v0.2 reaches stability. Distribution requirements:

- All four features must be individually toggleable (already implemented via config flags).
- The plugin must not crash when memory-core hooks are unavailable (already handled by failure isolation).
- Documentation must include configuration examples for common scenarios.

---

## 10. Limitations and Future Work

### 10.1 Hook Dependency on Upstream

MNEMOSYNE's four hooks (`retrieval_pre`, `before_message_write`, `before_compaction`, `after_compaction`) are not part of memory-core's public API. They exist as extension points but are not contractually stable. An upstream refactor could rename, remove, or change the signature of any hook.

**Mitigation:** The merge-guardian automation (documented in the fork's operational infrastructure) checks for hook availability after every upstream merge. If a hook disappears, the guardian logs a warning and MNEMOSYNE degrades gracefully — the missing feature is disabled, others continue.

### 10.2 Ingestion Wiring

The concept index in v0.1 is populated during nightly consolidation. Real-time ingestion — indexing new memories as they arrive during the session — is implemented as an incremental update in `compactionCapture` but is not yet triggered from all memory write paths. Full real-time ingestion is planned for v0.2.

### 10.3 Contradiction Detection Depth

The current contradiction detector (v0.1 scaffold) uses entity-level comparison: same entity, different value. This catches explicit contradictions but misses:

- **Semantic contradictions**: "The project is going well" vs "The project has critical blockers."
- **Temporal contradictions**: Facts that were true at time T but not at time T+1, where the detector cannot determine which is current.
- **Implication contradictions**: "All tests pass" followed by "Feature X is broken" (the second implies at least one test should fail).

Deeper contradiction detection using LLM-assisted semantic comparison is planned for v0.3.

### 10.4 Benchmarks

No formal benchmarks have been run comparing O(1) concept index retrieval against hybrid search. The theoretical complexity analysis (§4.7) predicts constant-time retrieval, but wall-clock measurements on the production corpus (878K events, ~2,000 concepts) are needed to quantify the actual speedup. Benchmarking against the CORF-annotated dataset from J2 is planned for v0.2.

### 10.5 Capture Volume

Compaction-aware capture increases the total volume of stored content. Over time, the captured corpus may grow to rival the original memory corpus. A retention policy (e.g., captured chunks older than 180 days with zero retrieval hits are pruned) is planned for v0.2.

---

## 11. Conclusion

MNEMOSYNE demonstrates that four significant improvements to a personal-agent memory system — constant-time concept retrieval, task-conditioned scoring, write-time contradiction gating, and compaction-aware capture — can be delivered as a single plugin layered on top of an unmodified upstream codebase. The plugin architecture provides failure isolation, upgrade independence, and marketplace distributability. Two features are live in production (v0.1); two are scaffolded and awaiting entity extraction and task descriptor wiring (v0.2). The approach validates a design principle: that personal-assistant memory diverges enough from enterprise-wiki memory to justify a separate enhancement layer rather than upstream modification.

---

## References

- Serra, O. (2026a). ENGRAM: Event-Navigated Graded Retrieval & Archival Memory. *J1, Serra Paper Series.* v4.0.
- Serra, O. (2026b). HIPPOCAMPUS: A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents. *J2, Serra Paper Series.* v5.0.
- Serra, O. (2026c). CORTEX: Identity Persistence and Consistency Preservation for Long-Running AI Agents. *J4, Serra Paper Series.* v4.0.
- Serra, O. (2026e). The Prompt Cerebellum: How Structured Nightly Prompting Produces Emergent Intelligence in Stateless AI Agents. *J5, Serra Paper Series.* v1.1.
- Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. *NeurIPS 2020.*
- Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560.*
- Xu, Z., et al. (2025). A-MEM: Agentic Memory for LLM Agents. *arXiv preprint.*
- Croft, W.B., Metzler, D., & Strohman, T. (2010). *Search Engines: Information Retrieval in Practice.* Addison-Wesley.
- MemoryOS. (2024). Mem0: Multi-Level Memory Architecture. *mem0.ai.*
- Carbonell, J. & Goldstein, J. (1998). The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries. *SIGIR 1998.*
- Robertson, S. & Zaragoza, H. (2009). The Probabilistic Relevance Framework: BM25 and Beyond. *Foundations and Trends in IR.*

---

## Changelog

- **v1.0 (2026-04-16):** Initial paper. Covers 4 features (hippocampus O(1) index, task-conditioned scoring, contradiction gate, compaction capture), v0.1 plugin scaffold with 680 LOC, v0.2 roadmap.
