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

cache getSettings() reads and parallelize a few independent file loads

[._.]/ Adam Eivy622ee3d3f42f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c9fa23936b..7945785041 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -99,3 +99,5 @@
## Internal
- **[issue-2183] Creative Tool Registry + gated dispatch (CDO Phase 1).** Foundation for the Creative Director orchestrator (epic #2182): a single registry (`server/services/creative/toolRegistry.js` + per-domain modules under `creative/tools/`) of creative-suite tools an orchestrating agent can call — universe, story builder, writers room, pipeline, media, catalog — each a thin conductor wrapper over an existing service entry point (`createUniverse`, `generateStep`, `startSeriesAutopilot`, `enqueueJob`, …), never a re-implementation. All orchestrator calls flow through one governed chokepoint, `dispatchCreativeTool(name, args, ctx)`, which validates args (Zod), enforces a new `creative` autonomy mode, charges the daily action budget for `llm`/`render` tools, and appends a `{tool, argsDigest, outcome, timing}` entry to the calling project's run ledger. The `creative` autonomy domain (`server/lib/domainAutonomy.js` `getCreativeAutonomyMode`) is kept separate from the four core domains and defaults to mirror the `cos` mode, so existing autopilot users get consistent behavior with no migration, while an explicit `domainAutonomy.creative` value can override it later. Direct user actions through the existing routes are unchanged — the gate lives only on the orchestrator path. No user-facing surface yet; the directive composer and plan board arrive in later CDO phases.
+
+- **`getSettings()` now serves from an in-memory cache instead of re-reading settings.json on every call.** `getSettings()` is invoked 100+ times across the codebase (several per request), each previously doing a fresh filesystem read + JSON.parse of app-wide, rarely-changing data. It now memoizes the parsed settings, populated lazily on first read and refreshed off the `settings:updated` event that every `save()`/`updateSettings()`/`updateSettingsWith()` already emits — so app-driven writes keep the cache coherent while write paths still read fresh off disk inside their write queue for the read-merge-write, preserving write-ordering guarantees. Mirrors the existing `settings:updated`-invalidated cache in `sharing/annotationIdentity.js`. Alongside it, a few independent per-file read loops are now parallelized (`digital-twin-analysis.validateCompleteness`, editorial series-health's series+settings load) and hot page derivations memoized (`Review` grouping/sorting, `Tribe` care-queue), cutting redundant work on socket-driven re-renders.
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index 6e64749493..328f2fe40f 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
ClipboardList,
@@ -234,11 +234,33 @@ export default function Review() {
if (ok) handleQueueDismiss(item.id);
};
- const grouped = items.reduce((acc, item) => {
+ // Derived review state. Memoized because this page subscribes to
+ // review:item:created/updated/deleted socket events and re-renders on each —
+ // without memoization every one of these filter/sort passes over `items` reruns
+ // on unrelated re-renders (typing, hover state). Hooks must run before the
+ // loading early-return, so they live here above it.
+ const grouped = useMemo(() => items.reduce((acc, item) => {
if (!acc[item.type]) acc[item.type] = [];
acc[item.type].push(item);
return acc;
- }, {});
+ }, {}), [items]);
+
+ const queueItems = useMemo(
+ () => (queue?.items || []).filter(i => !dismissedQueueIds.has(i.id)),
+ [queue, dismissedQueueIds]);
+ const queueSourceErrors = useMemo(
+ () => Object.entries(queue?.sources || {}).filter(([, s]) => s.error),
+ [queue]);
+
+ const pendingItems = useMemo(() => items.filter(i => i.status === 'pending'), [items]);
+
+ const actionableItems = useMemo(() => pendingItems
+ .filter(isActionableItem)
+ .sort((a, b) => {
+ const priority = TYPE_PRIORITY[a.type] - TYPE_PRIORITY[b.type];
+ if (priority !== 0) return priority;
+ return new Date(b.createdAt) - new Date(a.createdAt);
+ }), [pendingItems]);
if (loading) {
return (
@@ -248,24 +270,15 @@ export default function Review() {
);
}
- const queueItems = (queue?.items || []).filter(i => !dismissedQueueIds.has(i.id));
- const queueSourceErrors = Object.entries(queue?.sources || {}).filter(([, s]) => s.error);
-
- const pendingItems = items.filter(i => i.status === 'pending');
- const pendingCount = pendingItems.length;
+ // Cheap derivations off the memoized `pendingItems`/`actionableItems` — plain
+ // consts, not memos: each is O(n) filter or O(8) slice with no consumer that
+ // needs referential stability, so a hook here would be pure ceremony.
const pendingAlerts = pendingItems.filter(i => i.type === 'alert');
const pendingCos = pendingItems.filter(i => i.type === 'cos');
const pendingTodos = pendingItems.filter(i => i.type === 'todo');
-
- const actionableItems = pendingItems
- .filter(isActionableItem)
- .sort((a, b) => {
- const priority = TYPE_PRIORITY[a.type] - TYPE_PRIORITY[b.type];
- if (priority !== 0) return priority;
- return new Date(b.createdAt) - new Date(a.createdAt);
- });
-
const topActionItems = actionableItems.slice(0, 8);
+
+ const pendingCount = pendingItems.length;
const remainingActionCount = Math.max(0, actionableItems.length - topActionItems.length);
return (
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index 1689733614..23e7ae1899 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -556,14 +556,16 @@ function EmptyState({ onNew }) {
function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {
// External people are outside the tribe — no care cadence is owed, so they
// never appear in the queue (otherwise their null daysRemaining would sort
- // them to the top alongside genuinely-overdue contacts).
- const queue = useMemo(() => contacts.filter((contact) => contact.ring !== 'external').sort((a, b) => {
- const aStatus = contactStatus(a);
- const bStatus = contactStatus(b);
- const aScore = aStatus.daysRemaining == null ? -999 : aStatus.daysRemaining;
- const bScore = bStatus.daysRemaining == null ? -999 : bStatus.daysRemaining;
- return aScore - bScore;
- }), [contacts]);
+ // them to the top alongside genuinely-overdue contacts). Memoized + status
+ // computed once per contact (instead of twice per comparison in the sort).
+ const queue = useMemo(() => contacts
+ .filter((contact) => contact.ring !== 'external')
+ .map((contact) => {
+ const score = contactStatus(contact).daysRemaining;
+ return { contact, score: score == null ? -999 : score };
+ })
+ .sort((a, b) => a.score - b.score)
+ .map(({ contact }) => contact), [contacts]);
if (!queue.length) return <EmptyState onNew={onNew} />;
diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.js
index 4ac8d700c7..ad70338eeb 100644
--- a/server/lib/authGate.test.js
+++ b/server/lib/authGate.test.js
@@ -18,10 +18,17 @@ const resetSettings = () => {
// Merge an apiAccess block into settings.json (preserving any auth secrets a
// prior setPassword() call wrote). setPassword persists secrets to the same
// file, so read-modify-write rather than clobbering.
-const writeApiAccess = (apiAccess) => {
+// getSettings() memoizes the parsed file and only refreshes off the
+// `settings:updated` event that save() emits. This helper writes settings.json
+// directly (bypassing save()), so a prior getSettings — e.g. from setPassword —
+// would leave the cache stale on this apiAccess block. Drop the cache so the
+// subsequent authGate read observes the freshly-written file.
+const writeApiAccess = async (apiAccess) => {
const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));
raw.apiAccess = apiAccess;
writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');
+ const { __resetSettingsCache } = await import('../services/settings.js');
+ __resetSettingsCache();
};
beforeEach(() => {
@@ -247,7 +254,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('opens /api/voice/public/* when voice is exposed + passwordless', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ voice: { exposed: true, requireAuth: false } });
+ await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
const synth = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });
expect(synth.called).toBe(true);
@@ -260,7 +267,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
// config / process-control routes on the main /api/voice router.
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ voice: { exposed: true, requireAuth: false } });
+ await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
for (const path of ['/api/voice/config', '/api/voice/whisper', '/api/voice/test']) {
const result = await runGate(authGate, { path, headers: {} });
@@ -272,7 +279,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('gates the public surface when exposed but requireAuth is true', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ voice: { exposed: true, requireAuth: true } });
+ await writeApiAccess({ voice: { exposed: true, requireAuth: true } });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });
expect(result.called).toBe(false);
@@ -282,7 +289,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('gates the public surface when not exposed', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ voice: { exposed: false, requireAuth: false } });
+ await writeApiAccess({ voice: { exposed: false, requireAuth: false } });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });
expect(result.called).toBe(false);
@@ -292,7 +299,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('opens /sdapi/* when sdapi is exposed + passwordless', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ sdapi: { exposed: true, requireAuth: false } });
+ await writeApiAccess({ sdapi: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/sdapi/v1/txt2img', headers: {} });
expect(result.called).toBe(true);
@@ -301,7 +308,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('still applies the CSRF cross-origin guard to an exposed public path', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- writeApiAccess({ voice: { exposed: true, requireAuth: false } });
+ await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
path: '/api/voice/public/synthesize',
@@ -314,7 +321,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('ignores apiAccess entirely when auth is disabled (no regression)', async () => {
// Auth off → everything passes regardless of apiAccess flags.
- writeApiAccess({ voice: { exposed: false, requireAuth: true } });
+ await writeApiAccess({ voice: { exposed: false, requireAuth: true } });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });
expect(result.called).toBe(true);
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index faf68575cd..2bd12c38ab 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -166,8 +166,11 @@ router.get('/editorial/checks', asyncHandler(async (req, res) => {
// series + per issue), the readiness signal, and the revision trend +
// regressions. Reads the same manuscript-review findings the triage view shows.
router.get('/series/:id/editorial/health', asyncHandler(async (req, res) => {
- const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
- const settings = await getSettings();
+ // Independent loads — fetch the series and settings concurrently.
+ const [series, settings] = await Promise.all([
+ seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); }),
+ getSettings()
+ ]);
const gate = readReadinessGate(settings) || DEFAULT_READINESS_GATE;
// Per-series severity-weight override (#1616) so the returned score + `weights`
// echo reflect the override the autopilot health gate also uses.
diff --git a/server/routes/publicApiIntegration.test.js b/server/routes/publicApiIntegration.test.js
index 1520479edd..73a2d1da56 100644
--- a/server/routes/publicApiIntegration.test.js
+++ b/server/routes/publicApiIntegration.test.js
@@ -40,10 +40,16 @@ const resetSettings = (extra = {}) => {
writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(extra, null, 2) + '\n');
writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');
};
-const setApiAccess = (apiAccess) => {
+// getSettings() memoizes the parsed file and only refreshes off save()'s
+// `settings:updated` event. This helper writes settings.json directly, so a
+// prior getSettings (e.g. from setPassword) would leave the cache stale on this
+// apiAccess block — drop the cache so the app built next reads the fresh file.
+const setApiAccess = async (apiAccess) => {
const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));
raw.apiAccess = apiAccess;
writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');
+ const { __resetSettingsCache } = await import('../services/settings.js');
+ __resetSettingsCache();
};
const buildApp = async () => {
@@ -101,7 +107,7 @@ describe('public voice API — end-to-end through authGate', () => {
it('auth ON + exposed + passwordless: public synthesize works WITHOUT a token', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- setApiAccess({ voice: { exposed: true, requireAuth: false } });
+ await setApiAccess({ voice: { exposed: true, requireAuth: false } });
const app = await buildApp();
const res = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi', engine: 'piper' });
expect(res.status).toBe(200);
@@ -111,7 +117,7 @@ describe('public voice API — end-to-end through authGate', () => {
it('auth ON + exposed + passwordless: config mutation is STILL 401', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- setApiAccess({ voice: { exposed: true, requireAuth: false } });
+ await setApiAccess({ voice: { exposed: true, requireAuth: false } });
const app = await buildApp();
const res = await request(app).put('/api/voice/config').send({ enabled: true });
expect(res.status).toBe(401);
@@ -121,7 +127,7 @@ describe('public voice API — end-to-end through authGate', () => {
it('auth ON + requireAuth: public synthesize 401s without a token, works with one', async () => {
const auth = await import('../services/auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
- setApiAccess({ voice: { exposed: true, requireAuth: true } });
+ await setApiAccess({ voice: { exposed: true, requireAuth: true } });
const app = await buildApp();
const denied = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi' });
@@ -137,7 +143,7 @@ describe('public voice API — end-to-end through authGate', () => {
it('auth ON + not exposed: public synthesize 401s', async () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
- setApiAccess({ voice: { exposed: false, requireAuth: false } });
+ await setApiAccess({ voice: { exposed: false, requireAuth: false } });
const app = await buildApp();
const res = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi' });
expect(res.status).toBe(401);
diff --git a/server/services/digital-twin-analysis.js b/server/services/digital-twin-analysis.js
index 7b620df914..d7de6f5ea2 100644
--- a/server/services/digital-twin-analysis.js
+++ b/server/services/digital-twin-analysis.js
@@ -66,16 +66,16 @@ export async function validateCompleteness() {
const documents = await getDocuments();
const enabledDocs = documents.filter(d => d.enabled && d.category !== 'behavioral');
- // Load content for all enabled documents in parallel — the reads are
- // independent and their results are just concatenated for keyword scanning.
- const contents = (await Promise.all(
- enabledDocs.map(async doc => {
- const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
- if (!existsSync(filePath)) return null;
- const content = await readFile(filePath, 'utf-8');
- return { doc, content: content.toLowerCase() };
+ // Load content for all enabled documents in parallel. A missing file just
+ // resolves to null (dropping the synchronous existsSync pre-check that
+ // serialized the loop and hit the filesystem twice per doc).
+ const loaded = await Promise.all(
+ enabledDocs.map(async (doc) => {
+ const content = await readFile(join(DIGITAL_TWIN_DIR, doc.filename), 'utf-8').catch(() => null);
+ return content === null ? null : { doc, content: content.toLowerCase() };
})
- )).filter(Boolean);
+ );
+ const contents = loaded.filter(Boolean);
const allContent = contents.map(c => c.content).join('\n');
const found = [];
diff --git a/server/services/settings.js b/server/services/settings.js
index 87f61500e6..0b8cfdd847 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -70,6 +70,43 @@ const loadRaw = async () => {
return safeJSONParse(raw ?? '{}', {});
};
+// Read-side cache. `getSettings()` is called 100+ times across the codebase
+// (many per request), and each call previously did a fresh filesystem read +
+// JSON.parse. Settings is app-wide, rarely-changing data — a textbook memoize.
+// Correctness contract:
+// - The cache is populated lazily on the first `getSettings()` and refreshed
+// from the `settings:updated` event the SAME emitter already fires on every
+// `save()` — so any write through the app (saveSettings/updateSettings/
+// updateSettingsWith) keeps the cache warm and consistent.
+// - Write paths (`save`, `updateSettings`, `updateSettingsWith`) deliberately
+// still read `loadRaw()` off disk inside the write queue for their
+// read-merge-write, so their base snapshot is always the freshest persisted
+// truth, never the cache. The post-write `settings:updated` then syncs the
+// cache. This keeps the write-ordering guarantees intact.
+// - `null` = not-yet-loaded (distinct from a legitimately empty `{}`), so a
+// fresh process reads disk exactly once.
+// - The prior `stripStoreKeys(await loadRaw())` handed every caller a fresh deep
+// object graph, so callers may mutate nested settings in place. To preserve
+// that isolation the cache is never handed out directly: reads deep-clone it,
+// and the `settings:updated` listener stores a private clone (save() emits the
+// same `cleaned` object it also returns to its caller). structuredClone is the
+// right tool for this JSON-shaped data and stays far cheaper than the disk
+// read + full-tree JSON.parse it replaces.
+// A manual edit of settings.json while the server runs is not observed until
+// the next app-driven save or a restart — the standard trade-off for a cache,
+// and app-driven changes (the only ones the schedulers care about) refresh it.
+let settingsCache = null;
+settingsEvents.on('settings:updated', (cleaned) => {
+ settingsCache = structuredClone(cleaned);
+});
+
+// Test-only: drop the read cache so a suite that stubs the on-disk file per
+// test observes each fresh stub. Production code never calls this — writes keep
+// the cache coherent via the `settings:updated` event above.
+export const __resetSettingsCache = () => {
+ settingsCache = null;
+};
+
// Serialize all writes to settings.json on a single tail so an updateSettings
// read-merge-write can't interleave with a concurrent save (two browser tabs,
// a background job racing a user save) and clobber the other's patch. Reads
@@ -109,7 +146,17 @@ const save = async (settings) => {
return cleaned;
};
-export const getSettings = async () => stripStoreKeys(await loadRaw());
+export const getSettings = async () => {
+ if (settingsCache === null) {
+ // stripStoreKeys builds a fresh top-level object over the just-parsed
+ // loadRaw() graph, which nothing else references — safe to cache directly.
+ settingsCache = stripStoreKeys(await loadRaw());
+ }
+ // Hand out a private deep copy so a caller mutating nested settings in place
+ // can't corrupt the shared cache — matching the prior per-call
+ // `stripStoreKeys(await loadRaw())` deep-copy semantics, minus the I/O.
+ return structuredClone(settingsCache);
+};
export const saveSettings = (settings) => queueWrite(() => save(settings));
// Merge against the unstripped on-disk snapshot so save() sees every
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 3f739eb36e..c1f955f993 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -14,11 +14,14 @@ vi.mock('../lib/fileUtils.js', async (importActual) => {
});
import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
-import { getSettings, updateSettings, updateSettingsWith } from './settings.js';
+import { getSettings, updateSettings, updateSettingsWith, __resetSettingsCache } from './settings.js';
describe('settings.js', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // getSettings memoizes the parsed file; drop the cache so each test observes
+ // its own per-test tryReadFile stub instead of a value cached by a prior test.
+ __resetSettingsCache();
// Sensible defaults: empty file on disk, writes succeed. Individual tests
// override as needed.
tryReadFile.mockResolvedValue('{}');