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

feat(catalog): wire catalog ingredients into Ask retrieval

[._.]/ Adam Eivyfc53de0f5e7f
diff --git a/server/services/askService.js b/server/services/askService.js
index 2c960a11af..4c58707c57 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -22,6 +22,8 @@
import { getActiveProvider, getProviderById } from './providers.js';
import { hybridSearchMemories, getMemory } from './memoryBackend.js';
import { generateQueryEmbedding } from './memoryEmbeddings.js';
+import { hybridSearchIngredients } from './catalogDB.js';
+import { getCatalogType } from '../lib/catalogTypes.js';
import { getInboxLog, getProjects, getIdeas } from './brainStorage.js';
import { getStories } from './autobiography.js';
import { getGoals } from './identity.js';
@@ -35,7 +37,7 @@ import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManage
// Re-export so the route can keep importing modes via askService — but
// askConversations is the source of truth (it owns the persistence schema).
export const VALID_MODES = STORAGE_VALID_MODES;
-export const SOURCE_KINDS = ['memory', 'brain-note', 'autobiography', 'goal', 'calendar'];
+export const SOURCE_KINDS = ['memory', 'brain-note', 'autobiography', 'goal', 'calendar', 'catalog'];
const PER_SOURCE_LIMIT = {
memory: 6,
@@ -43,6 +45,7 @@ const PER_SOURCE_LIMIT = {
autobiography: 3,
goal: 5,
calendar: 6,
+ catalog: 4,
};
// Truncation caps for prompt assembly. Source snippets are short summaries;
@@ -115,6 +118,35 @@ async function retrieveMemories(question) {
return sources;
}
+// Creative Catalog ingredients (characters / places / objects / ideas / scenes
+// / concepts) via the same RRF hybrid search the memory retriever uses, so the
+// catalog slice shares Ask's scoring/budget model. Snippet is the type's
+// primary-content payload field (falling back to summary/description/name).
+// Vector matches only appear once embeddings are backfilled; FTS works
+// immediately. No try/catch — gatherSources' allSettled isolates failures.
+async function retrieveCatalog(question) {
+ const queryEmbedding = await generateQueryEmbedding(question);
+ const hits = await hybridSearchIngredients(question, queryEmbedding, {
+ limit: PER_SOURCE_LIMIT.catalog,
+ ftsWeight: 0.4,
+ vectorWeight: 0.6,
+ });
+ return hits.map(({ ingredient: ing, rrfScore }) => {
+ const t = getCatalogType(ing.type);
+ const primary = t?.primaryContentKey ? ing.payload?.[t.primaryContentKey] : null;
+ const snippetText = primary || ing.payload?.summary || ing.payload?.description || ing.name;
+ return {
+ kind: 'catalog',
+ id: `catalog:${ing.type}:${ing.id}`,
+ title: ing.name || t?.label || 'Ingredient',
+ snippet: normalizeSnippet(String(snippetText || '')),
+ relevance: rrfScore ?? 0.5,
+ href: `/catalog/${ing.type}/${ing.id}`,
+ meta: { id: ing.id, type: ing.type, tags: ing.tags },
+ };
+ });
+}
+
// askService scores by query-term overlap, not BM25. We reuse the BM25
// module's lowercase / punctuation / stopword tokenizer so the stopword
// list stays in lockstep, then tighten the result for lexical-overlap
@@ -270,12 +302,13 @@ export async function gatherSources(question, { timeWindow, maxSources = 12 } =
// Fan out — each retriever is independently failable, so allSettled keeps
// a single-source outage from killing the answer.
- const [memSettled, brainSettled, autoSettled, goalSettled, calSettled] = await Promise.allSettled([
+ const [memSettled, brainSettled, autoSettled, goalSettled, calSettled, catSettled] = await Promise.allSettled([
retrieveMemories(question),
retrieveBrainNotes(question, queryTokens),
retrieveAutobiography(queryTokens),
retrieveGoals(queryTokens),
retrieveCalendar(queryTokens, timeWindow),
+ retrieveCatalog(question),
]);
const all = [
@@ -284,6 +317,7 @@ export async function gatherSources(question, { timeWindow, maxSources = 12 } =
...(autoSettled.status === 'fulfilled' ? autoSettled.value : []),
...(goalSettled.status === 'fulfilled' ? goalSettled.value : []),
...(calSettled.status === 'fulfilled' ? calSettled.value : []),
+ ...(catSettled.status === 'fulfilled' ? catSettled.value : []),
];
// Dedupe by id (parallel retrievers can occasionally surface the same
@@ -299,7 +333,7 @@ export async function gatherSources(question, { timeWindow, maxSources = 12 } =
// Source-weighted final ranking — memory and goals are the highest-signal
// PortOS surfaces; calendar wins time-bounded questions; autobiography is
// long-form so it ranks last unless lexical match is very strong.
- const KIND_WEIGHT = { memory: 1.0, goal: 0.95, 'brain-note': 0.85, calendar: 0.85, autobiography: 0.7 };
+ const KIND_WEIGHT = { memory: 1.0, goal: 0.95, 'brain-note': 0.85, calendar: 0.85, catalog: 0.8, autobiography: 0.7 };
deduped.sort((a, b) => (b.relevance * (KIND_WEIGHT[b.kind] || 0.5)) - (a.relevance * (KIND_WEIGHT[a.kind] || 0.5)));
return deduped.slice(0, Math.max(1, Math.min(50, maxSources)));
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index 1120bc3d16..fb254eca6d 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -46,7 +46,14 @@ vi.mock('./calendarSync.js', () => ({
getEvents: vi.fn(),
}));
+// catalogDB is mocked so the catalog retriever never touches Postgres; the real
+// catalogTypes lib (getCatalogType) stays unmocked — it's pure.
+vi.mock('./catalogDB.js', () => ({
+ hybridSearchIngredients: vi.fn(),
+}));
+
const { spawn } = await import('child_process');
+const catalogDB = await import('./catalogDB.js');
const memoryBackend = await import('./memoryBackend.js');
const memoryEmbeddings = await import('./memoryEmbeddings.js');
const brainStorage = await import('./brainStorage.js');
@@ -71,6 +78,7 @@ beforeEach(() => {
identity.getGoals.mockResolvedValue({ goals: [] });
character.getCharacter.mockResolvedValue({ name: 'Adam', class: 'Developer' });
calendarSync.getEvents.mockResolvedValue({ events: [] });
+ catalogDB.hybridSearchIngredients.mockResolvedValue([]);
});
describe('gatherSources', () => {
@@ -91,6 +99,34 @@ describe('gatherSources', () => {
expect(sources[0].id).toBe('memory:mem-1');
});
+ it('surfaces catalog ingredients with kind/id/href shape and the type primary-content snippet', async () => {
+ catalogDB.hybridSearchIngredients.mockResolvedValue([
+ { ingredient: { id: 'cat-chr-1', type: 'character', name: 'Ada', tags: ['mentor'], payload: { physicalDescription: 'sharp eyes' } }, rrfScore: 0.9 },
+ { ingredient: { id: 'cat-idea-2', type: 'idea', name: 'Heist', tags: [], payload: { summary: 'a clockwork heist' } }, rrfScore: 0.6 },
+ ]);
+
+ const sources = await askService.gatherSources('who is in my story');
+ const catalog = sources.filter((s) => s.kind === 'catalog');
+ expect(catalog).toHaveLength(2);
+ const ada = catalog.find((s) => s.id === 'catalog:character:cat-chr-1');
+ expect(ada).toBeTruthy();
+ expect(ada.title).toBe('Ada');
+ expect(ada.snippet).toBe('sharp eyes'); // character primaryContentKey
+ expect(ada.href).toBe('/catalog/character/cat-chr-1');
+ const idea = catalog.find((s) => s.id === 'catalog:idea:cat-idea-2');
+ expect(idea.snippet).toBe('a clockwork heist'); // idea primaryContentKey = summary
+ });
+
+ it('still answers when the catalog retriever throws (isolated by allSettled)', async () => {
+ catalogDB.hybridSearchIngredients.mockRejectedValue(new Error('catalog down'));
+ memoryBackend.hybridSearchMemories.mockResolvedValue({ memories: [{ id: 'mem-1', rrfScore: 0.9 }] });
+ memoryBackend.getMemory.mockResolvedValue({ id: 'mem-1', content: 'x', summary: 's', type: 'fact' });
+
+ const sources = await askService.gatherSources('anything');
+ expect(sources.some((s) => s.kind === 'memory')).toBe(true);
+ expect(sources.some((s) => s.kind === 'catalog')).toBe(false);
+ });
+
it('keeps producing answers when one retriever throws', async () => {
// Memory throws — brain notes still surface.
memoryBackend.hybridSearchMemories.mockRejectedValue(new Error('vector backend down'));
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 8560fcd092..816e17581c 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -584,6 +584,72 @@ export async function searchIngredientsByText(q, { type, limit = 20 } = {}) {
return result.rows.map((row) => ({ ingredient: rowToIngredient(row), rank: parseFloat(row.rank) }));
}
+// Hybrid search: Reciprocal Rank Fusion over FTS (`search_tsv`) + vector
+// (`embedding`) results, mirroring memoryDB.hybridSearchMemories so the catalog
+// shares the SAME scoring model when it feeds Ask retrieval. Returns
+// `[{ ingredient, rrfScore, ftsRank, vectorRank, searchMethod }]` sorted by
+// rrfScore. Either signal can be absent (no query text, or no embeddings
+// backfilled yet) — the present one still ranks.
+export async function hybridSearchIngredients(queryText, queryEmbedding, options = {}) {
+ const { type, limit = 20, minRelevance = 0.5, ftsWeight = 0.4, vectorWeight = 0.6 } = options;
+ const RRF_K = 60;
+ const fetchLimit = limit * 2;
+
+ let ftsRows = [];
+ if (queryText) {
+ const conds = ['deleted = false', `search_tsv @@ websearch_to_tsquery('english', $1)`];
+ const params = [queryText, fetchLimit];
+ let idx = 3;
+ if (type) { conds.push(`type = $${idx++}`); params.push(type); }
+ const r = await query(
+ `SELECT *, ts_rank_cd(search_tsv, websearch_to_tsquery('english', $1)) AS rank
+ FROM catalog_ingredients WHERE ${conds.join(' AND ')}
+ ORDER BY rank DESC LIMIT $2`,
+ params,
+ );
+ ftsRows = r.rows;
+ }
+
+ let vecRows = [];
+ if (queryEmbedding) {
+ const conds = ['deleted = false', 'embedding IS NOT NULL', '1 - (embedding <=> $1) >= $2'];
+ const params = [arrayToPgvector(queryEmbedding), minRelevance * 0.5, fetchLimit];
+ let idx = 4;
+ if (type) { conds.push(`type = $${idx++}`); params.push(type); }
+ const r = await query(
+ `SELECT *, 1 - (embedding <=> $1) AS similarity
+ FROM catalog_ingredients WHERE ${conds.join(' AND ')}
+ ORDER BY embedding <=> $1 LIMIT $3`,
+ params,
+ );
+ vecRows = r.rows;
+ }
+
+ const rrf = new Map();
+ ftsRows.forEach((row, rank) => {
+ const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };
+ cur.row = row; cur.ftsRank = rank + 1; cur.rrfScore += ftsWeight / (RRF_K + rank + 1);
+ rrf.set(row.id, cur);
+ });
+ vecRows.forEach((row, rank) => {
+ const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };
+ if (!cur.row) cur.row = row;
+ cur.vectorRank = rank + 1; cur.rrfScore += vectorWeight / (RRF_K + rank + 1);
+ rrf.set(row.id, cur);
+ });
+
+ return Array.from(rrf.values())
+ .map((d) => ({
+ ingredient: rowToIngredient(d.row),
+ rrfScore: d.rrfScore,
+ ftsRank: d.ftsRank,
+ vectorRank: d.vectorRank,
+ searchMethod: d.ftsRank && d.vectorRank ? 'hybrid' : d.ftsRank ? 'fts' : 'vector',
+ }))
+ .sort((a, b) => b.rrfScore - a.rrfScore)
+ .slice(0, limit);
+}
+
// `{ client }` is optional — see the createIngredient comment above. Passing
// the same client used to insert the ingredient row keeps the source-link row