Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

voice: explicit long-term memory routing on retrieval-shaped turns

Adam Eivy714ef532f74e
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index fe871a9f28..445b14390f 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -14,6 +14,7 @@ import { getToolSpecsForIntent, classifyIntent, dispatchTool, getAllToolNames, U
import { isEchoOfRecentTts, rememberTtsSentence } from './echo.js';
import { appendJournal, getToday } from '../brainJournal.js';
import { resolvePending, isExpired } from './confirmGate.js';
+import { getRelevantMemories } from '../memoryRetriever.js';
// Compact per-page UI summary the LLM uses to drive ui_* tools. Keep it
// short — every turn pays the token cost. Groups elements by kind and shows
@@ -147,6 +148,65 @@ const buildSystemPrompt = (cfg) => {
return lines.join(' ');
};
+// Detect "retrieval-shaped" voice turns — the user is asking about their OWN
+// past: prior statements, preferences, facts, decisions, or recall-style
+// questions ("what did I say about…", "do I prefer…", "when did I…",
+// "remind me…", "have I mentioned…"). For these turns we proactively pull the
+// top relevant long-term memories into the system prompt so the model answers
+// from stored context instead of guessing. Deliberately a cheap regex set —
+// no extra LLM classification call. Narrow enough that action/navigation turns
+// ("open my daily log", "go to tasks") and present-tense questions ("what time
+// is it") don't false-positive into a memory search.
+//
+// Exported for unit testing.
+const RETRIEVAL_PATTERNS = [
+ // First-person recall about what *I* (the user) said/did/decided in the past.
+ /\b(?:what|when|where|why|how|who)\b[^?]*\bI\b[^?]*\b(?:said|told|mentioned|wrote|noted|decided|chose|picked|wanted|planned|asked|did|set)\b/i,
+ // "did I …" / "have I …" / "had I …" recall questions.
+ /\b(?:did|have|had|was|were)\s+I\b/i,
+ // Preference questions ("do I prefer", "what's my preferred", "which do I like").
+ /\bdo\s+I\s+(?:prefer|like|usually|normally|typically|tend\s+to|want|use)\b/i,
+ /\bmy\s+(?:preference|preferences|preferred|favorite|favourite|usual|go[- ]?to)\b/i,
+ // Explicit recall verbs aimed at the assistant's memory.
+ /\bremind\s+me\b/i,
+ /\b(?:do\s+you\s+)?remember\b/i,
+ /\b(?:what\s+do\s+you|what\s+can\s+you)\s+(?:remember|recall|know)\s+(?:about|regarding)\b/i,
+ /\brecall\b/i,
+ // "what did we decide/say/agree" — shared-history recall.
+ /\bwhat\s+did\s+we\s+(?:decide|say|agree|discuss|talk\s+about)\b/i,
+];
+
+export const isRetrievalShaped = (userText) => {
+ if (!userText || typeof userText !== 'string') return false;
+ const t = userText.trim();
+ if (!t) return false;
+ return RETRIEVAL_PATTERNS.some((re) => re.test(t));
+};
+
+// How many top-ranked memories to inject. Kept small (3–5) so the system
+// prompt stays cheap and the spoken reply stays grounded in the most relevant
+// few rather than a wall of marginally-related context.
+const MEMORY_INJECT_LIMIT = 5;
+
+// Run long-term memory retrieval for a retrieval-shaped utterance and render
+// the top-N hits into a clearly-delimited block for the system prompt. Returns
+// null when there are no relevant memories (inject nothing) — the caller must
+// guard on null. Memory retrieval can fail (embeddings backend down, no index
+// yet); that surfaces as zero memories rather than killing the turn.
+//
+// Exported for unit testing.
+export const buildMemoryContext = async (userText, { limit = MEMORY_INJECT_LIMIT } = {}) => {
+ const memories = await getRelevantMemories({ description: userText }, { limit });
+ if (!Array.isArray(memories) || !memories.length) return null;
+ const top = memories.slice(0, limit).filter((m) => m && typeof m.content === 'string' && m.content.trim());
+ if (!top.length) return null;
+ const lines = top.map((m) => `- ${m.content.trim()}`);
+ return [
+ 'Relevant memories (the user\'s own stored notes, preferences, facts, and past decisions — use these to answer; do not invent details not present here):',
+ ...lines,
+ ].join('\n');
+};
+
const SENTENCE_RE = /[.!?\n](?:\s+|$)/;
// Exported for unit testing — the sentence-boundary logic is too central to
@@ -405,6 +465,21 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
});
}
}
+ // Explicit long-term memory routing: only for retrieval-shaped turns (the
+ // user asking about their own past / preferences / prior decisions). For
+ // everything else we skip the search entirely so normal turns stay cheap.
+ // Injects nothing when there are no relevant memories.
+ if (isRetrievalShaped(userText)) {
+ const tMem = Date.now();
+ const memoryBlock = await buildMemoryContext(userText);
+ if (memoryBlock) {
+ const count = (memoryBlock.match(/^- /gm) || []).length;
+ tlog(`memory.inject ${count} memories +${Date.now() - tMem}ms`);
+ messages.push({ role: 'system', content: memoryBlock });
+ } else {
+ tlog(`memory.none +${Date.now() - tMem}ms`);
+ }
+ }
messages.push(...history, { role: 'user', content: userText });
const maxIterations = Math.max(1, cfg.llm.tools?.maxIterations ?? 3);
diff --git a/server/services/voice/pipeline.test.js b/server/services/voice/pipeline.test.js
index 827baf0bec..4d625516b6 100644
--- a/server/services/voice/pipeline.test.js
+++ b/server/services/voice/pipeline.test.js
@@ -1,5 +1,14 @@
-import { describe, it, expect } from 'vitest';
-import { splitSentences, isNonSpeechMarker, detectNarrationWithoutCall } from './pipeline.js';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the memory retriever so buildMemoryContext can be tested without a live
+// embeddings backend / memory index. Default returns no memories; individual
+// tests override with mockResolvedValueOnce.
+vi.mock('../memoryRetriever.js', () => ({
+ getRelevantMemories: vi.fn(async () => []),
+}));
+
+import { splitSentences, isNonSpeechMarker, detectNarrationWithoutCall, isRetrievalShaped, buildMemoryContext } from './pipeline.js';
+import { getRelevantMemories } from '../memoryRetriever.js';
describe('splitSentences', () => {
it('returns empty when no terminator is present', () => {
@@ -133,3 +142,88 @@ describe('detectNarrationWithoutCall', () => {
expect(detectNarrationWithoutCall({})).toBe(false);
});
});
+
+describe('isRetrievalShaped', () => {
+ it('flags first-person past recall questions', () => {
+ expect(isRetrievalShaped('What did I say about the budget last week?')).toBe(true);
+ expect(isRetrievalShaped('When did I decide to switch hosting providers?')).toBe(true);
+ expect(isRetrievalShaped('Why did I choose Postgres over SQLite?')).toBe(true);
+ expect(isRetrievalShaped('Did I mention anything about the trip?')).toBe(true);
+ expect(isRetrievalShaped('Have I talked about this before?')).toBe(true);
+ });
+
+ it('flags preference questions', () => {
+ expect(isRetrievalShaped('Do I prefer dark roast or light roast?')).toBe(true);
+ expect(isRetrievalShaped("What's my preferred editor?")).toBe(true);
+ expect(isRetrievalShaped('What is my favorite color?')).toBe(true);
+ });
+
+ it('flags explicit recall / remember phrasings', () => {
+ expect(isRetrievalShaped('Remind me what I planned for the weekend.')).toBe(true);
+ expect(isRetrievalShaped('Do you remember my doctor appointment?')).toBe(true);
+ expect(isRetrievalShaped('What do you remember about my goals?')).toBe(true);
+ expect(isRetrievalShaped('Recall what we discussed yesterday.')).toBe(true);
+ expect(isRetrievalShaped('What did we decide about the launch date?')).toBe(true);
+ });
+
+ it('does NOT flag action / navigation turns', () => {
+ expect(isRetrievalShaped('Open my daily log.')).toBe(false);
+ expect(isRetrievalShaped('Take me to tasks.')).toBe(false);
+ expect(isRetrievalShaped('Add milk to my brain inbox.')).toBe(false);
+ expect(isRetrievalShaped('Fill the description with hello.')).toBe(false);
+ });
+
+ it('does NOT flag present-tense / generic questions', () => {
+ expect(isRetrievalShaped('What time is it?')).toBe(false);
+ expect(isRetrievalShaped('How are my services doing?')).toBe(false);
+ expect(isRetrievalShaped('What are my goals?')).toBe(false);
+ expect(isRetrievalShaped('Tell me a joke.')).toBe(false);
+ });
+
+ it('tolerates empty / non-string input', () => {
+ expect(isRetrievalShaped('')).toBe(false);
+ expect(isRetrievalShaped(' ')).toBe(false);
+ expect(isRetrievalShaped(null)).toBe(false);
+ expect(isRetrievalShaped(undefined)).toBe(false);
+ });
+});
+
+describe('buildMemoryContext', () => {
+ beforeEach(() => {
+ getRelevantMemories.mockReset();
+ });
+
+ it('renders a delimited block with the top memories', async () => {
+ getRelevantMemories.mockResolvedValueOnce([
+ { content: 'User prefers dark roast coffee', type: 'preference', relevance: 0.9 },
+ { content: 'User decided to use Postgres for the DB', type: 'decision', relevance: 0.8 },
+ ]);
+ const block = await buildMemoryContext('do I prefer dark or light roast?');
+ expect(block).toContain('Relevant memories');
+ expect(block).toContain('- User prefers dark roast coffee');
+ expect(block).toContain('- User decided to use Postgres for the DB');
+ });
+
+ it('caps injection at the requested limit', async () => {
+ const many = Array.from({ length: 10 }, (_, i) => ({ content: `memory ${i}`, type: 'fact', relevance: 1 - i / 10 }));
+ getRelevantMemories.mockResolvedValueOnce(many);
+ const block = await buildMemoryContext('what did I say', { limit: 3 });
+ const bulletCount = (block.match(/^- /gm) || []).length;
+ expect(bulletCount).toBe(3);
+ });
+
+ it('returns null when no memories are relevant (inject nothing)', async () => {
+ getRelevantMemories.mockResolvedValueOnce([]);
+ expect(await buildMemoryContext('what did I say about X?')).toBeNull();
+ });
+
+ it('returns null when retriever yields only empty-content entries', async () => {
+ getRelevantMemories.mockResolvedValueOnce([{ content: ' ', type: 'fact' }, { type: 'fact' }]);
+ expect(await buildMemoryContext('what did I say about X?')).toBeNull();
+ });
+
+ it('returns null when the retriever returns a non-array', async () => {
+ getRelevantMemories.mockResolvedValueOnce(null);
+ expect(await buildMemoryContext('what did I say about X?')).toBeNull();
+ });
+});