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: reduce filesystem work for Brain collection listings (#9523)

Adam Eivycd6e66ba45bf
diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.js
index 433ced201d..f2a2600150 100644
--- a/server/lib/collectionStore.js
+++ b/server/lib/collectionStore.js
@@ -82,7 +82,7 @@
*/
import { join } from 'path';
-import { readdir, lstat, rm } from 'fs/promises';
+import { readdir, rm } from 'fs/promises';
import { atomicWrite, readJSONFile, readJSONFileStrict, unreadableStoreError, ensureDir } from './fileUtils.js';
import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.js';
import { isPlainObject, POLLUTING_KEYS } from './objects.js';
@@ -243,27 +243,18 @@ export function createCollectionStore({
* anything that doesn't match `idPattern` or isn't a directory.
*/
async function listIds() {
- const entries = await readdir(dir).catch((err) => {
+ const entries = await readdir(dir, { withFileTypes: true }).catch((err) => {
if (err?.code === 'ENOENT') return null;
throw err;
});
if (entries === null) return [...knownIds].filter(isValidId);
- const candidates = entries.filter((name) =>
- name !== 'index.json'
- && !name.startsWith('.')
- && isValidId(name)
- );
- // lstat (not stat) so symlinks are NOT followed — a symlink whose target
- // is a directory would otherwise be accepted as a valid record dir, with
- // future deleteOne calls rm-rf'ing the symlink AND its target's contents.
- // PortOS is single-user/Tailscale-private so this is defense-in-depth
- // rather than a real attack vector, but it closes the foot-gun where a
- // user symlinks a record dir to external storage. lstat rejects the
- // symlink as non-directory; legitimate same-volume directories pass.
- const stats = await Promise.all(candidates.map((name) =>
- lstat(join(dir, name)).then((s) => (s.isDirectory() ? name : null), () => null)
- ));
- return stats.filter(Boolean);
+ // Dirent types exclude symlinks without an explicit lstat per record.
+ return entries.filter((entry) =>
+ entry.name !== 'index.json'
+ && !entry.name.startsWith('.')
+ && isValidId(entry.name)
+ && entry.isDirectory()
+ ).map((entry) => entry.name);
}
/**
diff --git a/server/lib/collectionStore.test.js b/server/lib/collectionStore.test.js
index 7356bca27f..309b792ce0 100644
--- a/server/lib/collectionStore.test.js
+++ b/server/lib/collectionStore.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync } from 'fs';
+import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync, symlinkSync } from 'fs';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -256,10 +256,22 @@ describe('listIds', () => {
await store.saveTypeIndex({});
writeFileSync(join(dir, '.DS_Store'), '');
writeFileSync(join(dir, 'loose-file.txt'), 'noise');
+ mkdirSync(join(dir, '.hidden'));
+ symlinkSync(join(dir, 'alpha'), join(dir, 'linked'), 'junction');
const ids = await store.listIds();
expect([...ids].sort()).toEqual(['alpha', 'beta']);
});
+ it('retains known ids only when the directory is missing and propagates other errors', async () => {
+ const collectionDir = join(dir, 'records');
+ const store = createCollectionStore({ dir: collectionDir, type: 'widgets', schemaVersion: 1 });
+ await store.saveOne('alpha', { id: 'alpha' });
+ rmSync(collectionDir, { recursive: true });
+ expect(await store.listIds()).toEqual(['alpha']);
+ writeFileSync(collectionDir, 'not a directory');
+ await expect(store.listIds()).rejects.toMatchObject({ code: 'ENOTDIR' });
+ });
+
it('rejects entries that fail the idPattern', async () => {
const store = createCollectionStore({
dir, type: 'widgets', schemaVersion: 1,
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 7781d32f95..dafb7a354c 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -15,6 +15,13 @@ function getTempRoot() {
return tempRoot;
}
+vi.mock('fs/promises', async () => {
+ const actual = await vi.importActual('fs/promises');
+ return { ...actual, readdir: vi.fn(actual.readdir), lstat: vi.fn(actual.lstat) };
+});
+
+import { readdir, lstat } from 'fs/promises';
+
vi.mock('../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../lib/fileUtils.js');
return makePathsProxy({
@@ -934,12 +941,42 @@ describe('getInboxLog (paginated inbox reads, issue #5440)', () => {
}
await brainStorage.getInboxLog({ status: 'needs_review', limit: 1 });
+ await brainStorage.getSummary();
+ readdir.mockClear();
+ lstat.mockClear();
readJSONFile.mockClear();
const page = await brainStorage.getInboxLog({ status: 'needs_review', limit: 1 });
expect(page).toHaveLength(1);
await brainStorage.getInboxLogCounts();
expect(readJSONFile).toHaveBeenCalledTimes(1);
+ await brainStorage.getSummary();
+ expect(readdir).toHaveBeenCalled();
+ expect(readdir.mock.calls.every(([, options]) => options?.withFileTypes === true)).toBe(true);
+ expect(lstat).not.toHaveBeenCalled();
+ });
+
+ it('refreshes warm inbox membership after external directory additions and deletions', async () => {
+ const counts = await brainStorage.getInboxLogCounts();
+ const summary = await brainStorage.getSummary();
+ const id = 'external-inbox-record';
+ const recordDir = join(getTempRoot(), 'brain', 'inbox', id);
+ mkdirSync(recordDir, { recursive: true });
+ writeFileSync(join(recordDir, 'index.json'), JSON.stringify({
+ id, capturedText: 'External example', status: 'needs_review',
+ capturedAt: '2099-01-01T00:00:00.000Z',
+ }));
+
+ expect((await brainStorage.getInboxLog({ limit: 1 }))[0].id).toBe(id);
+ expect(await brainStorage.getInboxLogCounts()).toMatchObject({
+ total: counts.total + 1, needs_review: counts.needs_review + 1,
+ });
+ expect((await brainStorage.getSummary()).counts.inbox.total).toBe(summary.counts.inbox.total + 1);
+
+ rmSync(recordDir, { recursive: true });
+ expect((await brainStorage.getInboxLog({ limit: 1 }))[0]?.id).not.toBe(id);
+ expect(await brainStorage.getInboxLogCounts()).toEqual(counts);
+ expect(await brainStorage.getSummary()).toEqual(summary);
});
it('invalidates the projection after status updates and deletes', async () => {