Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(memory): recall matching memories into each chat turn (#1160)

Ruben Lütke8f2b6ca5a1e6
diff --git a/dodaios/brain/manager.py b/dodaios/brain/manager.py
index 309e5af843..21a5c303c7 100644
--- a/dodaios/brain/manager.py
+++ b/dodaios/brain/manager.py
@@ -4286,6 +4286,17 @@ class BrainManager:
parts.append(agentic_block)
return "\n\n".join(p for p in parts if p)
+ @staticmethod
+ async def _vault_recall(user_text: str) -> str:
+ """Per-message memory recall, bounded to 150 ms so a busy disk never stalls a turn."""
+ from dodaios.memory.vault.runtime import turn_block
+
+ try:
+ return await asyncio.wait_for(asyncio.to_thread(turn_block, user_text), timeout=0.15)
+ except TimeoutError:
+ log.info("memory vault: per-message recall skipped (over 150 ms)")
+ return ""
+
def _upcoming_block(self) -> str:
"""Dated plans from the notebooks for the next two weeks (initiative grounding).
@@ -11529,6 +11540,18 @@ class BrainManager:
log.warning("WikiContextInjector raised unexpectedly — skipping", exc_info=True)
self._wiki_context_suffix = ""
+ # Personal memory vault (ADR-0044): memories that match this message and
+ # are not in the always-on block ride along in the same per-turn slot.
+ if not (
+ turn_override is not None
+ and turn_override.tool_context.get("tool_origin") == "society"
+ ):
+ recalled = await self._vault_recall(user_text)
+ if recalled:
+ self._wiki_context_suffix = "\n\n".join(
+ p for p in (self._wiki_context_suffix.strip(), recalled) if p
+ )
+
# Wave 2 (omni-latency): assemble the per-turn dynamic context (date +
# wiki) once. In cache-optimized mode it rides on the user
# message (keeping the cached system prompt stable); empty in legacy
diff --git a/dodaios/memory/vault/runtime.py b/dodaios/memory/vault/runtime.py
index 3ff4499de3..65f575f177 100644
--- a/dodaios/memory/vault/runtime.py
+++ b/dodaios/memory/vault/runtime.py
@@ -130,6 +130,85 @@ _WORDS = {
),
}
+#: Words that say nothing about what a message is about (shipped input languages).
+_STOPWORDS = frozenset(
+ (
+ "the and you your what when where who how why can could would should will "
+ "are was were have has had this that these those with from for about into "
+ "please tell know remember just also some any more much very "
+ "der die das und ich du wir ihr sie ist sind war was wer wie wo wann warum " # i18n-allow
+ "ein eine einen dem den des mit von für über auf noch auch bitte mal mir " # i18n-allow
+ "mich dir dich mein meine kannst kann weißt hast habe nicht oder aber " # i18n-allow
+ "que los las una por para como con del pero" # i18n-allow
+ ).split()
+)
+
+#: Budget and size of the per-message recall.
+TURN_MAX_CHARS = 900
+TURN_LIMIT = 6
+#: A hit must score at least this share of the best hit to be shown.
+TURN_RELATIVE_FLOOR = 0.35
+
+_TURN_HEADER = (
+ "## Possibly relevant memories (looked up for this message)\n"
+ "From the user's long-term memory; use them only if they fit the question."
+)
+
+
+def turn_block(user_text: str, *, compact: bool = False) -> str:
+ """Memories that match this message and are not already always in mind.
+
+ Cheap and local: one FTS query on the vault, no model call. ``""`` when
+ nothing fits, no vault runs or the message has no content words.
+ """
+ vault = _active
+ if vault is None or not user_text.strip():
+ return ""
+ words = [
+ w for w in re.findall(r"\w+", user_text.casefold()) if len(w) > 2 and w not in _STOPWORDS
+ ]
+ if not words:
+ return ""
+ try:
+ budget = _budgets["compact" if compact else "full"]
+ in_mind = {
+ m.id for _, memories in vault.profile_selection(max_chars=budget) for m in memories
+ }
+ hits = [
+ h
+ for h in vault.search(" ".join(words), limit=TURN_LIMIT * 2)
+ if h.memory.id not in in_mind
+ ]
+ except Exception: # noqa: BLE001 — recall must never break a turn
+ log.warning("memory vault: per-message recall failed", exc_info=True)
+ return ""
+ if not hits:
+ return ""
+ floor = hits[0].score * TURN_RELATIVE_FLOOR
+ lines: list[str] = []
+ used = 0
+ chosen = []
+ for hit in hits:
+ if hit.score < floor or len(lines) >= TURN_LIMIT:
+ break
+ memory = hit.memory
+ line = f"- {memory.text}"
+ if memory.valid_from and memory.origin != "imported":
+ line += f" (since {memory.valid_from[:10]})"
+ if used + len(line) > TURN_MAX_CHARS:
+ break
+ lines.append(line)
+ used += len(line) + 1
+ chosen.append(memory.id)
+ if not lines:
+ return ""
+ try:
+ vault.mark_used(chosen)
+ except Exception: # noqa: BLE001 — a usage counter is not worth failing a turn over
+ log.debug("memory vault: could not count recall use", exc_info=True)
+ return _TURN_HEADER + "\n" + "\n".join(lines)
+
+
_KIND_HINTS: tuple[tuple[str, re.Pattern[str]], ...] = tuple(
(kind, re.compile(r"\b(" + "|".join(map(re.escape, words.split())) + r")\b", re.I))
for kind, words in _WORDS.items()
diff --git a/tests/unit/memory/vault/test_turn_recall.py b/tests/unit/memory/vault/test_turn_recall.py
new file mode 100644
index 0000000000..65b5dd1015
--- /dev/null
+++ b/tests/unit/memory/vault/test_turn_recall.py
@@ -0,0 +1,65 @@
+"""Per-message recall from the memory vault (ADR-0044)."""
+
+from __future__ import annotations
+
+import pytest
+
+from dodaios.memory.vault import runtime as vault_runtime
+from dodaios.memory.vault.store import MemoryVault
+
+
+def vault(tmp_path):
+ v = MemoryVault(tmp_path / "vault.db")
+ vault_runtime.set_active(v)
+ yield v
+ vault_runtime.set_active(None)
+
+
+def test_recall_brings_matching_memories_that_are_not_always_in_mind(vault):
+ vault.remember("I live in Berlin.", "profile")
+ vault.remember("We hiked the Zugspitze with Lea last summer.", "episode", entities=["Lea"])
+ vault.remember(
+ "Lea's birthday is on 14 March.", "reference", entities=["Lea"], sensitivity="sensitive"
+ )
+ block = vault_runtime.turn_block("When is Lea's birthday?")
+ assert block.startswith("## Possibly relevant memories")
+ assert "Lea's birthday is on 14 March." in block
+ # Already in the always-on block: not repeated.
+ assert "I live in Berlin." not in vault_runtime.turn_block("Where do I live, Berlin?")
+ used = {m.text: m.use_count for m in vault.list()}
+ assert used["Lea's birthday is on 14 March."] == 1
+
+
+def test_recall_stays_quiet_on_small_talk_and_without_a_vault(vault):
+ vault.remember("We hiked the Zugspitze last summer.", "episode")
+ assert vault_runtime.turn_block("can you tell me what you know?") == ""
+ assert vault_runtime.turn_block(" ") == ""
+ vault_runtime.set_active(None)
+ assert vault_runtime.turn_block("Zugspitze") == ""
+
+
+def test_recall_drops_weak_hits_and_respects_the_budget(vault):
+ for i in range(20):
+ vault.remember(f"Concert number {i} with the jazz band was great.", "episode")
+ block = vault_runtime.turn_block("jazz concert")
+ lines = [line for line in block.splitlines() if line.startswith("- ")]
+ assert 0 < len(lines) <= vault_runtime.TURN_LIMIT
+ assert len(block) <= vault_runtime.TURN_MAX_CHARS + 200
+
+
+async def test_manager_recall_helper_is_bounded(vault, monkeypatch):
+ from dodaios.brain.manager import BrainManager
+
+ vault.remember("We hiked the Zugspitze last summer.", "episode")
+ assert "Zugspitze" in await BrainManager._vault_recall("Zugspitze hike")
+
+ def slow(_text: str) -> str:
+ import time
+
+ time.sleep(0.5)
+ return "late"
+
+ monkeypatch.setattr(vault_runtime, "turn_block", slow)
+ assert await BrainManager._vault_recall("anything") == ""