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: project brain graph search index without loading full record bodies (#3507)

[._.]/ Adam Eivybcaa6560efa8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 369c461af9..ab9d6546f1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -152,3 +152,5 @@
- **[issue-3532] Deleting a social account from your Digital Twin no longer leaves your other machines to put it back.** Peer sync merged the account list add-only: whichever machine still had the account re-inserted it, so an account you removed on one machine reappeared on the next sync cycle, every cycle. A delete now records a tombstone on the account's id, and those tombstones union in both directions — so the machine that still holds the account drops it, instead of the deleting machine merely defending itself while the peer keeps re-sending. The id is the right key here, unlike the identity documents that tombstone on filename: an account id is minted once by the machine that created the account and then travels verbatim between peers, and re-adding the same handle after a delete mints a fresh id, which a platform-and-handle key would have wrongly kept suppressed. An account edited after another machine deleted it also survives — the edit is the user's later word, and the now-obsolete tombstone is dropped so it cannot bounce back from a peer that has not caught up. A peer running an older build simply ignores the new field and keeps offering its copy; the upgraded machine still refuses it, so nothing is corrupted while the two versions differ, and no migration is needed because a file without the field reads as an empty list.
- **[issue-3531] Deleting an autobiography life story no longer leaves it to be resurrected by your other machines.** Peer sync merged the stories add-only, so a story you deleted on one machine was put straight back by any machine that still had it, on the next sync cycle and every cycle after that — there was no way to permanently remove a story you had written. A delete now records a tombstone against the story, and those tombstones union in both directions, so the machine that still holds the story drops it too rather than the deleting machine merely defending itself while the peer keeps re-sending. The tombstone keys on the story's own id, which is safe here in a way it was not for identity documents: a story id is minted once when the story is written and travels with the record, so every machine knows the same story under the same id. A story that was edited after another machine deleted it is kept rather than reaped — that edit is the user's later word on it — and the now-obsolete tombstone is dropped so it cannot bounce back from a peer that has not seen the edit. A peer running an older build simply ignores the new field and keeps offering its copy; the upgraded machine still refuses it, so nothing is corrupted while the two versions differ. Two neighbouring bugs in the same merge went with it: the list of prompts you have already answered was only checked for having changed *length*, so a list that was merely in a different order than a peer's was never written back in the shared order — leaving two machines with the same prompts computing different checksums and re-syncing that file forever — and a story arriving from a peer without a usable id was filed under a blank key, where a second such story would overwrite it and neither could ever be deleted. Separately, a fresh install's first story read handed back the shared default record by reference, so anything written into it lingered in memory for the next reader; that record is now copied per read.
+
+- **[issue-3507] Opening the Brain graph's search box no longer walks every record on disk.** The graph search index returns nothing but a name and a type per node, but it was building that list by loading the *full* body of every person, project, idea, admin item and memory entry — plus every Daily Log day — and then discarding the summaries, tags and status it had just parsed. Since Brain keeps one file per record, focusing a search input meant thousands of file reads for a dropdown of labels. The index now reads the same in-memory field projections unified search uses, so it costs a scan of memory rather than a walk of the disk, and a Daily Log entry contributes only "is this day non-empty?" instead of its whole text — the biggest body in the Brain never enters the cache at all. The two graph views that genuinely need bodies (the overview and a node's neighborhood) still load them; only the label list changed, and it derives its labels and its skip rules from the same helpers the full-record path uses so the two cannot drift. Nodes come back in the same order as before: the projections are read unranked, so the memory entries in the dropdown stay in store order rather than silently re-sorting themselves newest-first.
diff --git a/server/services/brainGraph.js b/server/services/brainGraph.js
index 9152d9c41a..bc29362184 100644
--- a/server/services/brainGraph.js
+++ b/server/services/brainGraph.js
@@ -13,11 +13,19 @@
* one node's neighborhood (`getBrainGraphNeighborhood`). Shared-tag edges are
* only ever computed *among a bounded node set* and capped per node, so the
* O(n²) tag explosion can't happen.
+ *
+ * The two edge-bearing views need every record's tags and summary, so they go
+ * through `loadNodes()` (a full read of each entity store). The search index
+ * needs only `{ id, label, brainType }`, so it reads the cached field
+ * projections in `brainSearchIndex` instead — focusing the graph's search box
+ * no longer walks and JSON-parses every record body and Daily Log entry on disk
+ * (issue #3507).
*/
import * as brainStorage from './brainStorage.js';
import * as memoryBackend from './memoryBackend.js';
import { loadBridgeMap, bridgeKey } from './brainMemoryBridge.js';
+import { getBrainProjections, journalHasBody } from './brainSearchIndex.js';
import { getGoals } from './identity.js';
const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];
@@ -48,6 +56,14 @@ const clampLimit = (limit, fallback) => {
return Math.min(Math.floor(n), MAX_LIMIT);
};
+// Node identity — shared by the full-record path (`loadNodes`) and the
+// projection-backed search index, so the two can never drift on what a node is
+// called or which records are skipped.
+const entityLabel = (record) => record.name || record.title || '(untitled)';
+const goalLabel = (goal) => goal.title || '(untitled goal)';
+const isInactiveGoal = (goal) => goal.status === 'completed' || goal.status === 'abandoned';
+const journalDate = (entry) => entry.id || entry.date;
+
// Load all non-archived brain entities as graph nodes (no edges).
async function loadNodes() {
const nodes = [];
@@ -58,7 +74,7 @@ async function loadNodes() {
nodes.push({
id: record.id,
brainType: type,
- label: record.name || record.title || '(untitled)',
+ label: entityLabel(record),
summary: record.context || record.oneLiner || record.notes || record.content || '',
tags: record.tags || [],
importance: 0.6,
@@ -70,11 +86,11 @@ async function loadNodes() {
// Goals (identity system): active goals only (completed/abandoned excluded)
const goalsData = await getGoals().catch(() => null);
for (const goal of goalsData?.goals ?? []) {
- if (goal.status === 'completed' || goal.status === 'abandoned') continue;
+ if (isInactiveGoal(goal)) continue;
nodes.push({
id: goal.id,
brainType: 'goals',
- label: goal.title || '(untitled goal)',
+ label: goalLabel(goal),
summary: goal.description || '',
tags: goal.tags || [],
importance: goal.status === 'active' ? 0.75 : 0.5,
@@ -86,8 +102,8 @@ async function loadNodes() {
// Journals (Daily Log): non-empty dated entries as graph nodes
const journals = await brainStorage.getAll('journals').catch(() => []);
for (const entry of journals) {
- if (!entry.content && !entry.segments?.length) continue;
- const date = entry.id || entry.date;
+ if (!journalHasBody(entry)) continue;
+ const date = journalDate(entry);
if (!date) continue;
nodes.push({
id: date,
@@ -102,10 +118,49 @@ async function loadNodes() {
return nodes;
}
-// Lightweight index for the client-side search box — every node, no edges.
+/**
+ * Lightweight index for the client-side search box — every node, no edges.
+ *
+ * Deliberately does NOT go through `loadNodes()`: that reads the full body of
+ * every entity record and Daily Log entry only to throw the summaries and tags
+ * away here. Instead it reads `brainSearchIndex`'s cached field projections, so
+ * the endpoint costs an in-memory scan after the first call and never parses a
+ * record body it doesn't render. Node set, labels, and order are identical to
+ * the `loadNodes()` derivation — the label/skip rules are the shared helpers
+ * above, and `ranked: false` keeps each store's natural order.
+ *
+ * Goals still come from `getGoals()`: identity keeps them in ONE file, so
+ * there is no per-record walk to avoid.
+ */
export async function getBrainGraphSearchIndex() {
- const nodes = await loadNodes();
- return { nodes: nodes.map(n => ({ id: n.id, label: n.label, brainType: n.brainType })) };
+ const nodes = [];
+
+ // Independent stores — read them together, then emit in ENTITY_TYPES order so
+ // the node order matches the `loadNodes()` derivation. A store that fails
+ // still rejects the request, exactly as the full-record path does.
+ const perType = await Promise.all(ENTITY_TYPES.map((type) => getBrainProjections(type, { ranked: false })));
+ perType.forEach((records, i) => {
+ for (const record of records) {
+ if (record.archived) continue;
+ nodes.push({ id: record.id, label: entityLabel(record), brainType: ENTITY_TYPES[i] });
+ }
+ });
+
+ const goalsData = await getGoals().catch(() => null);
+ for (const goal of goalsData?.goals ?? []) {
+ if (isInactiveGoal(goal)) continue;
+ nodes.push({ id: goal.id, label: goalLabel(goal), brainType: 'goals' });
+ }
+
+ const journals = await getBrainProjections('journals', { ranked: false }).catch(() => []);
+ for (const entry of journals) {
+ if (!entry.hasBody) continue;
+ const date = journalDate(entry);
+ if (!date) continue;
+ nodes.push({ id: date, label: date, brainType: 'journals' });
+ }
+
+ return { nodes };
}
// Build the shared graph context once: nodes + tag index + remapped
diff --git a/server/services/brainGraph.test.js b/server/services/brainGraph.test.js
index 416e4db419..eebf40ca8b 100644
--- a/server/services/brainGraph.test.js
+++ b/server/services/brainGraph.test.js
@@ -1,7 +1,13 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import EventEmitter from 'events';
+// `brainSearchIndex` (which the search-index path reads through) subscribes to
+// brainEvents and uses the memories recency ranker, so the mock has to carry
+// both alongside `getAll`.
vi.mock('./brainStorage.js', () => ({
- getAll: vi.fn()
+ getAll: vi.fn(),
+ brainEvents: new EventEmitter(),
+ memoryRecencyMs: (record) => Date.parse(record?.updatedAt ?? '') || 0
}));
vi.mock('./memoryBackend.js', () => ({
@@ -21,6 +27,7 @@ import * as brainStorage from './brainStorage.js';
import * as memoryBackend from './memoryBackend.js';
import { loadBridgeMap } from './brainMemoryBridge.js';
import { getGoals } from './identity.js';
+import { getBrainProjections, __resetBrainSearchIndex } from './brainSearchIndex.js';
import {
getBrainGraphSearchIndex,
getBrainGraphOverview,
@@ -29,12 +36,15 @@ import {
beforeEach(() => {
vi.clearAllMocks();
+ __resetBrainSearchIndex();
loadBridgeMap.mockResolvedValue({});
memoryBackend.getGraphData.mockResolvedValue(null);
brainStorage.getAll.mockResolvedValue([]);
getGoals.mockResolvedValue({ goals: [] });
});
+const byId = (a, b) => a.id.localeCompare(b.id);
+
// A small node set fits entirely inside one overview page, so getBrainGraphOverview
// with a generous limit exercises the same edge-derivation the full graph used to.
const onlyType = (wanted, records) =>
@@ -60,6 +70,100 @@ describe('getBrainGraphSearchIndex', () => {
const { nodes } = await getBrainGraphSearchIndex();
expect(nodes.map(n => n.id)).toEqual(['p1']);
});
+
+ // The projection path (#3507) must derive exactly what the full-record path
+ // derives — same node set, same labels, same brainTypes.
+ it('matches the full-record derivation node-for-node', async () => {
+ brainStorage.getAll.mockImplementation(async (type) => {
+ if (type === 'people') return [
+ { id: 'p1', name: 'Ada Placeholder', tags: ['x'] },
+ { id: 'p2', name: 'Archived', tags: [], archived: true }
+ ];
+ if (type === 'projects') return [{ id: 'pr1', title: 'Example Project', tags: [] }];
+ if (type === 'ideas') return [{ id: 'i1', tags: [] }];
+ if (type === 'admin') return [{ id: 'ad1', title: 'Renew registration', tags: [] }];
+ if (type === 'memories') return [{ id: 'm1', name: 'A memory', tags: [] }];
+ return [];
+ });
+ getGoals.mockResolvedValue({ goals: [
+ { id: 'g1', title: 'Active goal', status: 'active' },
+ { id: 'g2', title: 'Done goal', status: 'completed' }
+ ] });
+
+ // getBrainGraphOverview runs the full loadNodes() path; a generous limit
+ // keeps every node, so its node set is the reference derivation.
+ const overview = await getBrainGraphOverview({ limit: 250 });
+ const fullPath = overview.nodes
+ .map(n => ({ id: n.id, label: n.label, brainType: n.brainType }))
+ .sort(byId);
+
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes.slice().sort(byId)).toEqual(fullPath);
+ expect(nodes).toHaveLength(6);
+ });
+
+ it('emits nodes in entity-type order, then goals, then journals', async () => {
+ brainStorage.getAll.mockImplementation(async (type) => {
+ if (type === 'memories') return [{ id: 'm1', name: 'M' }];
+ if (type === 'people') return [{ id: 'p1', name: 'P' }];
+ if (type === 'journals') return [{ id: '2026-01-01', content: 'Hello' }];
+ return [];
+ });
+ getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'G', status: 'active' }] });
+
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes.map(n => n.id)).toEqual(['p1', 'm1', 'g1', '2026-01-01']);
+ });
+
+ it('keeps memories in store order rather than the ranked search order', async () => {
+ onlyType('memories', [
+ { id: 'older', name: 'Older', updatedAt: '2026-01-01T00:00:00.000Z' },
+ { id: 'newer', name: 'Newer', updatedAt: '2026-02-01T00:00:00.000Z' }
+ ]);
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes.map(n => n.id)).toEqual(['older', 'newer']);
+ });
+
+ it('reads each store once and serves repeat requests from the projections', async () => {
+ onlyType('people', [{ id: 'p1', name: 'A' }]);
+
+ await getBrainGraphSearchIndex();
+ // 5 entity types + journals, one scan each.
+ expect(brainStorage.getAll).toHaveBeenCalledTimes(6);
+
+ await getBrainGraphSearchIndex();
+ expect(brainStorage.getAll).toHaveBeenCalledTimes(6);
+ });
+
+ it('keeps unrendered payloads and journal bodies out of the projections it reads', async () => {
+ brainStorage.getAll.mockImplementation(async (type) => {
+ if (type === 'memories') return [{
+ id: 'm1',
+ name: 'A memory',
+ content: 'x'.repeat(500),
+ embedding: [1, 2, 3],
+ attachments: [{ blob: 'y'.repeat(500) }]
+ }];
+ if (type === 'journals') return [{
+ id: '2026-01-01',
+ content: 'z'.repeat(5000),
+ segments: [{ text: 'z'.repeat(5000) }]
+ }];
+ return [];
+ });
+
+ await getBrainGraphSearchIndex();
+
+ const [memory] = await getBrainProjections('memories', { ranked: false });
+ expect(memory.embedding).toBeUndefined();
+ expect(memory.attachments).toBeUndefined();
+
+ // The Daily Log body is the biggest record in the brain — the graph only
+ // needs "is this day non-empty?", so the text must never reach the cache.
+ expect(await getBrainProjections('journals', { ranked: false })).toEqual([
+ { id: '2026-01-01', date: undefined, hasBody: true }
+ ]);
+ });
});
describe('getBrainGraphOverview', () => {
diff --git a/server/services/brainSearchIndex.js b/server/services/brainSearchIndex.js
index 5013d06b6f..873460b2a2 100644
--- a/server/services/brainSearchIndex.js
+++ b/server/services/brainSearchIndex.js
@@ -3,7 +3,9 @@
*
* 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).
+ * re-parsing every record file on disk (issue #3506), and so the brain graph's
+ * search index (`brainGraph.getBrainGraphSearchIndex`) can answer the graph
+ * search box without a full-body disk walk (issue #3507).
*
* Brain entity stores are per-record `collectionStore` dirs
* (`data/brain/<type>/<id>/index.json`) with NO whole-store cache — every
@@ -14,9 +16,11 @@
* 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
+ * Only the fields a consumer actually reads (plus the ordering key) are
* projected — the index holds no attachments, embeddings, or classification
- * payloads.
+ * payloads. A consumer that needs a *predicate* over a large body (the Daily
+ * Log's `content`/`segments`) gets a derived boolean instead, so the body never
+ * enters the cache.
*
* FRESHNESS — three signal classes, all of them covered:
* 1. `${type}:upserted` / `${type}:deleted` — the per-record events every
@@ -36,20 +40,54 @@
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({
+/**
+ * The projected fields per indexed brain type — the union of what every
+ * consumer reads:
+ * - `searchBrain` (server/services/search.js) matches on and renders snippets
+ * from `capturedText` / `name` / `context` / `title` / `oneLiner` / `notes`
+ * / `nextAction` / `content` / `mood` / `url` / `description`.
+ * - `getBrainGraphSearchIndex` (server/services/brainGraph.js) derives each
+ * node's label from `name || title` and drops archived records, so the five
+ * graph entity types also project `name`, `title` and `archived`.
+ * `journals` is graph-only (the Daily Log is not a unified-search source), and
+ * projects no body — see `journalHasBody` below.
+ */
+const PROJECTED_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']),
+ people: Object.freeze(['name', 'title', 'context', 'archived']),
+ projects: Object.freeze(['name', 'title', 'notes', 'archived']),
+ ideas: Object.freeze(['name', 'title', 'oneLiner', 'notes', 'archived']),
+ admin: Object.freeze(['name', 'title', 'notes', 'nextAction', 'archived']),
+ memories: Object.freeze(['name', 'title', 'content', 'mood', 'archived']),
links: Object.freeze(['title', 'url', 'description']),
+ journals: Object.freeze(['date']),
+});
+
+/**
+ * Is this Daily Log entry non-empty? The graph only asks the question — it
+ * never renders the answer's source — and a journal body is the largest record
+ * in the brain, so the predicate is projected and `content`/`segments` are not.
+ * Exported so `brainGraph`'s full-record path (which still loads bodies, for
+ * summaries and tags) applies the identical rule.
+ */
+export const journalHasBody = (record) => !!(record?.content || record?.segments?.length);
+
+// Fields computed from the record rather than copied off it, per type.
+const DERIVED_FIELDS = Object.freeze({
+ journals: Object.freeze({ hasBody: journalHasBody }),
});
-/** The brain entity types this index covers. */
-export const BRAIN_SEARCH_TYPES = Object.freeze(Object.keys(SEARCH_FIELDS));
+/**
+ * The brain entity types unified search reads. A strict subset of
+ * `BRAIN_PROJECTION_TYPES` — every source `search.js` fans out to must be
+ * indexed here or its `getBrainProjections` call throws.
+ */
+export const BRAIN_SEARCH_TYPES = Object.freeze([
+ 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links',
+]);
+
+/** Every brain entity type this index projects (search sources + graph-only). */
+export const BRAIN_PROJECTION_TYPES = Object.freeze(Object.keys(PROJECTED_FIELDS));
// Newest-first ordering key, for the two types whose reader sorted before
// handing records to search: inbox by capture time, memories by the
@@ -76,7 +114,7 @@ const generation = {};
const building = {};
function resetState() {
- for (const type of BRAIN_SEARCH_TYPES) {
+ for (const type of BRAIN_PROJECTION_TYPES) {
cache[type] = null;
generation[type] = 0;
delete building[type];
@@ -86,9 +124,12 @@ resetState();
function project(type, record) {
const projection = { id: record.id };
- for (const field of SEARCH_FIELDS[type]) {
+ for (const field of PROJECTED_FIELDS[type]) {
projection[field] = record[field];
}
+ for (const [field, derive] of Object.entries(DERIVED_FIELDS[type] ?? {})) {
+ projection[field] = derive(record);
+ }
const ranker = RANKERS[type];
if (ranker) projection._rank = ranker(record);
return projection;
@@ -135,12 +176,17 @@ function patchDelete(type, id) {
* 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.
+ *
+ * `ranked: false` keeps store order for a type that HAS a ranker. The brain
+ * graph's node list is built from `brainStorage.getAll()` order, so the graph
+ * search index opts out rather than silently reordering its `memories` nodes.
*/
-export async function getBrainProjections(type) {
- if (!(type in cache)) throw new Error(`brainSearchIndex: unknown search type "${type}"`);
+export async function getBrainProjections(type, { ranked = true } = {}) {
+ if (!(type in cache)) throw new Error(`brainSearchIndex: unknown projection type "${type}"`);
+ const order = (projections) => (ranked ? sortProjections(type, projections) : projections);
const cached = cache[type];
- if (cached) return sortProjections(type, [...cached.values()]);
+ if (cached) return order([...cached.values()]);
if (!building[type]) {
const startedAt = generation[type];
@@ -155,11 +201,11 @@ export async function getBrainProjections(type) {
}
const map = await building[type];
- return sortProjections(type, [...map.values()]);
+ return order([...map.values()]);
}
// Wire the freshness signals once, at module load.
-for (const type of BRAIN_SEARCH_TYPES) {
+for (const type of BRAIN_PROJECTION_TYPES) {
brainEvents.on(`${type}:upserted`, ({ record } = {}) => patchUpsert(type, record));
brainEvents.on(`${type}:deleted`, ({ id } = {}) => patchDelete(type, id));
}
diff --git a/server/services/brainSearchIndex.test.js b/server/services/brainSearchIndex.test.js
index b441f69072..1a7df9b74f 100644
--- a/server/services/brainSearchIndex.test.js
+++ b/server/services/brainSearchIndex.test.js
@@ -7,7 +7,12 @@ vi.mock('./brainStorage.js', () => ({
memoryRecencyMs: (record) => Date.parse(record?.updatedAt ?? '') || 0
}))
-import { getBrainProjections, BRAIN_SEARCH_TYPES, __resetBrainSearchIndex } from './brainSearchIndex.js'
+import {
+ getBrainProjections,
+ BRAIN_SEARCH_TYPES,
+ BRAIN_PROJECTION_TYPES,
+ __resetBrainSearchIndex
+} from './brainSearchIndex.js'
import { getAll, brainEvents } from './brainStorage.js'
const deferred = () => {
@@ -29,17 +34,51 @@ describe('brainSearchIndex', () => {
])
})
+ it('indexes every search source plus the graph-only journals type', () => {
+ for (const type of BRAIN_SEARCH_TYPES) {
+ expect(BRAIN_PROJECTION_TYPES).toContain(type)
+ }
+ expect(BRAIN_PROJECTION_TYPES).toContain('journals')
+ })
+
it('rejects a type it does not index', async () => {
- await expect(getBrainProjections('journals')).rejects.toThrow(/unknown search type/)
+ await expect(getBrainProjections('songs')).rejects.toThrow(/unknown projection type/)
})
- it('projects only the searched fields', async () => {
+ it('projects only the fields its consumers read', 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' })
+ expect(projection).not.toHaveProperty('avatarBlob')
+ expect(projection).not.toHaveProperty('embedding')
+ })
+
+ it('projects a journal entry as a body predicate, never the body', async () => {
+ getAll.mockResolvedValue([
+ { id: '2026-01-01', content: 'x'.repeat(500), segments: [{ text: 'x' }] },
+ { id: '2026-01-02', content: '', segments: [] },
+ { id: '2026-01-03', content: '', segments: [{ text: 'voice note' }] }
+ ])
+
+ expect(await getBrainProjections('journals')).toEqual([
+ { id: '2026-01-01', date: undefined, hasBody: true },
+ { id: '2026-01-02', date: undefined, hasBody: false },
+ { id: '2026-01-03', date: undefined, hasBody: true }
+ ])
+ })
+
+ it('keeps store order when the caller opts out of ranking', async () => {
+ getAll.mockResolvedValue([
+ { id: 'older', title: 'Older', updatedAt: '2026-01-01T00:00:00.000Z' },
+ { id: 'newer', title: 'Newer', updatedAt: '2026-02-01T00:00:00.000Z' }
+ ])
+
+ expect((await getBrainProjections('memories')).map((p) => p.id)).toEqual(['newer', 'older'])
+ expect((await getBrainProjections('memories', { ranked: false })).map((p) => p.id))
+ .toEqual(['older', 'newer'])
})
it('scans the store once and serves later reads from memory', async () => {