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: serve a page of brain links from a cached summary index instead of reading every link (#3509)
[._.]/ Adam Eivy15c07d56b320
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6f9112cb1c..9dad53bd42 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -123,3 +123,5 @@- **[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.- **[issue-3501] Daily agent reports for past dates read as all-zero, and the dashboard's activity card re-scanned every agent you have ever run.** Both the daily report and the "today" activity card worked out which agents finished on a given date by walking the entire in-memory agent dictionary and string-matching each record's completion timestamp — so the cost grew with your whole agent history rather than with the day being asked about, and once the housekeeping sweep had evicted a day's finished agents out of live state (it keeps roughly a day), asking for that date's report returned zeros even though every one of those runs was still sitting on disk. Both now consult the date-bucket index that already maps each archived agent to its day: the index is a small in-memory id-to-date map, so a date whose agents are all still live costs no disk reads at all, and a date that has been swept out resolves from the archive instead of reporting nothing. Live records still win over their archived copies, since the archive is written at completion time and the live one carries anything recorded since. The "while you were away" card is built on the same lookup now, which also stops it re-reading up to thirty days of archives on every poll for agents it already had in hand. Asking for a report by anything other than a plain calendar day is now rejected outright rather than quietly writing an empty report under a filename nothing can read back, and a report row's duration is derived the same way every other view derives it, so a clock-skewed run can no longer show negative time.++- **[issue-3509] Opening your Bookmarks no longer reads and re-sorts every link you have ever saved.** Answering a single page of `/brain/links` meant loading and JSON-parsing every link record on disk, filtering the whole array in memory, sorting all of it by date, and then throwing away everything outside the fifty rows actually asked for — so the cost of showing page one grew with the size of the entire collection rather than with the size of the page. The links list now rides a small in-memory index of just the four fields the endpoint orders, filters, and counts on, refreshed per record as links change rather than rebuilt per request, so only the requested page's records are opened. The filters keep their exact previous meaning, including that a link saved before the GitHub flag existed still does not match "not a GitHub repo" — absent is not the same as false. Links sharing a timestamp, which is every link from one bulk import, are now ordered by id underneath the date so paging through them cannot skip or repeat a row at a page boundary, and a link with a missing or unreadable date sorts last instead of scrambling the order around it. Two neighbouring paths lost the same whole-collection read: checking that a drag-reorder batch refers to links that still exist, and checking whether a URL you are about to save is already bookmarked.diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 083d12a111..0aa2a290f2 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -57,6 +57,8 @@ vi.mock('../services/brain.js', () => ({getSummary: vi.fn(),// LinksgetLinks: vi.fn(),+ getLinksPage: vi.fn(),+ listLinkIds: vi.fn(),getLinkById: vi.fn(),getLinkByUrl: vi.fn(),createLinkFromUrl: vi.fn(),@@ -1437,7 +1439,7 @@ describe('Brain Routes', () => {{ id: idB, bucketId: bucket, bucketOrder: 0 },{ id: idA, bucketId: bucket, bucketOrder: 1 }];- brainService.getLinks.mockResolvedValue([{ id: idA }, { id: idB }]);+ brainService.listLinkIds.mockResolvedValue([idA, idB]);brainService.reorderLinks.mockResolvedValue(updates.map(u => ({ ...u, url: 'x' })));const res = await request(app).post('/api/brain/links/reorder').send({ updates });expect(res.status).toBe(200);@@ -1455,7 +1457,7 @@ describe('Brain Routes', () => {});it('rejects the whole batch (no write) when any id is unknown', async () => {- brainService.getLinks.mockResolvedValue([{ id: idA }]); // idB no longer exists+ brainService.listLinkIds.mockResolvedValue([idA]); // idB no longer existsconst res = await request(app).post('/api/brain/links/reorder').send({updates: [{ id: idA, bucketId: bucket, bucketOrder: 0 },@@ -1467,7 +1469,7 @@ describe('Brain Routes', () => {});it('is matched before /links/:id so "reorder" is not treated as an id', async () => {- brainService.getLinks.mockResolvedValue([{ id: idA }]);+ brainService.listLinkIds.mockResolvedValue([idA]);brainService.reorderLinks.mockResolvedValue([]);const res = await request(app).post('/api/brain/links/reorder')diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.jsindex 4ba4484f56..4a8cadea1b 100644--- a/server/routes/brainLinks.js+++ b/server/routes/brainLinks.js@@ -37,23 +37,10 @@ const router = Router();*/router.get('/links', asyncHandler(async (req, res) => {const { linkType, isGitHubRepo, limit, offset } = validateRequest(linksQuerySchema, req.query);- let links = await brainService.getLinks();-- // Apply filters- if (linkType) {- links = links.filter(l => l.linkType === linkType);- }- if (isGitHubRepo !== undefined) {- links = links.filter(l => l.isGitHubRepo === isGitHubRepo);- }-- // Sort by createdAt descending- links.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));-- // Apply pagination- const total = links.length;- links = links.slice(offset, offset + limit);-+ // Filtering, newest-first ordering, and the total count are answered from+ // brainStorage's cached link-summary index, so only THIS page's records are+ // read and parsed from disk (issue #3509) — not the whole collection.+ const { links, total } = await brainService.getLinksPage({ linkType, isGitHubRepo, limit, offset });res.json({ links, total, limit, offset });}));@@ -69,7 +56,9 @@ router.post('/links/reorder', asyncHandler(async (req, res) => {// All-or-nothing: reject before any write if a batch references a link that// no longer exists, so the response can't report success after a partial// apply (mirrors the single-link PUT's 404 on an unknown id).- const known = new Set((await brainService.getLinks()).map(l => l.id));+ // Membership only — `listLinkIds` answers it from the summary index instead+ // of parsing every link body (issue #3509).+ const known = new Set(await brainService.listLinkIds());const missing = updates.filter(u => !known.has(u.id)).map(u => u.id);if (missing.length) {throw new ServerError('Unknown link id in reorder batch', {diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.jsnew file mode 100644index 0000000000..7bf172ea9c--- /dev/null+++ b/server/routes/brainLinks.test.js@@ -0,0 +1,161 @@+/**+ * GET /api/brain/links — the paginated read path (issue #3509).+ *+ * The route used to pull EVERY link record through `getLinks()`, then filter,+ * sort, and slice in memory: page cost scaled with the size of the whole+ * collection. These tests pin the replacement contract — the route hands the+ * filters and the window to `getLinksPage` and returns what it gets, and never+ * reaches for the whole collection.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/brain.js', () => ({+ getLinks: vi.fn(),+ getLinksPage: vi.fn(),+ listLinkIds: vi.fn(),+ getLinkById: vi.fn(),+ getLinkByUrl: vi.fn(),+ createLinkFromUrl: vi.fn(),+ updateLink: vi.fn(),+ reorderLinks: vi.fn(),+ deleteLink: vi.fn(),+ cloneRepoInBackground: vi.fn(),+ getBuckets: vi.fn(),+ getBucketById: vi.fn(),+ createBucketAppended: vi.fn(),+ updateBucket: vi.fn(),+ deleteBucketAndUnlinkChildren: vi.fn(),+}));++vi.mock('../services/githubCloner.js', () => ({+ parseGitHubUrl: vi.fn(() => null),+ pullRepo: vi.fn(),+}));++vi.mock('../services/cos.js', () => ({ addTask: vi.fn() }));++vi.mock('../services/malwareScanReports.js', () => ({+ prepareScanReportDirectory: vi.fn(),+ reportPathForId: vi.fn(() => '/tmp/report.md'),+ getScanReport: vi.fn(),+}));++vi.mock('../lib/openFolder.js', () => ({ openFolderInSystemExplorer: vi.fn() }));++import * as brainService from '../services/brain.js';+import linkRoutes from './brainLinks.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/brain', linkRoutes);+ app.use(errorMiddleware);+ return app;+};++const app = buildApp();++const link = (id, extra = {}) => ({ id, url: `https://example.com/${id}`, ...extra });++beforeEach(() => {+ vi.clearAllMocks();+ brainService.getLinksPage.mockResolvedValue({ links: [], total: 0 });+});++describe('GET /api/brain/links', () => {+ it('returns the service page verbatim alongside the echoed window', async () => {+ brainService.getLinksPage.mockResolvedValue({ links: [link('a'), link('b')], total: 137 });++ const res = await request(app).get('/api/brain/links?limit=2&offset=10');++ expect(res.status).toBe(200);+ expect(res.body.links.map(l => l.id)).toEqual(['a', 'b']);+ // `total` is the count of everything MATCHING the filters, not the page size.+ expect(res.body).toMatchObject({ total: 137, limit: 2, offset: 10 });+ });++ it('delegates filtering, ordering, and pagination to getLinksPage', async () => {+ await request(app).get('/api/brain/links?linkType=github&isGitHubRepo=true&limit=25&offset=50');++ expect(brainService.getLinksPage).toHaveBeenCalledTimes(1);+ expect(brainService.getLinksPage).toHaveBeenCalledWith({+ linkType: 'github',+ isGitHubRepo: true,+ limit: 25,+ offset: 50,+ });+ });++ it('never pulls the whole collection to answer a page', async () => {+ brainService.getLinksPage.mockResolvedValue({ links: [link('a')], total: 5000 });++ const res = await request(app).get('/api/brain/links?limit=1');++ expect(res.status).toBe(200);+ expect(res.body.links).toHaveLength(1);+ // The O(N) read path is gone — this is the regression guard for #3509.+ expect(brainService.getLinks).not.toHaveBeenCalled();+ });++ it('applies the schema defaults when no window is given', async () => {+ await request(app).get('/api/brain/links');++ expect(brainService.getLinksPage).toHaveBeenCalledWith({+ linkType: undefined,+ isGitHubRepo: undefined,+ limit: 50,+ offset: 0,+ });+ });++ it('passes isGitHubRepo=false through as a boolean, not a truthy string', async () => {+ await request(app).get('/api/brain/links?isGitHubRepo=false');++ expect(brainService.getLinksPage).toHaveBeenCalledWith(+ expect.objectContaining({ isGitHubRepo: false }),+ );+ });++ it('rejects an out-of-range limit before touching the service', async () => {+ const res = await request(app).get('/api/brain/links?limit=999999');++ expect(res.status).toBe(400);+ expect(brainService.getLinksPage).not.toHaveBeenCalled();+ });+});++describe('POST /api/brain/links/reorder', () => {+ const idA = '11111111-1111-4111-8111-111111111111';+ const idB = '22222222-2222-4222-8222-222222222222';+ const bucket = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';++ it('checks batch membership from the id listing, not the full records', async () => {+ const updates = [{ id: idA, bucketId: bucket, bucketOrder: 0 }];+ brainService.listLinkIds.mockResolvedValue([idA, idB]);+ brainService.reorderLinks.mockResolvedValue(updates);++ const res = await request(app).post('/api/brain/links/reorder').send({ updates });++ expect(res.status).toBe(200);+ expect(brainService.getLinks).not.toHaveBeenCalled();+ expect(brainService.reorderLinks).toHaveBeenCalledWith(updates);+ });++ it('still rejects the whole batch when an id is unknown', async () => {+ brainService.listLinkIds.mockResolvedValue([idA]);++ const res = await request(app).post('/api/brain/links/reorder').send({+ updates: [+ { id: idA, bucketId: bucket, bucketOrder: 0 },+ { id: idB, bucketId: bucket, bucketOrder: 1 },+ ],+ });++ expect(res.status).toBe(404);+ expect(brainService.reorderLinks).not.toHaveBeenCalled();+ });+});diff --git a/server/services/brain.js b/server/services/brain.jsindex a853583a37..2d8ffa63b2 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -876,6 +876,10 @@ export async function deleteMemoryEntry(id) {}export const getLinks = storage.getLinks;+// Paginated read path — filters/sorts/counts off the cached link summary index+// and loads only the requested page's bodies (issue #3509).+export const getLinksPage = storage.getLinksPage;+export const listLinkIds = storage.listLinkIds;export const getLinkById = storage.getLinkById;export const getLinkByUrl = storage.getLinkByUrl;export const updateLink = storage.updateLink;diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 6bfce4ad0d..fa20e65251 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -47,6 +47,8 @@ vi.mock('./brainStorage.js', () => {getAdminById: vi.fn(),deleteAdminItem: vi.fn(),getLinks: vi.fn(),+ getLinksPage: vi.fn(),+ listLinkIds: vi.fn(),getLinkById: vi.fn(),getLinkByUrl: vi.fn(),createLink: vi.fn(),diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex c1cc0fda65..85d7bccf46 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -264,10 +264,11 @@ 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.+// ─── Per-record projection indexes (issues #3508, #3509) ────────────────────+// A projection index answers one question about EVERY record in a store — "is+// this id live?" (#3508), "what are this link's sort/filter keys?" (#3509) —+// 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@@ -286,30 +287,51 @@ export async function getAll(type) {// 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;+const RECORD_INDEX_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;+// Every index registers itself here so ONE invalidation drops the touched id+// from all of them — an index that missed a signal would serve a stale+// projection until the next unrelated change to that record.+const recordIndexes = [];++/**+ * Build a per-type projection index. `project(record)` maps the parsed on-disk+ * record (or `null` for a missing/corrupt one) to the value to cache for that+ * id. Registers itself for invalidation; call `resolveRecordIndex` to read it.+ */+function createRecordIndex(project) {+ const index = {+ project,+ byType: 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.+ generation: Object.fromEntries(BRAIN_ENTITY_TYPES.map((type) => [type, 0])),+ };+ recordIndexes.push(index);+ return index;+}-function invalidateLiveId(type, id) {- const index = liveIdIndex[type];- if (!index || !id) return;- index.delete(id);- liveIdGeneration[type] += 1;+function invalidateRecordIndexes(type, id) {+ if (!id) return;+ for (const index of recordIndexes) {+ const byType = index.byType[type];+ if (!byType) continue;+ byType.delete(id);+ index.generation[type] += 1;+ }}-async function resolveLiveIds(type, attempt) {- // `storeFor` throws for an unknown type, and both maps are keyed off the same- // BRAIN_ENTITY_TYPES list — so past this line `liveIdIndex[type]` exists.+/**+ * Resolve a projection index for one store. Returns `[id, value]` pairs in+ * `listIds()` order — every present id, including ones whose projection is+ * `null` (callers decide what a null projection means).+ */+async function resolveRecordIndex(indexState, type, attempt) {+ // `storeFor` throws for an unknown type, and the index maps are keyed off the+ // same BRAIN_ENTITY_TYPES list — so past this line `byType[type]` exists.const store = storeFor(type);- const index = liveIdIndex[type];- const generation = liveIdGeneration[type];+ const index = indexState.byType[type];+ const generation = indexState.generation[type];const ids = await store.listIds();const present = new Set(ids);@@ -319,32 +341,38 @@ async function resolveLiveIds(type, attempt) {const unresolved = ids.filter((id) => !index.has(id));const loaded = await Promise.all(unresolved.map((id) => store.loadOne(id)));- const verdicts = new Map(unresolved.map((id, i) => [id, isLiveRecord(loaded[i])]));+ const resolved = new Map(unresolved.map((id, i) => [id, indexState.project(loaded[i])]));// An invalidation landed while we were reading, so what we loaded may already// describe the pre-change record. Re-run — the retry re-reads only the ids the// invalidation dropped, so it is cheap. Past the attempt ceiling we answer- // from what we have but do NOT write it into the index: caching a verdict we+ // from what we have but do NOT write it into the index: caching a value we// know raced would strand it there until the next change to that record.- const raced = liveIdGeneration[type] !== generation;- if (raced && attempt + 1 < LIVE_ID_MAX_ATTEMPTS) {- return resolveLiveIds(type, attempt + 1);+ const raced = indexState.generation[type] !== generation;+ if (raced && attempt + 1 < RECORD_INDEX_MAX_ATTEMPTS) {+ return resolveRecordIndex(indexState, type, attempt + 1);}if (raced) {// Ceiling reached. The invalidation may also have dropped ids this pass// took FROM the index (so they were never in `unresolved`) — read those// before answering, or a record we merely stopped knowing about would be- // reported as not live and undercount the tally.- const unknown = ids.filter((id) => !verdicts.has(id) && !index.has(id));+ // reported as absent and undercount the result.+ const unknown = ids.filter((id) => !resolved.has(id) && !index.has(id));const reloaded = await Promise.all(unknown.map((id) => store.loadOne(id)));- unknown.forEach((id, i) => verdicts.set(id, isLiveRecord(reloaded[i])));+ unknown.forEach((id, i) => resolved.set(id, indexState.project(reloaded[i])));} else {- for (const [id, live] of verdicts) index.set(id, live);+ for (const [id, value] of resolved) index.set(id, value);}- return ids.filter((id) => (verdicts.has(id) ? verdicts.get(id) : index.get(id)) === true);+ return ids.map((id) => [id, resolved.has(id) ? resolved.get(id) : index.get(id)]);}+// 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;+const liveIdIndex = createRecordIndex(isLiveRecord);+/*** Ids of the LIVE records in a store — present, not tombstoned, not archived —* without loading record bodies for ids the index has already resolved.@@ -353,12 +381,13 @@ async function resolveLiveIds(type, attempt) {* 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);+export async function listLiveIds(type) {+ const rows = await resolveRecordIndex(liveIdIndex, type, 0);+ return rows.filter(([, live]) => live === true).map(([id]) => id);}// Wire the freshness signals once, at module load. Invalidation only drops the-// touched id, so the next `listLiveIds` re-reads exactly one record.+// touched id, so the next resolve re-reads exactly one record.//// The `journals` type is the one that needs checking rather than assuming:// brainJournal re-emits `journals:upserted` / `journals:deleted` under the SAME@@ -369,10 +398,10 @@ export function listLiveIds(type) {// `remove()` → `journals:deleted` with `{ id }`), which is what actually// invalidates.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(`${type}:upserted`, ({ id } = {}) => invalidateRecordIndexes(type, id));+ brainEvents.on(`${type}:deleted`, ({ id } = {}) => invalidateRecordIndexes(type, id));}-brainEvents.on('record:changed', ({ type, id } = {}) => invalidateLiveId(type, id));+brainEvents.on('record:changed', ({ type, id } = {}) => invalidateRecordIndexes(type, id));/*** Get the RAW records map for a store, INCLUDING tombstones, keyed by id.@@ -940,12 +969,79 @@ export const updateLink = (id, data) => update('links', id, data);export const reorderLinks = (updates) => updateMany('links', updates);export const deleteLink = (id) => remove('links', id);+// ─── Link summary index (issue #3509) ───────────────────────────────────────+// Every ordering, filtering, counting, and membership question the links API+// asks is answerable from four fields. Caching just those in a projection index+// (see createRecordIndex above) means `GET /api/brain/links` reads ONLY the+// requested page's record bodies instead of the whole collection — page cost+// goes from O(N) parsed records to O(limit).+//+// `null` marks an id that is not a user-visible link (absent, unparseable, or+// tombstoned) — exactly what `getAll` drops. Tombstones stay in the id listing,+// so this must be a null projection rather than an omitted entry.+const projectLinkSummary = (record) => (record && !isTombstone(record)+ ? {+ // Pre-parsed sort key: `getAll` + `new Date()` in a comparator re-parses the+ // same timestamp O(n log n) times. `safeDate` yields 0 for a missing or+ // unparseable createdAt, so such a link sorts last deterministically+ // instead of poisoning the comparator with NaN.+ createdAtMs: safeDate(record.createdAt),+ // Filter keys are stored RAW so the route's strict `===` comparison keeps+ // its exact semantics (a link with no `isGitHubRepo` field must not match+ // `?isGitHubRepo=false`, just as the old in-memory filter behaved).+ linkType: record.linkType,+ isGitHubRepo: record.isGitHubRepo,+ url: record.url,+ }+ : null);+const linkSummaryIndex = createRecordIndex(projectLinkSummary);++const resolveLinkSummaries = () => resolveRecordIndex(linkSummaryIndex, 'links', 0);+/**- * Find link by URL+ * One page of links, newest-first by `createdAt`.+ *+ * Filtering, ordering, and the `total` count all come off the cached summary+ * index; only the page's own records are loaded from disk. `linkType` /+ * `isGitHubRepo` are optional and compared strictly, matching the filters the+ * route used to apply in memory.+ */+export async function getLinksPage({ linkType, isGitHubRepo, limit = 50, offset = 0 } = {}) {+ const rows = await resolveLinkSummaries();+ const matching = rows.filter(([, summary]) => summary+ && (linkType === undefined || summary.linkType === linkType)+ && (isGitHubRepo === undefined || summary.isGitHubRepo === isGitHubRepo));++ // Newest-first, with the id as a deterministic tiebreak: a bulk import stamps+ // many links with the SAME createdAt, and an unstable order across two page+ // requests would drop or duplicate records at the slice boundary.+ matching.sort(([idA, a], [idB, b]) => (b.createdAtMs - a.createdAtMs) || idA.localeCompare(idB));++ const total = matching.length;+ const pageIds = matching.slice(offset, offset + limit).map(([id]) => id);+ const page = await Promise.all(pageIds.map((id) => getById('links', id)));+ // A record deleted between the index read and the body read comes back null —+ // drop it rather than emitting a hole in the page.+ return { links: page.filter(Boolean), total };+}++/**+ * Ids of the user-visible (non-tombstoned) links, from the same summary index —+ * a membership check that parses no record bodies in steady state.+ */+export async function listLinkIds() {+ const rows = await resolveLinkSummaries();+ return rows.filter(([, summary]) => summary).map(([id]) => id);+}++/**+ * Find link by URL. Resolves the id from the summary index (no bodies) and+ * loads only the one match.*/export async function getLinkByUrl(url) {- const links = await getAll('links');- return links.find(link => link.url === url) || null;+ const rows = await resolveLinkSummaries();+ const hit = rows.find(([, summary]) => summary && summary.url === url);+ return hit ? getById('links', hit[0]) : null;}// Buckets (bookmark groups for links)@@ -1085,7 +1181,7 @@ export async function backfillOriginInstanceId() {// =============================================================================/**- * Invalidate the non-collection caches (meta + JSONL logs) and the live-id+ * Invalidate the non-collection caches (meta + JSONL logs) and every projection* index. Entity store BODIES still read through to disk, so there is no* whole-record entity cache to clear.*/@@ -1094,9 +1190,11 @@ export function invalidateAllCaches() {caches[key].data = null;caches[key].timestamp = 0;}- for (const type of BRAIN_ENTITY_TYPES) {- liveIdIndex[type].clear();- liveIdGeneration[type] += 1;+ for (const index of recordIndexes) {+ for (const type of BRAIN_ENTITY_TYPES) {+ index.byType[type].clear();+ index.generation[type] += 1;+ }}}diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex af0980b7e6..46c2221ed8 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -388,6 +388,142 @@ describe('listLiveIds (embedding-coverage id index, issue #3508)', () => {});});+describe('getLinksPage (paginated link reads, issue #3509)', () => {+ // The temp store is shared by every test in this file, so assertions filter+ // the page down to the ids the test itself created rather than assuming the+ // links collection is empty.+ const mine = (page, ids) => page.links.map((l) => l.id).filter((id) => ids.includes(id));+ const linkCount = async () => (await brainStorage.getAll('links')).length;++ // Overwrite createdAt behind the store (create() stamps its own) and drop the+ // caches so the summary index picks the new sort key up.+ const stampCreatedAt = async (id, createdAt) => {+ await writeRawRecord('links', id, { ...(await rawRecord('links', id)), createdAt });+ brainStorage.invalidateAllCaches();+ };++ it('orders newest-first and returns only the requested window plus a full total', async () => {+ const older = await brainStorage.create('links', { url: 'https://example.com/older', linkType: 'article' });+ const newer = await brainStorage.create('links', { url: 'https://example.com/newer', linkType: 'article' });+ const newest = await brainStorage.create('links', { url: 'https://example.com/newest', linkType: 'article' });+ // Far-future stamps so these three are unambiguously the newest three links+ // in the shared store, whatever else the file has created.+ await stampCreatedAt(older.id, ISO('2099-01-01'));+ await stampCreatedAt(newer.id, ISO('2099-02-01'));+ await stampCreatedAt(newest.id, ISO('2099-03-01'));++ const first = await brainStorage.getLinksPage({ limit: 2, offset: 0 });+ expect(first.links.map((l) => l.id)).toEqual([newest.id, newer.id]);+ // `total` counts everything matching the filters, not the page.+ expect(first.total).toBe(await linkCount());+ // The page carries FULL records, not just the indexed summary fields.+ expect(first.links[0]).toMatchObject({ url: 'https://example.com/newest', linkType: 'article' });++ const second = await brainStorage.getLinksPage({ limit: 2, offset: 2 });+ expect(second.links[0].id).toBe(older.id);+ expect(second.total).toBe(first.total);+ });++ it('answers filtering and counting from the index, reading only the page bodies', async () => {+ const ids = [];+ for (let i = 0; i < 5; i++) {+ const l = await brainStorage.create('links', { url: `https://example.com/slice-${i}`, linkType: 'tool' });+ ids.push(l.id);+ }+ // Prime the summary index.+ expect(mine(await brainStorage.getLinksPage({ linkType: 'tool', limit: 50 }), ids)).toHaveLength(5);++ // Retype every one of them BEHIND the store — no write path, so no event and+ // no invalidation. Filtering/counting that still re-read bodies would now+ // return zero matches.+ for (const id of ids) {+ await writeRawRecord('links', id, { ...(await rawRecord('links', id)), linkType: 'other' });+ }++ const page = await brainStorage.getLinksPage({ linkType: 'tool', limit: 1, offset: 0 });+ expect(page.total).toBe(5);+ expect(page.links).toHaveLength(1);+ // …and the one body the page DID read is the fresh on-disk record — proof the+ // stale filter/count above came from the index, not from a whole-store re-read.+ expect(page.links[0].linkType).toBe('other');++ // The cache is droppable: a full re-read sees the retype and matches nothing.+ brainStorage.invalidateAllCaches();+ expect(mine(await brainStorage.getLinksPage({ linkType: 'tool', limit: 50 }), ids)).toHaveLength(0);+ });++ it('filters strictly on linkType and isGitHubRepo, matching the old in-memory filter', async () => {+ const repo = await brainStorage.create('links', { url: 'https://example.com/gh', linkType: 'github', isGitHubRepo: true });+ const plain = await brainStorage.create('links', { url: 'https://example.com/plain', linkType: 'documentation', isGitHubRepo: false });+ // No isGitHubRepo field at all — must NOT match `false`, exactly as the old+ // `l.isGitHubRepo === isGitHubRepo` filter behaved.+ const untyped = await brainStorage.create('links', { url: 'https://example.com/untyped', linkType: 'documentation' });+ const ids = [repo.id, plain.id, untyped.id];++ expect(mine(await brainStorage.getLinksPage({ isGitHubRepo: true, limit: 50 }), ids)).toEqual([repo.id]);+ expect(mine(await brainStorage.getLinksPage({ isGitHubRepo: false, limit: 50 }), ids)).toEqual([plain.id]);+ expect(mine(await brainStorage.getLinksPage({ linkType: 'documentation', limit: 50 }), ids).sort())+ .toEqual([plain.id, untyped.id].sort());+ expect(mine(await brainStorage.getLinksPage({ linkType: 'github', isGitHubRepo: true, limit: 50 }), ids))+ .toEqual([repo.id]);+ });++ it('drops a link from the page as soon as it is deleted', async () => {+ const kept = await brainStorage.create('links', { url: 'https://example.com/kept', linkType: 'reference' });+ const gone = await brainStorage.create('links', { url: 'https://example.com/gone', linkType: 'reference' });+ const ids = [kept.id, gone.id];++ expect(mine(await brainStorage.getLinksPage({ linkType: 'reference', limit: 50 }), ids).sort())+ .toEqual(ids.slice().sort());++ // remove() tombstones in place — the id survives `listIds()`, so the index+ // has to drop it off the `links:deleted` event rather than the id diff.+ await brainStorage.remove('links', gone.id);++ expect(mine(await brainStorage.getLinksPage({ linkType: 'reference', limit: 50 }), ids)).toEqual([kept.id]);+ });++ it('orders createdAt ties by id so a page boundary never drops or duplicates a link', async () => {+ const shared = ISO('2098-04-01');+ const created = [];+ for (const n of ['a', 'b', 'c']) {+ created.push(await brainStorage.create('links', { url: `https://example.com/tie-${n}`, linkType: 'other' }));+ }+ const ids = created.map((l) => l.id);+ for (const id of ids) await stampCreatedAt(id, shared);++ const p1 = await brainStorage.getLinksPage({ linkType: 'other', limit: 2, offset: 0 });+ const p2 = await brainStorage.getLinksPage({ linkType: 'other', limit: 2, offset: 2 });+ const seen = [...mine(p1, ids), ...mine(p2, ids)];+ expect(new Set(seen).size).toBe(3);+ expect(seen.slice().sort()).toEqual(ids.slice().sort());+ });++ it('listLinkIds reports live ids and skips tombstones', async () => {+ const alive = await brainStorage.create('links', { url: 'https://example.com/alive' });+ const dead = await brainStorage.create('links', { url: 'https://example.com/dead' });+ await brainStorage.remove('links', dead.id);++ const ids = await brainStorage.listLinkIds();+ expect(ids).toContain(alive.id);+ expect(ids).not.toContain(dead.id);+ });++ it('getLinkByUrl resolves through the index and returns the full record', async () => {+ const created = await brainStorage.create('links', {+ url: 'https://example.com/by-url', linkType: 'documentation', title: 'Docs',+ });++ expect(await brainStorage.getLinkByUrl('https://example.com/by-url'))+ .toMatchObject({ id: created.id, title: 'Docs' });+ expect(await brainStorage.getLinkByUrl('https://example.com/never-saved')).toBeNull();++ // A deleted link's url must stop resolving.+ await brainStorage.remove('links', created.id);+ expect(await brainStorage.getLinkByUrl('https://example.com/by-url')).toBeNull();+ });+});+// 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.