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

address review (round 9): nullish-coalesce relevance, normalise snippets at retrieval, doc fixes

Adam Eivyce2a7c2a0975
diff --git a/server/routes/ask.js b/server/routes/ask.js
index 88c9fa496c..c6d23717aa 100644
--- a/server/routes/ask.js
+++ b/server/routes/ask.js
@@ -178,8 +178,10 @@ router.post('/', asyncHandler(async (req, res) => {
await send('delta', { text: evt.text });
} else if (evt.type === 'done') {
providerInfo = { providerId: evt.providerId, model: evt.model };
- // Streaming providers accumulate via delta events; one-shot CLI
- // providers report the full answer once at 'done'.
+ // Both API and CLI providers stream their text via `delta` events
+ // (CLI providers yield a single big chunk). The terminal `done`
+ // event also carries the full answer as a defensive fallback —
+ // populate `assistantText` from it only if no deltas arrived.
if (!assistantText && evt.answer) assistantText = evt.answer;
} else if (evt.type === 'error') {
streamErrored = true;
diff --git a/server/services/askConversations.js b/server/services/askConversations.js
index 589b90907d..7f81f06c3d 100644
--- a/server/services/askConversations.js
+++ b/server/services/askConversations.js
@@ -81,11 +81,12 @@ export async function listConversations({ limit = 50 } = {}) {
throw err;
});
- // Filenames carry a sortable timestamp prefix (`ask_<base36-ms>_…`) so a
- // descending lexical sort gives newest-first ordering without reading any
- // file. The full sweep below still reads every conversation — we need it
- // to enforce the 30-day expiry on stale unpinned entries beyond the first
- // page — but the sort lets us fill `summaries` from the head.
+ // Filenames carry a sortable timestamp prefix (`ask_<base36-ms-padded>_…`)
+ // so a descending lexical sort gives newest-first ordering without
+ // reading any file. The two-tier sweep below uses this: JSON-read the
+ // head page for summaries, `stat()` everything else and only JSON-read
+ // tail files whose mtime puts them past the expiry window (those are
+ // pruning candidates and we still need the JSON to honour `promoted`).
const ids = entries
.filter((f) => f.endsWith('.json'))
.map((f) => f.slice(0, -5))
diff --git a/server/services/askService.js b/server/services/askService.js
index fb4699d884..1940317187 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -42,9 +42,22 @@ const PER_SOURCE_LIMIT = {
// Truncation caps for prompt assembly. Source snippets are short summaries;
// transcript turns are previous chat turns trimmed so multi-turn history
-// can't blow the token budget alone.
+// can't blow the token budget alone. Snippets are also normalised at
+// retrieval time (not just at prompt assembly) because they're streamed to
+// the client in the `sources` SSE event and persisted into the
+// conversation JSON on every assistant turn — letting full bodies through
+// would bloat both wire and disk.
const SNIPPET_MAX_CHARS = 600;
const HISTORY_TURN_MAX_CHARS = 1500;
+
+// Cap snippet at retrieval time to bound what gets persisted + sent to
+// the client. Collapse whitespace and trim before slicing.
+function normaliseSnippet(text) {
+ if (!text) return '';
+ const collapsed = String(text).replace(/\s+/g, ' ').trim();
+ if (collapsed.length <= SNIPPET_MAX_CHARS) return collapsed;
+ return collapsed.slice(0, SNIPPET_MAX_CHARS - 1) + '…';
+}
// Autobiography stories grow over time — cap how many we score per question
// so a user with hundreds of stories doesn't make every Ask quadratic.
const AUTOBIO_SCAN_LIMIT = 50;
@@ -84,8 +97,8 @@ async function retrieveMemories(question) {
kind: 'memory',
id: `memory:${mem.id}`,
title: mem.summary || mem.type || 'Memory',
- snippet: mem.content || '',
- relevance: hits[i].rrfScore || hits[i].similarity || 0.5,
+ snippet: normaliseSnippet(mem.content),
+ relevance: hits[i].rrfScore ?? hits[i].similarity ?? 0.5,
href: `/brain/memory?id=${encodeURIComponent(mem.id)}`,
meta: { type: mem.type, importance: mem.importance, updatedAt: mem.updatedAt },
});
@@ -136,11 +149,11 @@ async function retrieveBrainNotes(question, queryTokens) {
const candidates = [];
for (const idea of ideasArr || []) {
const text = `${idea.title || ''} ${idea.description || ''}`.trim();
- candidates.push({ kind: 'brain-note', subkind: 'idea', recordId: idea.id, title: idea.title || '(idea)', snippet: text, href: `/brain/memory?type=ideas&id=${encodeURIComponent(idea.id)}`, updatedAt: idea.updatedAt || idea.createdAt });
+ candidates.push({ kind: 'brain-note', subkind: 'idea', recordId: idea.id, title: idea.title || '(idea)', snippet: normaliseSnippet(text), href: `/brain/memory?type=ideas&id=${encodeURIComponent(idea.id)}`, updatedAt: idea.updatedAt || idea.createdAt });
}
for (const proj of projectsArr || []) {
const text = `${proj.title || ''} ${proj.description || ''}`.trim();
- candidates.push({ kind: 'brain-note', subkind: 'project', recordId: proj.id, title: proj.title || '(project)', snippet: text, href: `/brain/memory?type=projects&id=${encodeURIComponent(proj.id)}`, updatedAt: proj.updatedAt || proj.createdAt });
+ candidates.push({ kind: 'brain-note', subkind: 'project', recordId: proj.id, title: proj.title || '(project)', snippet: normaliseSnippet(text), href: `/brain/memory?type=projects&id=${encodeURIComponent(proj.id)}`, updatedAt: proj.updatedAt || proj.createdAt });
}
for (const entry of inbox || []) {
// Brain inbox records use `capturedText` / `capturedAt` (see
@@ -148,7 +161,7 @@ async function retrieveBrainNotes(question, queryTokens) {
// forward-compat with any older entries that may exist on disk.
const text = entry.capturedText || entry.text || entry.summary || '';
if (!text) continue;
- candidates.push({ kind: 'brain-note', subkind: 'inbox', recordId: entry.id, title: text.slice(0, 80), snippet: text, href: '/brain/inbox', updatedAt: entry.capturedAt || entry.timestamp || entry.createdAt });
+ candidates.push({ kind: 'brain-note', subkind: 'inbox', recordId: entry.id, title: text.slice(0, 80), snippet: normaliseSnippet(text), href: '/brain/inbox', updatedAt: entry.capturedAt || entry.timestamp || entry.createdAt });
}
for (const c of candidates) {
@@ -169,7 +182,7 @@ async function retrieveAutobiography(queryTokens) {
kind: 'autobiography',
id: `autobiography:${s.id}`,
title: s.themeId ? `${s.themeId} — ${(s.promptText || '').slice(0, 60)}` : (s.promptText || 'Autobiography'),
- snippet: s.content || '',
+ snippet: normaliseSnippet(s.content),
href: '/digital-twin/autobiography',
relevance: lexicalScore(`${s.promptText || ''} ${s.content || ''}`, queryTokens),
meta: { themeId: s.themeId, createdAt: s.createdAt },
@@ -186,7 +199,7 @@ async function retrieveGoals(queryTokens) {
kind: 'goal',
id: `goal:${g.id}`,
title: g.title || '(goal)',
- snippet: [g.description, g.horizon ? `horizon: ${g.horizon}` : '', g.status ? `status: ${g.status}` : ''].filter(Boolean).join(' · '),
+ snippet: normaliseSnippet([g.description, g.horizon ? `horizon: ${g.horizon}` : '', g.status ? `status: ${g.status}` : ''].filter(Boolean).join(' · ')),
href: `/digital-twin/goals?id=${encodeURIComponent(g.id)}`,
relevance: lexicalScore(`${g.title || ''} ${g.description || ''} ${(g.tags || []).join(' ')}`, queryTokens) + (g.status === 'active' ? 0.05 : 0),
meta: { status: g.status, horizon: g.horizon, category: g.category },
@@ -212,7 +225,7 @@ async function retrieveCalendar(queryTokens, timeWindow) {
kind: 'calendar',
id: `calendar:${e.id || `${e.startTime}-${e.title}`}`,
title: e.title || '(event)',
- snippet: [e.startTime || '', e.location || '', (e.description || '').slice(0, 200)].filter(Boolean).join(' · '),
+ snippet: normaliseSnippet([e.startTime || '', e.location || '', (e.description || '').slice(0, 200)].filter(Boolean).join(' · ')),
href: `/calendar/agenda?date=${encodeURIComponent(e.startTime || '')}`,
relevance: lexicalScore(text, queryTokens),
meta: { startTime: e.startTime, endTime: e.endTime, accountId: e.accountId },
@@ -290,9 +303,10 @@ function formatSourcesForPrompt(sources) {
const lines = ['## Retrieved Sources', ''];
sources.forEach((s, i) => {
const tag = `[${i + 1}]`;
- const snippet = (s.snippet || '').replace(/\s+/g, ' ').slice(0, SNIPPET_MAX_CHARS);
+ // Snippets are already normalised + capped at retrieval time, so we
+ // don't repeat the trimming here.
lines.push(`${tag} ${s.kind} — ${s.title}`);
- if (snippet) lines.push(` ${snippet}`);
+ if (s.snippet) lines.push(` ${s.snippet}`);
});
return lines.join('\n');
}