Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(memory): require explicit updates for supersession (#2188)

Chester6d897e8eaaba
diff --git a/headroom/memory/mcp_server.py b/headroom/memory/mcp_server.py
index e71fe9b54..52830ff06 100644
--- a/headroom/memory/mcp_server.py
+++ b/headroom/memory/mcp_server.py
@@ -76,7 +76,9 @@ _TOOLS = [
description=(
"Save information to persistent memory for future sessions. "
"Use this for decisions, conventions, architecture context, "
- "user preferences, project facts, or anything worth remembering.\n\n"
+ "user preferences, project facts, or anything worth remembering. "
+ "Saving a similar fact does not replace an existing memory; corrections "
+ "must use an explicit update path with the existing memory ID.\n\n"
"IMPORTANT: Break information into atomic facts — one fact per "
"entry in the 'facts' array. Each fact should be a single, "
"self-contained statement that answers one question. "
@@ -264,11 +266,6 @@ async def _handle_search(
return [TextContent(type="text", text=f"Search error: {e}")]
-# Similarity threshold for auto-supersession: if a new memory is this
-# similar to an existing one, it replaces (supersedes) the old one.
-_SUPERSEDE_SIMILARITY = 0.70
-
-
async def _handle_save(
backend: LocalBackend, arguments: dict[str, Any], user_id: str
) -> list[TextContent]:
@@ -294,44 +291,16 @@ async def _handle_save(
if not fact:
continue
- # Check for semantically similar existing memory to auto-supersede
- superseded_id: str | None = None
- try:
- existing = await backend.search_memories(
- query=fact,
- user_id=user_id,
- top_k=3,
- )
- for r in existing:
- if getattr(r.memory, "superseded_by", None):
- continue
- if r.score >= _SUPERSEDE_SIMILARITY:
- superseded_id = r.memory.id
- logger.info(
- f"Memory MCP: auto-superseding [{r.memory.id[:8]}] "
- f"(similarity={r.score:.2f}): {r.memory.content[:60]}"
- )
- break
- except Exception:
- pass
-
- if superseded_id:
- memory = await backend.update_memory(
- memory_id=superseded_id,
- new_content=fact,
- )
- results_lines.append(
- f" updated [{superseded_id[:8]}→{memory.id[:8]}]: {fact[:60]}"
- )
- superseded += 1
- else:
- memory = await backend.save_memory(
- content=fact,
- user_id=user_id,
- importance=importance,
- )
- results_lines.append(f" saved [{memory.id[:8]}]: {fact[:60]}")
- saved += 1
+ # Similarity is a retrieval signal, not proof that two memories
+ # represent versions of the same fact. Only explicit update paths
+ # with a caller-supplied memory ID may create a supersession chain.
+ memory = await backend.save_memory(
+ content=fact,
+ user_id=user_id,
+ importance=importance,
+ )
+ results_lines.append(f" saved [{memory.id[:8]}]: {fact[:60]}")
+ saved += 1
summary = f"Saved {saved} new, updated {superseded} existing ({saved + superseded} total)"
return [TextContent(type="text", text=summary + "\n" + "\n".join(results_lines))]
diff --git a/tests/test_memory/test_mcp_server.py b/tests/test_memory/test_mcp_server.py
index 34339c31d..b86e15179 100644
--- a/tests/test_memory/test_mcp_server.py
+++ b/tests/test_memory/test_mcp_server.py
@@ -228,3 +228,30 @@ def test_search_fails_open_when_access_tracking_fails() -> None:
result = asyncio.run(mcp_server_mod._handle_search(backend, {"query": "preference"}, "alice"))
assert "Useful preference" in result[0].kwargs["text"]
+
+
+def test_save_does_not_supersede_a_semantically_similar_memory() -> None:
+ existing = Memory(content="Use compact output by default", user_id="alice")
+ saved = Memory(content="Keep semantic compression disabled", user_id="alice")
+ backend = SimpleNamespace(
+ search_memories=AsyncMock(return_value=[SimpleNamespace(memory=existing, score=0.91)]),
+ update_memory=AsyncMock(),
+ save_memory=AsyncMock(return_value=saved),
+ )
+
+ result = asyncio.run(
+ mcp_server_mod._handle_save(
+ backend,
+ {"facts": ["Keep semantic compression disabled"], "importance": 0.9},
+ "alice",
+ )
+ )
+
+ backend.search_memories.assert_not_awaited()
+ backend.update_memory.assert_not_awaited()
+ backend.save_memory.assert_awaited_once_with(
+ content="Keep semantic compression disabled",
+ user_id="alice",
+ importance=0.9,
+ )
+ assert result[0].kwargs["text"].startswith("Saved 1 new, updated 0 existing")