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

perf: serve unified search from an in-memory brain projection instead of a full disk scan (#3506)

[._.]/ Adam Eivy67b49109d64b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0500a00209..c5474f8784 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -95,3 +95,5 @@
## Internal
- **[issue-3497] The Chief of Staff no longer re-reads and re-parses its task lists on every scheduler tick** — an unchanged list is served from memory instead, which matters most on installs whose task history has grown large. Edits made outside PortOS (a text editor, a restore, a sync peer) are still picked up immediately.
+
+- **[issue-3506] Typing in the ⌘K search bar no longer re-reads every Brain record off disk.** Brain keeps one file per record — people, projects, ideas, admin items, memory entries, links and inbox captures each live in their own directory — and unified search was opening and parsing all of them, across all seven stores, for every single character typed. On a Brain that has been in use for a while that is thousands of file reads per keystroke, which is exactly why the palette got slower the more you put into it. Search now reads a small in-memory projection of just the fields it matches on, refreshed as records change rather than rebuilt per query, so the disk is touched once per store instead of once per character. A store that is legitimately empty counts as read — otherwise the one case with nothing to cache would have kept re-scanning forever. Records arriving from a sync peer, which deliberately land without firing the usual change events so they cannot echo back around the network, now raise a local-only signal so the projection refreshes for them too; without it an inbound sync would have left search answering from a stale snapshot indefinitely. The old cap that only ever searched your 200 most recent inbox captures is gone with it — it existed solely to bound the disk cost that no longer exists.
diff --git a/server/services/brainSearchIndex.js b/server/services/brainSearchIndex.js
new file mode 100644
index 0000000000..5013d06b6f
--- /dev/null
+++ b/server/services/brainSearchIndex.js
@@ -0,0 +1,171 @@
+/**
+ * Brain Search Index
+ *
+ * In-memory field projections of the brain entity stores, so unified search
+ * (`server/services/search.js`) can answer a keystroke without re-reading and
+ * re-parsing every record file on disk (issue #3506).
+ *
+ * Brain entity stores are per-record `collectionStore` dirs
+ * (`data/brain/<type>/<id>/index.json`) with NO whole-store cache — every
+ * `brainStorage.getAll(type)` lists the directory and `loadOne`s each record.
+ * That is the right trade for the write paths, but the ⌘K palette fans out to
+ * seven of those stores on EVERY keystroke, so a brain of a few thousand
+ * records turns each character typed into thousands of stat+read+JSON.parse
+ * calls. This module reads each store at most once and then keeps the
+ * projection fresh from `brainEvents`.
+ *
+ * Only the fields search actually matches on (plus the ordering key) are
+ * projected — the index holds no attachments, embeddings, or classification
+ * payloads.
+ *
+ * FRESHNESS — three signal classes, all of them covered:
+ * 1. `${type}:upserted` / `${type}:deleted` — the per-record events every
+ * local write path emits (create/update/updateWith/updateMany/remove, and
+ * upsertWithId in its default mode). Patched incrementally, no re-scan.
+ * 2. `record:changed` — the local-only invalidation signal brainStorage emits
+ * from the write paths that are deliberately event-SILENT: peer applies
+ * (`applyRemoteRecord`, silent to prevent the #1077 cross-peer echo) and
+ * `upsertWithId({ emitEvent: false })`. Without it an inbound sync or
+ * anti-entropy reconcile would leave this cache stale indefinitely.
+ * 3. Nothing else writes brain entity records — `pruneTombstones` only hard-
+ * prunes tombstones, which `getAll` strips and which therefore were never
+ * in the projection, and `backfillOriginInstanceId` runs once at boot and
+ * touches no projected field.
+ */
+
+import { getAll, brainEvents, memoryRecencyMs } from './brainStorage.js';
+import { safeDate } from '../lib/fileUtils.js';
+
+// The projected fields per searchable brain type — the exact set
+// `searchBrain` matches on and renders snippets from.
+const SEARCH_FIELDS = Object.freeze({
+ inbox: Object.freeze(['capturedText']),
+ people: Object.freeze(['name', 'context']),
+ projects: Object.freeze(['name', 'notes']),
+ ideas: Object.freeze(['title', 'oneLiner', 'notes']),
+ admin: Object.freeze(['title', 'notes', 'nextAction']),
+ memories: Object.freeze(['title', 'content', 'mood']),
+ links: Object.freeze(['title', 'url', 'description']),
+});
+
+/** The brain entity types this index covers. */
+export const BRAIN_SEARCH_TYPES = Object.freeze(Object.keys(SEARCH_FIELDS));
+
+// Newest-first ordering key, for the two types whose reader sorted before
+// handing records to search: inbox by capture time, memories by the
+// import-aware recency clock. Types with no ranker keep the store's natural
+// (id) order, exactly as their `getAll`-backed readers did.
+const RANKERS = Object.freeze({
+ inbox: (record) => safeDate(record?.capturedAt),
+ memories: (record) => memoryRecencyMs(record),
+});
+
+/**
+ * Per-type cache slot.
+ *
+ * `null` = NOT BUILT. A `Map` — INCLUDING an empty one — = built. The
+ * distinction is load-bearing: a user with zero links must get a cache hit, not
+ * a directory re-scan on every keystroke, so nothing here may branch on
+ * `.size`/`.length` truthiness.
+ */
+const cache = {};
+// Bumped by every invalidation. A rebuild that started before the bump is
+// discarded rather than cached, so a sync landing mid-build can't be undone.
+const generation = {};
+// In-flight rebuild per type, so a burst of keystrokes shares one disk scan.
+const building = {};
+
+function resetState() {
+ for (const type of BRAIN_SEARCH_TYPES) {
+ cache[type] = null;
+ generation[type] = 0;
+ delete building[type];
+ }
+}
+resetState();
+
+function project(type, record) {
+ const projection = { id: record.id };
+ for (const field of SEARCH_FIELDS[type]) {
+ projection[field] = record[field];
+ }
+ const ranker = RANKERS[type];
+ if (ranker) projection._rank = ranker(record);
+ return projection;
+}
+
+function sortProjections(type, projections) {
+ // Newest-first. Only ranked types reorder; the rest keep store order.
+ return RANKERS[type] ? projections.sort((a, b) => b._rank - a._rank) : projections;
+}
+
+function invalidate(type) {
+ if (!(type in cache)) return;
+ cache[type] = null;
+ generation[type] += 1;
+}
+
+function patchUpsert(type, record) {
+ if (!(type in cache) || !record?.id) return;
+ const map = cache[type];
+ if (!map) {
+ // Not built (possibly mid-rebuild): there is nothing to patch, and the
+ // in-flight scan may already have missed this write — bump the generation
+ // so its result is discarded instead of cached stale.
+ generation[type] += 1;
+ return;
+ }
+ map.set(record.id, project(type, record));
+}
+
+function patchDelete(type, id) {
+ if (!(type in cache) || !id) return;
+ const map = cache[type];
+ if (!map) {
+ generation[type] += 1;
+ return;
+ }
+ map.delete(id);
+}
+
+/**
+ * Field projections for one brain type, newest-first where the type is ranked.
+ *
+ * Reads the store from disk at most once per invalidation; every later call is
+ * served from memory. Returns a fresh array each call (callers filter/map it),
+ * but the projection objects themselves are shared — treat them as read-only.
+ * Ranked types carry a `_rank` ordering key alongside the projected fields.
+ */
+export async function getBrainProjections(type) {
+ if (!(type in cache)) throw new Error(`brainSearchIndex: unknown search type "${type}"`);
+
+ const cached = cache[type];
+ if (cached) return sortProjections(type, [...cached.values()]);
+
+ if (!building[type]) {
+ const startedAt = generation[type];
+ building[type] = getAll(type)
+ .then((records) => {
+ const map = new Map((records ?? []).map((r) => [r.id, project(type, r)]));
+ // Only adopt the scan if nothing invalidated the type while it ran.
+ if (generation[type] === startedAt) cache[type] = map;
+ return map;
+ })
+ .finally(() => { delete building[type]; });
+ }
+
+ const map = await building[type];
+ return sortProjections(type, [...map.values()]);
+}
+
+// Wire the freshness signals once, at module load.
+for (const type of BRAIN_SEARCH_TYPES) {
+ brainEvents.on(`${type}:upserted`, ({ record } = {}) => patchUpsert(type, record));
+ brainEvents.on(`${type}:deleted`, ({ id } = {}) => patchDelete(type, id));
+}
+brainEvents.on('record:changed', ({ type } = {}) => invalidate(type));
+
+/** Test hook — drop every projection and reset the in-flight/generation state. */
+export function __resetBrainSearchIndex() {
+ resetState();
+}
diff --git a/server/services/brainSearchIndex.test.js b/server/services/brainSearchIndex.test.js
new file mode 100644
index 0000000000..b441f69072
--- /dev/null
+++ b/server/services/brainSearchIndex.test.js
@@ -0,0 +1,184 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import EventEmitter from 'events'
+
+vi.mock('./brainStorage.js', () => ({
+ brainEvents: new EventEmitter(),
+ getAll: vi.fn().mockResolvedValue([]),
+ memoryRecencyMs: (record) => Date.parse(record?.updatedAt ?? '') || 0
+}))
+
+import { getBrainProjections, BRAIN_SEARCH_TYPES, __resetBrainSearchIndex } from './brainSearchIndex.js'
+import { getAll, brainEvents } from './brainStorage.js'
+
+const deferred = () => {
+ let resolve
+ const promise = new Promise((r) => { resolve = r })
+ return { promise, resolve }
+}
+
+describe('brainSearchIndex', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ __resetBrainSearchIndex()
+ getAll.mockResolvedValue([])
+ })
+
+ it('covers every brain type unified search reads', () => {
+ expect([...BRAIN_SEARCH_TYPES]).toEqual([
+ 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links'
+ ])
+ })
+
+ it('rejects a type it does not index', async () => {
+ await expect(getBrainProjections('journals')).rejects.toThrow(/unknown search type/)
+ })
+
+ it('projects only the searched fields', async () => {
+ getAll.mockResolvedValue([
+ { id: 'p1', name: 'Ada Placeholder', context: 'colleague', avatarBlob: 'x'.repeat(50), embedding: [1, 2, 3] }
+ ])
+
+ const [projection] = await getBrainProjections('people')
+ expect(projection).toEqual({ id: 'p1', name: 'Ada Placeholder', context: 'colleague' })
+ })
+
+ it('scans the store once and serves later reads from memory', async () => {
+ getAll.mockResolvedValue([{ id: 'l1', title: 'Example', url: 'https://example.com' }])
+
+ await getBrainProjections('links')
+ await getBrainProjections('links')
+
+ expect(getAll).toHaveBeenCalledTimes(1)
+ })
+
+ it('caches a built-but-empty store instead of re-scanning it', async () => {
+ getAll.mockResolvedValue([])
+
+ expect(await getBrainProjections('links')).toEqual([])
+ expect(await getBrainProjections('links')).toEqual([])
+
+ // `null` means NOT BUILT; an empty result is built and must stay cached.
+ expect(getAll).toHaveBeenCalledTimes(1)
+ })
+
+ it('collapses concurrent first reads into one scan', async () => {
+ const gate = deferred()
+ getAll.mockReturnValue(gate.promise)
+
+ const both = Promise.all([getBrainProjections('ideas'), getBrainProjections('ideas')])
+ gate.resolve([{ id: 'i1', title: 'Example idea' }])
+ const [a, b] = await both
+
+ expect(getAll).toHaveBeenCalledTimes(1)
+ expect(a).toEqual(b)
+ })
+
+ it('patches the projection on an upserted event without re-scanning', async () => {
+ getAll.mockResolvedValue([{ id: 'p1', name: 'Ada Placeholder', context: 'colleague' }])
+ await getBrainProjections('people')
+
+ brainEvents.emit('people:upserted', { id: 'p1', record: { id: 'p1', name: 'Ada Renamed', context: 'friend' } })
+ brainEvents.emit('people:upserted', { id: 'p2', record: { id: 'p2', name: 'Bo Placeholder', context: 'neighbor' } })
+
+ const projections = await getBrainProjections('people')
+ expect(getAll).toHaveBeenCalledTimes(1)
+ expect(projections).toEqual([
+ { id: 'p1', name: 'Ada Renamed', context: 'friend' },
+ { id: 'p2', name: 'Bo Placeholder', context: 'neighbor' }
+ ])
+ })
+
+ it('drops a record on a deleted event', async () => {
+ getAll.mockResolvedValue([
+ { id: 'p1', name: 'Ada Placeholder' },
+ { id: 'p2', name: 'Bo Placeholder' }
+ ])
+ await getBrainProjections('people')
+
+ brainEvents.emit('people:deleted', { id: 'p1', record: { id: 'p1' } })
+
+ expect(await getBrainProjections('people')).toEqual([{ id: 'p2', name: 'Bo Placeholder', context: undefined }])
+ expect(getAll).toHaveBeenCalledTimes(1)
+ })
+
+ it('rebuilds after record:changed — the signal event-silent peer applies emit', async () => {
+ getAll.mockResolvedValue([{ id: 'p1', name: 'Ada Placeholder' }])
+ await getBrainProjections('people')
+
+ getAll.mockResolvedValue([
+ { id: 'p1', name: 'Ada Placeholder' },
+ { id: 'p2', name: 'Synced From Peer' }
+ ])
+ brainEvents.emit('record:changed', { type: 'people', id: 'p2' })
+
+ const projections = await getBrainProjections('people')
+ expect(getAll).toHaveBeenCalledTimes(2)
+ expect(projections.map((p) => p.id)).toEqual(['p1', 'p2'])
+ })
+
+ it('leaves other types alone when one type is invalidated', async () => {
+ getAll.mockResolvedValue([{ id: 'x1', title: 'Example' }])
+ await getBrainProjections('people')
+ await getBrainProjections('links')
+
+ brainEvents.emit('record:changed', { type: 'people', id: 'x1' })
+
+ // links stays cached across the people invalidation…
+ await getBrainProjections('links')
+ expect(getAll).toHaveBeenCalledTimes(2)
+
+ // …while people re-scans.
+ await getBrainProjections('people')
+ expect(getAll).toHaveBeenCalledTimes(3)
+ })
+
+ it('discards a scan that an invalidation superseded mid-flight', async () => {
+ const gate = deferred()
+ getAll.mockReturnValueOnce(gate.promise)
+
+ const pending = getBrainProjections('people')
+ // A peer apply lands while the first scan is still reading the directory.
+ brainEvents.emit('record:changed', { type: 'people', id: 'p2' })
+ gate.resolve([{ id: 'p1', name: 'Stale Snapshot' }])
+ await pending
+
+ getAll.mockResolvedValue([{ id: 'p1', name: 'Fresh Snapshot' }])
+ const projections = await getBrainProjections('people')
+
+ expect(getAll).toHaveBeenCalledTimes(2)
+ expect(projections[0].name).toBe('Fresh Snapshot')
+ })
+
+ it('discards a scan that an upsert superseded mid-flight', async () => {
+ const gate = deferred()
+ getAll.mockReturnValueOnce(gate.promise)
+
+ const pending = getBrainProjections('people')
+ brainEvents.emit('people:upserted', { id: 'p9', record: { id: 'p9', name: 'Written Mid Scan' } })
+ gate.resolve([])
+ await pending
+
+ getAll.mockResolvedValue([{ id: 'p9', name: 'Written Mid Scan' }])
+ expect((await getBrainProjections('people')).map((p) => p.id)).toEqual(['p9'])
+ expect(getAll).toHaveBeenCalledTimes(2)
+ })
+
+ it('orders inbox entries newest-first by capture time', async () => {
+ getAll.mockResolvedValue([
+ { id: 'older', capturedText: 'first', capturedAt: '2026-01-01T00:00:00.000Z' },
+ { id: 'newer', capturedText: 'second', capturedAt: '2026-02-01T00:00:00.000Z' }
+ ])
+
+ const projections = await getBrainProjections('inbox')
+ expect(projections.map((p) => p.id)).toEqual(['newer', 'older'])
+ })
+
+ it('keeps store order for unranked types', async () => {
+ getAll.mockResolvedValue([
+ { id: 'b', name: 'Beta' },
+ { id: 'a', name: 'Alpha' }
+ ])
+
+ expect((await getBrainProjections('projects')).map((p) => p.id)).toEqual(['b', 'a'])
+ })
+})
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index e66c4b3a9b..f79c12b8d1 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -127,6 +127,25 @@ const FILES = {
// Event emitter for brain data changes
export const brainEvents = new EventEmitter();
+/**
+ * Announce a persisted entity-store change that did NOT emit the usual
+ * `${type}:upserted` / `${type}:deleted` event.
+ *
+ * Two write paths are deliberately event-silent — `applyRemoteRecord` (peer
+ * applies, silent to prevent the #1077 cross-peer echo loop) and
+ * `upsertWithId({ emitEvent: false })` (the caller emits its own richer event).
+ * Read-through consumers didn't care, but a derived in-memory projection does:
+ * without this signal, brainSearchIndex would serve stale results forever after
+ * an inbound sync (issue #3506).
+ *
+ * LOCAL-ONLY, like `sync:applied`: it carries no record payload, is never fed
+ * to the sync log, and is never relayed to a peer, so it cannot amplify an
+ * echo. Listeners must treat it as "re-read this type from canonical state".
+ */
+function emitRecordChanged(type, id) {
+ brainEvents.emit('record:changed', { type, id });
+}
+
// In-memory caches — only for the non-collection files. Entity stores read
// through to disk (per issue #725: no whole-store cache to go stale when a
// per-record write bypasses it).
@@ -414,7 +433,12 @@ export async function upsertWithId(type, id, recordData, { emitEvent = true } =
};
await store.saveOneNow(id, record);
- if (emitEvent) brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });
+ if (emitEvent) {
+ brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });
+ } else {
+ // A suppressed per-record event still has to reach derived projections.
+ emitRecordChanged(type, id);
+ }
await brainSyncLog.appendChange(live ? 'update' : 'create', type, id, record, originInstanceId)
.catch(err => console.error(`⚠️ Sync log append failed for upsert ${type}/${id}: ${err.message}`));
@@ -822,8 +846,10 @@ export const updateBucket = (id, data) => update('buckets', id, data);
export const deleteBucket = (id) => remove('buckets', id);
// =============================================================================
-// REMOTE SYNC OPERATIONS (no events, no sync log — echo prevention)
+// REMOTE SYNC OPERATIONS (no per-record events, no sync log — echo prevention)
// =============================================================================
+// The only event these emit is the local-only `record:changed` invalidation
+// signal (see emitRecordChanged) — it never leaves this instance.
/**
* Apply a remote record to a store (last-writer-wins by updatedAt)
@@ -883,6 +909,9 @@ export async function applyRemoteRecord(type, id, record, op) {
: { ...record });
}
+ // Still no per-record event (that would echo back to the peer, #1077) —
+ // just the local invalidation signal so derived projections re-read.
+ emitRecordChanged(type, id);
return { applied: true };
});
}
diff --git a/server/services/search.js b/server/services/search.js
index 344c495fde..687b46c66f 100644
--- a/server/services/search.js
+++ b/server/services/search.js
@@ -5,11 +5,12 @@
* Uses Promise.allSettled for fault isolation — a failing adapter never
* blocks results from the other sources.
*
- * Sources: Brain (inbox/people/projects/ideas/links), CoS Memory (BM25),
- * Apps, History, Health metrics
+ * Sources: Brain (inbox/people/projects/ideas/admin/memories/links, served from
+ * the in-memory projections in brainSearchIndex.js), CoS Memory
+ * (BM25/hybrid), Apps, History, Health metrics
*/
-import { getInboxLog, getPeople, getProjects, getIdeas, getAdminItems, getMemoryEntries, getLinks } from './brainStorage.js';
+import { getBrainProjections } from './brainSearchIndex.js';
import { searchBM25 } from './memoryBM25.js';
import { getMemories, ensureBackend, hybridSearchMemories } from './memoryBackend.js';
import { getAllApps } from './apps.js';
@@ -42,115 +43,102 @@ function extractSnippet(text, query, maxLen = 100) {
// SOURCE ADAPTERS
// =============================================================================
+// Deep link into the Brain memory view for the id-addressed entity types.
+const brainMemoryUrl = (type) => (record) => `/brain/memory?type=${type}&id=${record.id}`;
+
+/**
+ * Brain sources, in the order their matches appear in the result list.
+ *
+ * `match` names the fields a query is tested against; they must stay a subset
+ * of the fields `brainSearchIndex` projects for that type, or the match
+ * silently stops working.
+ */
+const BRAIN_SOURCES = Object.freeze([
+ {
+ type: 'inbox',
+ resultType: 'inbox',
+ match: ['capturedText'],
+ title: (r) => (r.capturedText ?? '').substring(0, 60),
+ snippet: (r) => r.capturedText,
+ url: () => '/brain/inbox'
+ },
+ {
+ type: 'people',
+ resultType: 'person',
+ match: ['name', 'context'],
+ title: (r) => r.name,
+ snippet: (r) => r.context,
+ url: brainMemoryUrl('people')
+ },
+ {
+ type: 'projects',
+ resultType: 'project',
+ match: ['name', 'notes'],
+ title: (r) => r.name,
+ snippet: (r) => r.notes,
+ url: brainMemoryUrl('projects')
+ },
+ {
+ type: 'ideas',
+ resultType: 'idea',
+ match: ['title', 'oneLiner', 'notes'],
+ title: (r) => r.title,
+ snippet: (r) => r.oneLiner || r.notes,
+ url: brainMemoryUrl('ideas')
+ },
+ {
+ type: 'admin',
+ resultType: 'admin',
+ match: ['title', 'notes', 'nextAction'],
+ title: (r) => r.title,
+ snippet: (r) => r.notes || r.nextAction,
+ url: brainMemoryUrl('admin')
+ },
+ {
+ type: 'memories',
+ resultType: 'memory-entry',
+ match: ['title', 'content', 'mood'],
+ title: (r) => r.title,
+ snippet: (r) => r.content,
+ url: brainMemoryUrl('memories')
+ },
+ {
+ type: 'links',
+ resultType: 'link',
+ match: ['title', 'url', 'description'],
+ title: (r) => r.title || r.url,
+ snippet: (r) => r.description || r.url,
+ url: () => '/brain/links'
+ }
+]);
+
+/**
+ * Search the brain entity stores.
+ *
+ * Reads field projections from `brainSearchIndex` rather than
+ * `brainStorage.getAll()`, so a keystroke costs an in-memory scan instead of a
+ * full stat+read+parse of every record file across seven collection dirs
+ * (issue #3506). The index also removes the old `limit: 200` cap on inbox
+ * entries — that cap existed only to bound the per-query disk cost.
+ */
async function searchBrain(query) {
const q = query.toLowerCase();
- const [inboxResult, peopleResult, projectsResult, ideasResult, adminResult, memoriesResult, linksResult] =
- await Promise.allSettled([
- getInboxLog({ limit: 200 }),
- getPeople(),
- getProjects(),
- getIdeas(),
- getAdminItems(),
- getMemoryEntries(),
- getLinks()
- ]);
-
- const inboxEntries = inboxResult.status === 'fulfilled' ? inboxResult.value : [];
- const inboxMatches = (Array.isArray(inboxEntries) ? inboxEntries : [])
- .filter(e => e.capturedText?.toLowerCase().includes(q))
- .map(e => ({
- id: e.id,
- title: (e.capturedText ?? '').substring(0, 60),
- snippet: extractSnippet(e.capturedText, query),
- url: '/brain/inbox',
- type: 'inbox'
- }));
-
- const peopleMatches = peopleResult.status === 'fulfilled'
- ? (peopleResult.value ?? [])
- .filter(p => p.name?.toLowerCase().includes(q) || p.context?.toLowerCase().includes(q))
- .map(p => ({
- id: p.id,
- title: p.name,
- snippet: extractSnippet(p.context, query),
- url: `/brain/memory?type=people&id=${p.id}`,
- type: 'person'
- }))
- : [];
-
- const projectMatches = projectsResult.status === 'fulfilled'
- ? (projectsResult.value ?? [])
- .filter(p => p.name?.toLowerCase().includes(q) || p.notes?.toLowerCase().includes(q))
- .map(p => ({
- id: p.id,
- title: p.name,
- snippet: extractSnippet(p.notes, query),
- url: `/brain/memory?type=projects&id=${p.id}`,
- type: 'project'
- }))
- : [];
-
- const ideaMatches = ideasResult.status === 'fulfilled'
- ? (ideasResult.value ?? [])
- .filter(i => i.title?.toLowerCase().includes(q) || i.oneLiner?.toLowerCase().includes(q) || i.notes?.toLowerCase().includes(q))
- .map(i => ({
- id: i.id,
- title: i.title,
- snippet: extractSnippet(i.oneLiner || i.notes, query),
- url: `/brain/memory?type=ideas&id=${i.id}`,
- type: 'idea'
- }))
- : [];
-
- const adminMatches = adminResult.status === 'fulfilled'
- ? (adminResult.value ?? [])
- .filter(a => a.title?.toLowerCase().includes(q) || a.notes?.toLowerCase().includes(q) || a.nextAction?.toLowerCase().includes(q))
- .map(a => ({
- id: a.id,
- title: a.title,
- snippet: extractSnippet(a.notes || a.nextAction, query),
- url: `/brain/memory?type=admin&id=${a.id}`,
- type: 'admin'
- }))
- : [];
-
- const memoryMatches = memoriesResult.status === 'fulfilled'
- ? (memoriesResult.value ?? [])
- .filter(m => m.title?.toLowerCase().includes(q) || m.content?.toLowerCase().includes(q) || m.mood?.toLowerCase().includes(q))
- .map(m => ({
- id: m.id,
- title: m.title,
- snippet: extractSnippet(m.content, query),
- url: `/brain/memory?type=memories&id=${m.id}`,
- type: 'memory-entry'
- }))
- : [];
-
- const linkMatches = linksResult.status === 'fulfilled'
- ? (linksResult.value ?? [])
- .filter(l =>
- l.title?.toLowerCase().includes(q) ||
- l.url?.toLowerCase().includes(q) ||
- l.description?.toLowerCase().includes(q)
- )
- .map(l => ({
- id: l.id,
- title: l.title || l.url,
- snippet: extractSnippet(l.description || l.url, query),
- url: '/brain/links',
- type: 'link'
- }))
- : [];
-
- const results = [
- ...inboxMatches,
- ...peopleMatches,
- ...projectMatches,
- ...ideaMatches,
- ...adminMatches,
- ...memoryMatches,
- ...linkMatches
- ].slice(0, 8);
+ // allSettled per source: one unreadable store never blanks the others.
+ const settled = await Promise.allSettled(BRAIN_SOURCES.map((s) => getBrainProjections(s.type)));
+
+ const results = BRAIN_SOURCES.flatMap((source, i) => {
+ const outcome = settled[i];
+ if (outcome.status !== 'fulfilled') return [];
+ return (outcome.value ?? [])
+ .filter((r) => source.match.some((f) => typeof r[f] === 'string' && r[f].toLowerCase().includes(q)))
+ .map((r) => ({
+ id: r.id,
+ title: source.title(r),
+ snippet: extractSnippet(source.snippet(r), query),
+ url: source.url(r),
+ type: source.resultType
+ }));
+ }).slice(0, 8);
return { id: 'brain', label: 'Brain', icon: 'Brain', results };
}
diff --git a/server/services/search.test.js b/server/services/search.test.js
index 0136f554eb..7812bf7b00 100644
--- a/server/services/search.test.js
+++ b/server/services/search.test.js
@@ -1,14 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
+import EventEmitter from 'events'
-// Mock all dependencies
+// Mock all dependencies. Brain search runs through the REAL brainSearchIndex
+// (issue #3506), so the seam mocked here is brainStorage's disk reader.
vi.mock('./brainStorage.js', () => ({
- getInboxLog: vi.fn().mockResolvedValue([]),
- getPeople: vi.fn().mockResolvedValue([]),
- getProjects: vi.fn().mockResolvedValue([]),
- getIdeas: vi.fn().mockResolvedValue([]),
- getAdminItems: vi.fn().mockResolvedValue([]),
- getMemoryEntries: vi.fn().mockResolvedValue([]),
- getLinks: vi.fn().mockResolvedValue([])
+ brainEvents: new EventEmitter(),
+ getAll: vi.fn().mockResolvedValue([]),
+ memoryRecencyMs: (record) => Date.parse(record?.updatedAt ?? '') || 0
}))
vi.mock('./memoryBM25.js', () => ({
@@ -30,15 +28,23 @@ vi.mock('./history.js', () => ({
}))
import { fanOutSearch } from './search.js'
-import { getInboxLog, getPeople, getProjects, getIdeas, getAdminItems, getMemoryEntries, getLinks } from './brainStorage.js'
+import { getAll } from './brainStorage.js'
+import { __resetBrainSearchIndex } from './brainSearchIndex.js'
import { searchBM25 } from './memoryBM25.js'
import { getMemories, ensureBackend, hybridSearchMemories } from './memoryBackend.js'
import { getAllApps } from './apps.js'
import { getHistory } from './history.js'
+// Per-type record fixtures the mocked brainStorage.getAll serves.
+let brainRecords = {}
+const setBrainRecords = (type, records) => { brainRecords[type] = records }
+
describe('search service', () => {
beforeEach(() => {
vi.clearAllMocks()
+ brainRecords = {}
+ __resetBrainSearchIndex()
+ getAll.mockImplementation(async (type) => brainRecords[type] ?? [])
ensureBackend.mockResolvedValue('file')
})
@@ -49,7 +55,7 @@ describe('search service', () => {
})
it('should search across brain inbox entries', async () => {
- getInboxLog.mockResolvedValue([
+ setBrainRecords('inbox', [
{ id: 'i1', capturedText: 'Hello world from inbox' },
{ id: 'i2', capturedText: 'Another thought' }
])
@@ -63,7 +69,7 @@ describe('search service', () => {
})
it('should search across people', async () => {
- getPeople.mockResolvedValue([
+ setBrainRecords('people', [
{ id: 'p1', name: 'John Doe', context: 'Friend from school' },
{ id: 'p2', name: 'Jane Smith', context: 'Colleague at work' }
])
@@ -78,7 +84,7 @@ describe('search service', () => {
})
it('should search across projects', async () => {
- getProjects.mockResolvedValue([
+ setBrainRecords('projects', [
{ id: 'pr1', name: 'PortOS', notes: 'Personal operating system' }
])
@@ -91,7 +97,7 @@ describe('search service', () => {
})
it('should search across ideas', async () => {
- getIdeas.mockResolvedValue([
+ setBrainRecords('ideas', [
{ id: 'id1', title: 'AI assistant', oneLiner: 'Build a smart agent', notes: 'Use LLMs' }
])
@@ -104,7 +110,7 @@ describe('search service', () => {
})
it('should search across links', async () => {
- getLinks.mockResolvedValue([
+ setBrainRecords('links', [
{ id: 'l1', title: 'GitHub', url: 'https://github.com', description: 'Code hosting platform' }
])
@@ -116,6 +122,52 @@ describe('search service', () => {
expect(linkResult.type).toBe('link')
})
+ it('should search across admin items', async () => {
+ setBrainRecords('admin', [
+ { id: 'ad1', title: 'Renew registration', notes: 'Due next month', nextAction: 'Book appointment' }
+ ])
+
+ const results = await fanOutSearch('renew')
+ const brainSource = results.find(s => s.id === 'brain')
+ const adminResult = brainSource.results.find(r => r.id === 'ad1')
+ expect(adminResult).toBeDefined()
+ expect(adminResult.type).toBe('admin')
+ expect(adminResult.url).toBe('/brain/memory?type=admin&id=ad1')
+ })
+
+ it('should search across memory entries, newest first', async () => {
+ setBrainRecords('memories', [
+ { id: 'me-old', title: 'Trip notes', content: 'older recollection', updatedAt: '2020-01-01T00:00:00.000Z' },
+ { id: 'me-new', title: 'Trip recap', content: 'newer recollection', updatedAt: '2026-01-01T00:00:00.000Z' }
+ ])
+
+ const results = await fanOutSearch('recollection')
+ const brainSource = results.find(s => s.id === 'brain')
+ const memoryEntries = brainSource.results.filter(r => r.type === 'memory-entry')
+ expect(memoryEntries.map(r => r.id)).toEqual(['me-new', 'me-old'])
+ })
+
+ it('should read each brain store from disk only once across repeated queries', async () => {
+ setBrainRecords('people', [{ id: 'p1', name: 'Ada Placeholder', context: 'colleague' }])
+
+ await fanOutSearch('ada')
+ const afterFirst = getAll.mock.calls.length
+ await fanOutSearch('ada')
+ await fanOutSearch('placeholder')
+
+ // One scan per brain source on the first query; every later keystroke is
+ // served from the in-memory projection (issue #3506).
+ expect(afterFirst).toBe(7)
+ expect(getAll).toHaveBeenCalledTimes(7)
+ })
+
+ it('should not re-scan a brain store that is legitimately empty', async () => {
+ await fanOutSearch('anything')
+ await fanOutSearch('anything else')
+
+ expect(getAll).toHaveBeenCalledTimes(7)
+ })
+
it('should search apps', async () => {
getAllApps.mockResolvedValue([
{ id: 'a1', name: 'MortalLoom', description: 'Longevity tracker app' },
@@ -205,13 +257,7 @@ describe('search service', () => {
})
it('should handle failing adapters gracefully', async () => {
- getInboxLog.mockRejectedValue(new Error('DB error'))
- getPeople.mockRejectedValue(new Error('DB error'))
- getProjects.mockRejectedValue(new Error('DB error'))
- getIdeas.mockRejectedValue(new Error('DB error'))
- getAdminItems.mockRejectedValue(new Error('DB error'))
- getMemoryEntries.mockRejectedValue(new Error('DB error'))
- getLinks.mockRejectedValue(new Error('DB error'))
+ getAll.mockRejectedValue(new Error('DB error'))
searchBM25.mockRejectedValue(new Error('Index error'))
getAllApps.mockRejectedValue(new Error('App error'))
getHistory.mockRejectedValue(new Error('History error'))
@@ -223,12 +269,10 @@ describe('search service', () => {
})
it('should limit brain results to 8', async () => {
- getInboxLog.mockResolvedValue(
- Array.from({ length: 20 }, (_, i) => ({
- id: `inbox-${i}`,
- capturedText: `test entry ${i}`
- }))
- )
+ setBrainRecords('inbox', Array.from({ length: 20 }, (_, i) => ({
+ id: `inbox-${i}`,
+ capturedText: `test entry ${i}`
+ })))
const results = await fanOutSearch('test')
const brainSource = results.find(s => s.id === 'brain')