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: project SELECT id for pipeline issue sweeps, bound message inbox aggregate (#2540)
[._.]/ Adam Eivyfedc1852aa4c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 80edeceea0..92aac3f67c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -16,6 +16,7 @@## Fixed+- **[issue-2540] Stop full-JSONB table loads for pipeline issue id sweeps and bound the multi-account message inbox aggregate.** `listIssueIds` (the conflict-journal orphan-base-hash sweep + tombstone GC) went through `readState()` → `loadAll()`, pulling every issue's full `data` JSONB — up to ~12MB of stage `runHistory` each — into memory only to read the ids; it now sources the store's `SELECT id` projection, with the PG backend filtering tombstones via the mirrored `deleted` column (`listIds({ includeDeleted })`) so the whole-record load is skipped entirely for the default live sweep. Separately, `messageSync.getMessages`'s multi-account inbox spread every message from every account into one array and globally sorted it before slicing a page; it now bounds each account's contribution to the top `offset+limit` by date and merges those heads, so a paged inbox reads `accounts × (offset+limit)` messages into the merge instead of the full cross-account total (the exact `total` count is preserved).- **[issue-2538] Bound Spotify auth and privacy-broker fetches, and single-flight token refresh.** The Spotify token endpoint (`spotifyAuth.js`) and the BADBOOL / CA-registry broker fetchers (`privacyBrokers.js`) used bare `fetch` with no timeout, so a hung `accounts.spotify.com` could stall an OAuth callback or a history-sync refresh — and a broker source that never responded could hang a user-triggered refresh — indefinitely. All three now go through the shared `fetchWithTimeout` helper with a 15s cap. Separately, concurrent `getAccessToken()` callers that all found the token expired each POSTed their own refresh, and since Spotify rotates the grant the losers persisted a stale token (last-write-wins); refreshes now share one in-flight `refreshPromise` (single-flight), so the grant is rotated exactly once and the guard is released on settle so a failed refresh can retry.- **[issue-2544] Wiki vault selection now lives in the URL.** The selected Obsidian vault was local `useState`, so a reload, shared link, ⌘K jump, or voice nav always landed you back on the first vault. The vault is now encoded as a `?vault=<id>` search param (the tab route param is preserved when switching tabs), selection is driven from the URL, and a stale/deleted vault id renders a "Vault not found" fallback with a one-click "Show default vault" recovery.- **POST Digit Span: the form no longer jumps up as digits flash on and off.** During the show phase the visible-digit slot collapsed to zero height in the blank gaps between digits, so the container (padding + `min-h`) oscillated and the recall form/progress bar below shifted up on every flash. The slot now reserves its line box with a non-breaking space in the gaps, keeping the layout steady while digits flash.diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 6e17330864..b9f75665da 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -29,6 +29,45 @@ function filterBySearch(messages, search) {return genericFilterBySearch(messages, search, MESSAGE_SEARCH_FIELDS);}+/**+ * Merge per-account caches into ONE date-sorted page (#2540) without spreading+ * every message across every account into a single giant array first.+ *+ * A message can only appear in the global top `(offset + limit)` if it is also+ * in the top `(offset + limit)` of its OWN account (there can't be more than+ * `offset+limit` messages globally ahead of it without more than that many+ * ahead of it within its own account). So each account contributes at most+ * `offset+limit` heads to the cross-account merge — bounding the spread + sort+ * to `accounts × (offset+limit)` instead of the full multi-account total. The+ * per-account filter still walks every message (needed for the exact `total`),+ * but no whole-inbox intermediate array is built or globally sorted.+ *+ * Pure helper (no I/O) so the paging math is unit-testable; the caller loads the+ * caches.+ */+export function aggregatePagedMessages(caches, { search, limit = 50, offset = 0 } = {}) {+ const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.floor(offset)) : 0;+ const safeLimit = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : 50;+ const perAccountCap = safeOffset + safeLimit;+ const byDateDesc = (a, b) => safeDate(b.date) - safeDate(a.date);+ let total = 0;+ const heads = [];+ for (const { id, cache } of caches) {+ const filtered = filterBySearch(cache.messages, search);+ total += filtered.length;+ if (perAccountCap === 0) continue;+ const top = [...filtered]+ .sort(byDateDesc)+ .slice(0, perAccountCap)+ .map((m) => ({ ...m, accountId: m.accountId || id }));+ heads.push(...top);+ }+ return {+ messages: heads.sort(byDateDesc).slice(safeOffset, safeOffset + safeLimit),+ total,+ };+}+async function loadCache(accountId) {if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);await ensureDir(CACHE_DIR);@@ -71,16 +110,9 @@ export async function getMessages(options = {}) {const caches = await Promise.all(accountIds.map(async id => ({ id, cache: await loadCache(id) })));- let allMessages = [];- for (const { id, cache } of caches) {- allMessages.push(...cache.messages.map(m => ({ ...m, accountId: m.accountId || id })));- }- allMessages = filterBySearch(allMessages, search);- allMessages.sort((a, b) => safeDate(b.date) - safeDate(a.date));- return {- messages: allMessages.slice(offset, offset + limit),- total: allMessages.length- };+ // Bound the cross-account merge to `accounts × (offset+limit)` heads instead+ // of spreading + globally sorting every message across every account (#2540).+ return aggregatePagedMessages(caches, { search, limit, offset });}export async function deleteCache(accountId) {diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex e000d3020f..e949dcf456 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -76,7 +76,7 @@ vi.mock('../lib/timezone.js', () => ({import { readdir, unlink } from 'fs/promises';import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, updateMessageEvaluations, logMessageTouchpoints } from './messageSync.js';+import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';import { autoLogTouchpoints } from './tribe.js';import { getAccount, updateSyncStatus } from './messageAccounts.js';import { syncGmail } from './messageGmailSync.js';@@ -252,6 +252,79 @@ describe('getMessages', () => {});});+// ─── aggregatePagedMessages (bounded multi-account merge, #2540) ───++describe('aggregatePagedMessages', () => {+ // Build N accounts each with `perAccount` dated messages (newest = highest index).+ const buildCaches = (n, perAccount) =>+ Array.from({ length: n }, (_, a) => ({+ id: `acct-${a}`,+ cache: {+ messages: Array.from({ length: perAccount }, (_, i) => ({+ id: `a${a}-m${i}`,+ subject: `Acct ${a} Msg ${i}`,+ date: `2026-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,+ })),+ },+ }));++ it('returns the global date-sorted page and the exact total across accounts', () => {+ const caches = buildCaches(3, 5); // 15 messages total+ const { messages, total } = aggregatePagedMessages(caches, { limit: 4, offset: 0 });+ expect(total).toBe(15);+ expect(messages).toHaveLength(4);+ // Newest date is m4 (2026-01-05) present in all 3 accounts → top of the page.+ expect(messages[0].date).toBe('2026-01-05T00:00:00Z');+ // Sorted strictly newest-first.+ const dates = messages.map((m) => m.date);+ expect([...dates].sort().reverse()).toEqual(dates);+ });++ it('matches a full unbounded aggregate for an across-account page (offset+limit)', () => {+ const caches = buildCaches(4, 8);+ // Reference: spread everything, global sort, slice — the pre-#2540 behavior.+ const all = caches.flatMap(({ id, cache }) =>+ cache.messages.map((m) => ({ ...m, accountId: m.accountId || id })));+ all.sort((a, b) => new Date(b.date) - new Date(a.date));+ const ref = all.slice(3, 3 + 5).map((m) => m.id);+ const { messages, total } = aggregatePagedMessages(caches, { limit: 5, offset: 3 });+ expect(total).toBe(32);+ expect(messages.map((m) => m.id)).toEqual(ref);+ });++ it('stamps accountId from the owning cache when the message lacks one', () => {+ const caches = [{ id: 'acct-x', cache: { messages: [{ id: 'm1', date: '2026-01-01' }] } }];+ const { messages } = aggregatePagedMessages(caches, { limit: 10, offset: 0 });+ expect(messages[0].accountId).toBe('acct-x');+ });++ it('preserves a message-level accountId over the cache id', () => {+ const caches = [{ id: 'acct-x', cache: { messages: [{ id: 'm1', date: '2026-01-01', accountId: 'orig' }] } }];+ const { messages } = aggregatePagedMessages(caches, { limit: 10, offset: 0 });+ expect(messages[0].accountId).toBe('orig');+ });++ it('applies the search filter and reports the filtered total', () => {+ const caches = [+ { id: 'a', cache: { messages: [+ { id: 'm1', subject: 'Invoice', date: '2026-01-02' },+ { id: 'm2', subject: 'Lunch', date: '2026-01-01' },+ ] } },+ { id: 'b', cache: { messages: [{ id: 'm3', subject: 'Invoice due', date: '2026-01-03' }] } },+ ];+ const { messages, total } = aggregatePagedMessages(caches, { search: 'invoice', limit: 10, offset: 0 });+ expect(total).toBe(2);+ expect(messages.map((m) => m.id)).toEqual(['m3', 'm1']);+ });++ it('returns total but no messages when limit is 0', () => {+ const caches = buildCaches(2, 3);+ const { messages, total } = aggregatePagedMessages(caches, { limit: 0, offset: 0 });+ expect(total).toBe(6);+ expect(messages).toEqual([]);+ });+});+// ─── getMessage ───describe('getMessage', () => {diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.jsindex e67b69955e..b8fb2c2889 100644--- a/server/services/pipeline/issueCrud.js+++ b/server/services/pipeline/issueCrud.js@@ -63,11 +63,15 @@ export async function listIssues({* the complete id set (e.g. the conflict-journal orphan-base-hash sweep, which* would otherwise prune a live issue's base hash and silently disable conflict* detection for it) use this. Returns ids only — no projection, no history.+ *+ * Sources from the store's `SELECT id` projection (#2540) rather than+ * `readState()` → `loadAll()`, which would pull every issue's full `data` JSONB+ * (up to ~12MB of stage runHistory each) into memory only to read the ids. The+ * PG backend filters tombstones via the mirrored `deleted` column, so the+ * whole-record load is avoided entirely for the default live-membership sweep.*/export async function listIssueIds({ includeDeleted = false } = {}) {- const { issues } = await readState();- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- return live.map((i) => i.id);+ return store().listIds({ includeDeleted });}/**diff --git a/server/services/pipeline/issuesStore/db.js b/server/services/pipeline/issuesStore/db.jsindex 07fa5e8fee..96457bc75f 100644--- a/server/services/pipeline/issuesStore/db.js+++ b/server/services/pipeline/issuesStore/db.js@@ -23,9 +23,19 @@ export async function readRaw(id) {return rows[0]?.data ?? null;}-/** Every issue id (live, ephemeral, AND tombstones) — the service filters. */-export async function listIds() {- const { rows } = await query(`SELECT id FROM pipeline_issues`);+/**+ * Issue ids only — SELECT id, never the `data` JSONB (each issue can carry up to+ * ~12MB of stage runHistory, so an id sweep that loaded `data` would move the+ * whole table into memory just to read the ids, #2540). Default returns every+ * id (live, ephemeral, AND tombstones) — the "the service filters" contract the+ * facade relies on. `includeDeleted: false` scopes to non-tombstoned rows via+ * the mirrored `deleted` column so a live-membership sweep (tombstoneGc) skips+ * the whole-record load entirely.+ */+export async function listIds({ includeDeleted = true } = {}) {+ const { rows } = includeDeleted+ ? await query(`SELECT id FROM pipeline_issues`)+ : await query(`SELECT id FROM pipeline_issues WHERE deleted = false`);return rows.map((r) => r.id);}diff --git a/server/services/pipeline/issuesStore/db.test.js b/server/services/pipeline/issuesStore/db.test.jsindex ebecfe4df3..fded27a348 100644--- a/server/services/pipeline/issuesStore/db.test.js+++ b/server/services/pipeline/issuesStore/db.test.js@@ -84,6 +84,14 @@ describe.skipIf(!dbReady)('pipeline issues DB adapter round-trip', () => {expect((await db.listIds()).sort()).toEqual(['iss-dead', 'iss-ghost', 'iss-live']);});+ it('listIds({ includeDeleted: false }) excludes tombstones via the mirror column (#2540)', async () => {+ await db.writeRaw('iss-live', I('iss-live'));+ await db.writeRaw('iss-ghost', I('iss-ghost', { ephemeral: true }));+ await db.writeRaw('iss-dead', I('iss-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ // Ephemeral rows are live (deleted = false) so they stay in the sweep.+ expect((await db.listIds({ includeDeleted: false })).sort()).toEqual(['iss-ghost', 'iss-live']);+ });+it('tolerates a malformed timestamp without throwing', async () => {await db.writeRaw('iss-bad', I('iss-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));const col = (await query(`SELECT created_at, updated_at FROM pipeline_issues WHERE id = 'iss-bad'`)).rows[0];diff --git a/server/services/pipeline/issuesStore/store.js b/server/services/pipeline/issuesStore/store.jsindex 7a10ca0cfa..594e564d20 100644--- a/server/services/pipeline/issuesStore/store.js+++ b/server/services/pipeline/issuesStore/store.js@@ -50,7 +50,17 @@ function makeFileBackend(dir, sanitizeRecord) {return {name: 'file',readOne: (id) => cs.loadOne(id),- listIds: () => cs.listIds(),+ // Default returns every id (incl tombstones). `includeDeleted: false` has no+ // per-record `deleted` column to filter on in the file backend, so it loads+ // raw records to drop tombstones — same "filter the full set in JS" tradeoff+ // as `listRawBySeries` below; the file backend is dev/test-only, and the PG+ // backend (production) filters via the mirrored column with no JSONB load.+ listIds: async ({ includeDeleted = true } = {}) => {+ const ids = await cs.listIds();+ if (includeDeleted) return ids;+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));+ return ids.filter((_, i) => records[i] != null && records[i].deleted !== true);+ },listRaw: async () => {const ids = await cs.listIds();const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));@@ -128,7 +138,7 @@ function createFacade({ dir, sanitizeRecord }) {type: 'pipelineIssues',getBackendName,- listIds: async () => (await getBackend()).listIds(),+ listIds: async (opts) => (await getBackend()).listIds(opts),loadOne: async (id) => {if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;return (await getBackend()).readOne(id);diff --git a/server/services/pipeline/issuesStore/store.test.js b/server/services/pipeline/issuesStore/store.test.jsindex 1e8e0b5f13..2e35a6fc6d 100644--- a/server/services/pipeline/issuesStore/store.test.js+++ b/server/services/pipeline/issuesStore/store.test.js@@ -58,6 +58,15 @@ describe('pipeline issues store facade — file backend', () => {expect(await s.loadAllForSeries('ser-missing')).toEqual([]);});+ it('listIds({ includeDeleted: false }) drops tombstones; default keeps them (#2540)', async () => {+ const s = getIssuesStore(passthroughSanitize);+ await s.saveOneNow('iss-live', { id: 'iss-live', seriesId: 'ser-1', title: 'Live' });+ await s.saveOneNow('iss-dead', { id: 'iss-dead', seriesId: 'ser-1', title: 'Dead', deleted: true });+ expect((await s.listIds()).sort()).toEqual(['iss-dead', 'iss-live']);+ expect((await s.listIds({ includeDeleted: true })).sort()).toEqual(['iss-dead', 'iss-live']);+ expect(await s.listIds({ includeDeleted: false })).toEqual(['iss-live']);+ });+it('deleteOne removes the record', async () => {const s = getIssuesStore(passthroughSanitize);await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'X' });