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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: tally embedding coverage from a live-id index instead of loading every brain record body (#3508)
[._.]/ Adam Eivy6cf3b5b905e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2d27c1ea91..12bc2af0f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -115,3 +115,5 @@- **[issue-3499] Background scheduler ticks no longer fire a network `git fetch` and a `gh` process at GitHub every time they check whether a plan item is claimable.** Deciding whether a PLAN.md item is already in flight means reading the repo's claim branches and open PRs, which costs a `git fetch --prune`, a `git branch -a`, and a spawned `gh pr list` — and the evaluation loop runs far more often than claim branches actually appear, so the same three processes were being spawned over and over for an answer that had not changed. The scan result is now reused for a minute per repository, which is short enough that a newly pushed claim branch is still seen within a tick or two and long enough that a burst of checks costs one scan instead of one each. What gets cached is every claimed slug in the repo rather than one caller's filtered answer, so a second caller asking about a different set of items still gets a correct result off the same scan, and callers that overlap in time share a single in-flight scan instead of racing three more processes into the same repo.- **[issue-3500] The Chief of Staff's cooldown sweep no longer re-scans its whole blocked backlog once per blocked task.** Tasks that get parked with an orphan-retry cooldown are revived by a pass that walks both task queues — the user queue and the internal one — and each revived task has to be written back to the queue it came from. That queue was being re-derived per task by searching the user queue for the task itself, a linear scan inside a linear loop, so the work grew with the square of the backlog on every scheduler tick. The two queues are now walked separately, which hands each task its origin for free and makes the sweep linear. Behavior is unchanged, including that a task carrying an explicit type still wins over the queue it was found in.++- **[issue-3508] The "N missing · Embed" badge on the Brain graph no longer reads your entire Brain off disk to compute a number.** Checking embedding coverage means counting live records and asking which of them have a vector yet — but it was answering that by loading and parsing every person, project, idea, admin item, memory entry and daily log entry in full, across every store, then throwing all of it away except each record's id. On a Brain with a few thousand records that is a few thousand file reads and JSON parses to render two integers. The tally now works from an id index instead: which record ids exist is re-read from the directory listing every time (cheap, and it is the honest source of truth for records added or hard-pruned), while whether a given record is archived or tombstoned — the part that requires opening the file — is resolved once per record and then remembered. Changes that keep a record's id, an archive flip or a delete writing a tombstone over it, drop just that one id from the index so the next count re-reads exactly one file; records arriving from a sync peer, which land deliberately silent so they cannot echo back around the network, ride the same local-only signal the search projection already uses, so an archive performed on another machine is not invisible here. The daily-log walk also loses a cap nobody meant as a policy: it used to ask for the first 10,000 days and would simply have stopped counting after that.diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 4ddb8fe255..7723d5bcc2 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -384,6 +384,13 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMi* only reports active rows (an archived/non-active mapped memory is treated as* embedded and is not a backfill target). Read-only; walks the same stores as* the onlyMissing sync so the count matches what "Embed missing" would process.+ *+ * Only IDENTITY is needed to tally — each store's live ids, checked against the+ * bridge map — so the entity/journal walks go through `brainStorage.listLiveIds`+ * rather than `getAll` / `listJournals` (issue #3508). Those loaded and parsed+ * every record body across every collection, then threw all of it away but the+ * `id` and `archived` fields, turning a status poll into hundreds of disk reads.+ * `listLiveIds` reads only the ids it has never resolved.*/export async function getEmbeddingCoverage() {const map = await loadBridgeMap();@@ -394,17 +401,16 @@ export async function getEmbeddingCoverage() {let missing = 0;const tally = (key) => { total += 1; if (!isEmbedded(key)) missing += 1; };- for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {- const records = await brainStorage.getAll(type);- for (const record of records) {- if (record.archived) continue;- tally(bridgeKey(type, record.id));- }+ // Entity stores plus the daily log — the journal record id IS its date, the+ // same key syncAllBrainData bridges under. `listLiveIds` already drops+ // tombstones and archived records, and it has no page cap (the old+ // `listJournals({ limit: 10000 })` silently stopped counting past 10k days).+ for (const type of ['people', 'projects', 'ideas', 'admin', 'memories', 'journals']) {+ for (const id of await brainStorage.listLiveIds(type)) tally(bridgeKey(type, id));}- const { records: journals } = await listJournals({ limit: 10000, includeContent: false });- for (const record of journals) tally(bridgeKey('journals', record.id));-+ // digests/reviews are append-only JSONL: one whole-file read each, behind+ // brainStorage's own cache — not a per-record disk walk, so they stay as-is.for (const [type, getter] of [['digests', brainStorage.getDigests], ['reviews', brainStorage.getReviews]]) {const records = await getter(1000);for (const record of records) tally(bridgeKey(type, record.id));diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsindex b55a4e6686..84e0a538e6 100644--- a/server/services/brainMemoryBridge.test.js+++ b/server/services/brainMemoryBridge.test.js@@ -13,8 +13,10 @@ const updateMemory = vi.fn(async () => ({ id: 'updated' }));const updateMemoryEmbedding = vi.fn(async () => {});const deleteMemory = vi.fn(async () => ({ success: true }));const generateMemoryEmbedding = vi.fn(async () => [0.1, 0.2, 0.3]);+const getMemoryIdsMissingEmbedding = vi.fn(async () => new Set());const getById = vi.fn();const getAll = vi.fn(async () => []);+const listLiveIds = vi.fn(async () => []);const getDigests = vi.fn(async () => []);const getReviews = vi.fn(async () => []);const listJournals = vi.fn(async () => ({ records: [] }));@@ -37,11 +39,13 @@ vi.mock('../lib/fileUtils.js', () => ({return writeFile(filePath, payload);}),}));-vi.mock('./memoryBackend.js', () => ({ createMemory, updateMemory, updateMemoryEmbedding, deleteMemory }));+vi.mock('./memoryBackend.js', () => ({+ createMemory, updateMemory, updateMemoryEmbedding, deleteMemory, getMemoryIdsMissingEmbedding,+}));vi.mock('./memoryEmbeddings.js', () => ({ generateMemoryEmbedding }));vi.mock('./brainStorage.js', () => {const { EventEmitter } = require('events');- return { brainEvents: new EventEmitter(), getById, getAll, getDigests, getReviews };+ return { brainEvents: new EventEmitter(), getById, getAll, listLiveIds, getDigests, getReviews };});vi.mock('./brainJournal.js', () => ({ listJournals, getJournal }));@@ -486,3 +490,58 @@ describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovexpect(updateMemory).not.toHaveBeenCalledWith('mem-live', { status: 'archived' });});});++describe('brainMemoryBridge — getEmbeddingCoverage (issue #3508)', () => {+ const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];++ beforeEach(() => {+ listLiveIds.mockImplementation(async () => []);+ getDigests.mockImplementation(async () => []);+ getReviews.mockImplementation(async () => []);+ getMemoryIdsMissingEmbedding.mockImplementation(async () => new Set());+ });++ it('tallies live ids without loading any record bodies', async () => {+ const bridge = await loadBridge();+ listLiveIds.mockImplementation(async (type) => {+ if (type === 'people') return ['p1', 'p2'];+ if (type === 'journals') return ['2026-01-01'];+ return [];+ });+ // p1 is embedded; p2 is mapped to a vector-less memory; the day is unmapped.+ bridgeFileContents = JSON.stringify({+ [bridge.bridgeKey('people', 'p1')]: 'mem-p1',+ [bridge.bridgeKey('people', 'p2')]: 'mem-p2',+ });+ getMemoryIdsMissingEmbedding.mockResolvedValue(new Set(['mem-p2']));++ expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 3, missing: 2 });++ // The whole point of the fix: identity comes from the id index, never from+ // a full-body walk of every collection.+ expect(getAll).not.toHaveBeenCalled();+ expect(listJournals).not.toHaveBeenCalled();+ for (const type of [...ENTITY_TYPES, 'journals']) {+ expect(listLiveIds).toHaveBeenCalledWith(type);+ }+ });++ it('counts the append-only JSONL logs alongside the id-indexed stores', async () => {+ const bridge = await loadBridge();+ listLiveIds.mockImplementation(async (type) => (type === 'ideas' ? ['i1'] : []));+ getDigests.mockResolvedValue([{ id: 'd1' }]);+ getReviews.mockResolvedValue([{ id: 'r1' }]);+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('digests', 'd1')]: 'mem-d1' });++ expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 3, missing: 2 });+ });++ it('treats an unreachable missing-embedding query as "nothing known missing"', async () => {+ const bridge = await loadBridge();+ listLiveIds.mockImplementation(async (type) => (type === 'admin' ? ['a1'] : []));+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('admin', 'a1')]: 'mem-a1' });+ getMemoryIdsMissingEmbedding.mockRejectedValue(new Error('backend down'));++ expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 1, missing: 0 });+ });+});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex f79c12b8d1..f02324b424 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -264,6 +264,93 @@ export async function getAll(type) {.map(([id, record]) => ({ id, ...record }));}+// ─── Live-id index (issue #3508) ────────────────────────────────────────────+// `listLiveIds(type)` answers "which record ids are live right now?" — the only+// question tally/coverage callers ask — WITHOUT re-reading and re-parsing every+// record body on every call, the way `getAll(type)` must.+//+// Cost model per call: one `listIds()` (readdir + lstat, no body reads) plus a+// `loadOne` for ids the index has never resolved. Steady state is zero body+// reads; a store the caller has already walked answers from memory.+//+// FRESHNESS — the same three signal classes brainSearchIndex documents:+// 1. Adds and hard-deletes (create, pruneTombstones) — covered by the+// `listIds()` diff itself; membership is re-read from disk every call.+// 2. IN-PLACE mutations that keep the id: an `archived` flip, or `remove()`+// writing a tombstone over the record. The id survives the diff, so these+// ride the per-record `${type}:upserted` / `${type}:deleted` events.+// 3. Event-SILENT writes — `applyRemoteRecord` (silent to prevent the #1077+// echo loop) and `upsertWithId({ emitEvent: false })` — ride the local-only+// `record:changed` invalidation signal.+//+// No `null = not built` sentinel is needed here (unlike brainSearchIndex):+// `listIds()` is the membership authority on every call, so an empty index is a+// legitimate "nothing resolved yet" state and never causes a redundant re-scan.+const liveIdIndex = Object.fromEntries(BRAIN_ENTITY_TYPES.map((type) => [type, new Map()]));+// Bumped by every invalidation, so a resolve pass that raced an invalidation is+// retried instead of writing the value it read just before the change landed.+const liveIdGeneration = Object.fromEntries(BRAIN_ENTITY_TYPES.map((type) => [type, 0]));+const LIVE_ID_MAX_ATTEMPTS = 3;++// Live = present, not a tombstone, and not archived. `loadOne` returns null for+// a missing/corrupt/unparseable record, which `getAll` also drops — so it is+// not live either.+const isLiveRecord = (record) => !!record && !isTombstone(record) && !record.archived;++function invalidateLiveId(type, id) {+ const index = liveIdIndex[type];+ if (!index || !id) return;+ index.delete(id);+ liveIdGeneration[type] += 1;+}++async function resolveLiveIds(type, attempt) {+ const store = storeFor(type);+ const index = liveIdIndex[type];+ const generation = liveIdGeneration[type];++ const ids = await store.listIds();+ const present = new Set(ids);+ for (const id of [...index.keys()]) {+ if (!present.has(id)) index.delete(id);+ }++ const unresolved = ids.filter((id) => !index.has(id));+ const loaded = await Promise.all(unresolved.map((id) => store.loadOne(id)));++ // An invalidation landed while we were reading, so what we loaded may already+ // describe the pre-change record — re-run instead of caching it. The retry+ // re-reads only the ids that invalidation dropped, so it is cheap. On the+ // final attempt we adopt what we have: a tally one write behind is better+ // than a caller that never returns.+ if (liveIdGeneration[type] !== generation && attempt + 1 < LIVE_ID_MAX_ATTEMPTS) {+ return resolveLiveIds(type, attempt + 1);+ }++ unresolved.forEach((id, i) => index.set(id, isLiveRecord(loaded[i])));+ return ids.filter((id) => index.get(id) === true);+}++/**+ * Ids of the LIVE records in a store — present, not tombstoned, not archived —+ * without loading record bodies for ids the index has already resolved.+ *+ * This is the cheap counterpart to `getAll(type).filter(r => !r.archived)` for+ * callers that only need identity (embedding-coverage tallies, membership+ * checks). Returns a fresh array in `listIds()` order each call.+ */+export function listLiveIds(type) {+ return resolveLiveIds(type, 0);+}++// Wire the freshness signals once, at module load. Invalidation only drops the+// touched id, so the next `listLiveIds` re-reads exactly one record.+for (const type of BRAIN_ENTITY_TYPES) {+ brainEvents.on(`${type}:upserted`, ({ id } = {}) => invalidateLiveId(type, id));+ brainEvents.on(`${type}:deleted`, ({ id } = {}) => invalidateLiveId(type, id));+}+brainEvents.on('record:changed', ({ type, id } = {}) => invalidateLiveId(type, id));+/*** Get the RAW records map for a store, INCLUDING tombstones, keyed by id.*@@ -975,14 +1062,19 @@ export async function backfillOriginInstanceId() {// =============================================================================/**- * Invalidate the non-collection caches (meta + JSONL logs). Entity stores read- * through to disk, so there is no entity cache to clear.+ * Invalidate the non-collection caches (meta + JSONL logs) and the live-id+ * index. Entity store BODIES still read through to disk, so there is no+ * whole-record entity cache to clear.*/export function invalidateAllCaches() {for (const key of Object.keys(caches)) {caches[key].data = null;caches[key].timestamp = 0;}+ for (const type of BRAIN_ENTITY_TYPES) {+ liveIdIndex[type].clear();+ liveIdGeneration[type] += 1;+ }}/**diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 67e87015e6..af0980b7e6 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -322,6 +322,80 @@ describe('songs entity enrollment (SongBook)', () => {});});+describe('listLiveIds (embedding-coverage id index, issue #3508)', () => {+ it('returns only live ids — archived and tombstoned records are excluded', async () => {+ const live = await brainStorage.create('ideas', { title: 'Live Idea' });+ const archived = await brainStorage.create('ideas', { title: 'Archived Idea' });+ const removed = await brainStorage.create('ideas', { title: 'Removed Idea' });+ await brainStorage.update('ideas', archived.id, { archived: true });+ await brainStorage.remove('ideas', removed.id);++ const ids = await brainStorage.listLiveIds('ideas');+ expect(ids).toContain(live.id);+ expect(ids).not.toContain(archived.id);+ expect(ids).not.toContain(removed.id);+ });++ it('serves a repeat call from the index instead of re-parsing record bodies', async () => {+ const created = await brainStorage.create('projects', { name: 'Indexed Project' });+ expect(await brainStorage.listLiveIds('projects')).toContain(created.id);++ // Flip `archived` on disk BEHIND the store — no write path, so no event.+ // A re-read would see it; the index (correctly) does not, which is exactly+ // how we prove the second call did no body read.+ await writeRawRecord('projects', created.id, { name: 'Indexed Project', archived: true });+ expect(await brainStorage.listLiveIds('projects')).toContain(created.id);++ // …and the cache is droppable.+ brainStorage.invalidateAllCaches();+ expect(await brainStorage.listLiveIds('projects')).not.toContain(created.id);+ });++ it('re-reads a single record after a local write event', async () => {+ const created = await brainStorage.create('admin', { title: 'Admin Task' });+ expect(await brainStorage.listLiveIds('admin')).toContain(created.id);++ await brainStorage.update('admin', created.id, { archived: true });+ expect(await brainStorage.listLiveIds('admin')).not.toContain(created.id);+ });++ it('re-reads after an event-SILENT peer apply (record:changed)', async () => {+ // applyRemoteRecord never emits `${type}:upserted` (that would echo back to+ // the peer, #1077) — only the local-only `record:changed` signal, so the+ // index has to be listening for it or an inbound archive goes unnoticed.+ await brainStorage.applyRemoteRecord(+ 'memories', 'peer-mem-1',+ { title: 'From Peer', updatedAt: ISO('2026-06-09'), originInstanceId: 'peer-x' },+ 'create',+ );+ expect(await brainStorage.listLiveIds('memories')).toContain('peer-mem-1');++ await brainStorage.applyRemoteRecord(+ 'memories', 'peer-mem-1',+ { title: 'From Peer', archived: true, updatedAt: ISO('2026-06-10'), originInstanceId: 'peer-x' },+ 'update',+ );+ expect(await brainStorage.listLiveIds('memories')).not.toContain('peer-mem-1');+ });++ it('picks up creates and hard-prunes from the directory listing alone', async () => {+ const first = await brainStorage.create('buckets', { name: 'Bucket One' });+ expect(await brainStorage.listLiveIds('buckets')).toContain(first.id);++ const second = await brainStorage.create('buckets', { name: 'Bucket Two' });+ const both = await brainStorage.listLiveIds('buckets');+ expect(both).toEqual(expect.arrayContaining([first.id, second.id]));+ });+});++// Overwrite a record's stored JSON directly, bypassing every brainStorage write+// path (and therefore every brainEvents signal). Used to prove the live-id index+// is answering from memory rather than re-reading the file.+async function writeRawRecord(type, id, record) {+ const { PATHS, atomicWrite } = await import('../lib/fileUtils.js');+ await atomicWrite(join(PATHS.brain, type, id, 'index.json'), record);+}+// Read the raw stored record (including tombstones) by bypassing the read// filter. getRawRecords returns the per-record map with tombstones, so this is// layout-agnostic (works against the collectionStore per-record files).