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

refactor([data-versioning-centralize-cosagents-settings]): persist settings.json via atomicWrite + serialize writes

[._.]/ Adam Eivye2a89d8559b3
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 27ec83d1ca..0c891bde44 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -32,8 +32,8 @@ export async function loadAgentIndex() {
}
if (existsSync(INDEX_FILE)) {
- const content = await readFile(INDEX_FILE, 'utf-8').catch(() => '{}');
- const parsed = safeJSONParse(content, {});
+ const content = await tryReadFile(INDEX_FILE);
+ const parsed = safeJSONParse(content ?? '{}', {});
agentIndex = new Map(Object.entries(parsed));
console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
} else {
diff --git a/server/services/settings.js b/server/services/settings.js
index 27861185d7..0bac7212fb 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -1,7 +1,7 @@
-import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { EventEmitter } from 'events';
-import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { safeJSONParse, PATHS, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';
// POLLUTING_KEYS (`__proto__`/`constructor`/`prototype`) is the project-wide
@@ -66,14 +66,23 @@ settingsEvents.setMaxListeners(50);
// - A direct `saveSettings(badObject)` with store keys warns once after the
// write resolves.
const loadRaw = async () => {
- const raw = await readFile(SETTINGS_FILE, 'utf-8').catch(() => '{}');
- return safeJSONParse(raw, {});
+ const raw = await tryReadFile(SETTINGS_FILE);
+ return safeJSONParse(raw ?? '{}', {});
};
+// 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
+// stay off the queue — atomicWrite's temp-file+rename keeps every read whole.
+const queueWrite = createFileWriteQueue();
+
const save = async (settings) => {
const cleaned = stripStoreKeys(settings);
- await writeFile(SETTINGS_FILE, JSON.stringify(cleaned, null, 2) + '\n');
- // Warn AFTER the successful write so a thrown writeFile never produces
+ // atomicWrite (temp-file + rename) so a mid-write crash never truncates
+ // settings.json. Pass a pre-stringified string to preserve the trailing
+ // newline; atomicWrite's own JSON.stringify omits it.
+ await atomicWrite(SETTINGS_FILE, JSON.stringify(cleaned, null, 2) + '\n');
+ // Warn AFTER the successful write so a thrown write never produces
// a misleading "stripped" log line for a write that didn't happen.
if (isPlainObject(settings)) {
const polluted = Object.keys(settings).filter((k) => MORTALLOOM_STORE_KEYS.has(k));
@@ -86,14 +95,16 @@ const save = async (settings) => {
};
export const getSettings = async () => stripStoreKeys(await loadRaw());
-export const saveSettings = save;
+export const saveSettings = (settings) => queueWrite(() => save(settings));
// Merge against the unstripped on-disk snapshot so save() sees every
// MortalLoom store key in one place — guaranteeing exactly one warning
-// per updateSettings call, only when the write succeeds.
-export const updateSettings = async (patch) => {
+// per updateSettings call, only when the write succeeds. The whole
+// read-merge-write runs inside one queued turn so it merges against the
+// freshest persisted snapshot, not a stale pre-image.
+export const updateSettings = (patch) => queueWrite(async () => {
const raw = await loadRaw();
const incoming = isPlainObject(patch) ? patch : {};
const merged = { ...raw, ...incoming };
return save(merged);
-};
+});
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 9a333c9686..0a3aff53b0 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -1,32 +1,44 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-// Mock fs/promises before importing the module
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(),
- writeFile: vi.fn()
-}));
+// settings.js persists via the shared atomicWrite helper and reads via
+// tryReadFile (both from server/lib/fileUtils.js). Mock just those two and
+// keep the rest of fileUtils real (PATHS, safeJSONParse). The createFileWriteQueue
+// serializer is exercised for real — writes are sequential in these tests anyway.
+vi.mock('../lib/fileUtils.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ atomicWrite: vi.fn(),
+ tryReadFile: vi.fn()
+ };
+});
-import { readFile, writeFile } from 'fs/promises';
+import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { getSettings, updateSettings } from './settings.js';
describe('settings.js', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // Sensible defaults: empty file on disk, writes succeed. Individual tests
+ // override as needed.
+ tryReadFile.mockResolvedValue('{}');
+ atomicWrite.mockResolvedValue();
});
describe('getSettings', () => {
it('should return parsed settings from file', async () => {
const mockSettings = { theme: 'dark', notifications: true };
- readFile.mockResolvedValue(JSON.stringify(mockSettings));
+ tryReadFile.mockResolvedValue(JSON.stringify(mockSettings));
const result = await getSettings();
expect(result).toEqual(mockSettings);
- expect(readFile).toHaveBeenCalledTimes(1);
+ expect(tryReadFile).toHaveBeenCalledTimes(1);
});
it('should return empty object when file does not exist', async () => {
- readFile.mockRejectedValue(new Error('ENOENT'));
+ // tryReadFile returns null when the file is missing/unreadable.
+ tryReadFile.mockResolvedValue(null);
const result = await getSettings();
@@ -35,7 +47,7 @@ describe('settings.js', () => {
it('should return empty object for empty file content', async () => {
// safeJSONParse returns the default {} for empty/invalid input
- readFile.mockResolvedValue('');
+ tryReadFile.mockResolvedValue('');
const result = await getSettings();
expect(result).toEqual({});
@@ -50,7 +62,7 @@ describe('settings.js', () => {
features: ['notifications', 'autoSave'],
version: 2
};
- readFile.mockResolvedValue(JSON.stringify(mockSettings));
+ tryReadFile.mockResolvedValue(JSON.stringify(mockSettings));
const result = await getSettings();
@@ -61,8 +73,7 @@ describe('settings.js', () => {
describe('updateSettings', () => {
it('should merge patch with existing settings', async () => {
const existingSettings = { theme: 'light', notifications: true };
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
const result = await updateSettings({ theme: 'dark' });
@@ -71,8 +82,7 @@ describe('settings.js', () => {
it('should add new keys when patching', async () => {
const existingSettings = { theme: 'light' };
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
const result = await updateSettings({ newSetting: 'value' });
@@ -80,20 +90,18 @@ describe('settings.js', () => {
});
it('should write formatted JSON to file', async () => {
- readFile.mockResolvedValue('{}');
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue('{}');
await updateSettings({ test: true });
- expect(writeFile).toHaveBeenCalledTimes(1);
- const [, content] = writeFile.mock.calls[0];
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ const [, content] = atomicWrite.mock.calls[0];
// Should be formatted with 2-space indent and trailing newline
expect(content).toBe('{\n "test": true\n}\n');
});
it('should create settings from empty when file does not exist', async () => {
- readFile.mockRejectedValue(new Error('ENOENT'));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(null);
const result = await updateSettings({ firstSetting: 'value' });
@@ -104,8 +112,7 @@ describe('settings.js', () => {
const existingSettings = {
display: { theme: 'light', fontSize: 12 }
};
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
// Shallow merge replaces the entire display object
const result = await updateSettings({ display: { theme: 'dark' } });
@@ -120,8 +127,7 @@ describe('settings.js', () => {
b: 2,
c: 3
};
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
const result = await updateSettings({ b: 20 });
@@ -130,8 +136,7 @@ describe('settings.js', () => {
it('should handle null values in patch', async () => {
const existingSettings = { feature: true };
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
const result = await updateSettings({ feature: null });
@@ -140,8 +145,7 @@ describe('settings.js', () => {
it('should handle empty patch object', async () => {
const existingSettings = { theme: 'dark' };
- readFile.mockResolvedValue(JSON.stringify(existingSettings));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existingSettings));
const result = await updateSettings({});
@@ -149,6 +153,32 @@ describe('settings.js', () => {
});
});
+ describe('write serialization', () => {
+ it('serializes concurrent updateSettings so neither patch is clobbered', async () => {
+ // Simulate a slow disk: each write reflects onto the next read so the
+ // queued read-merge-write can observe the prior write's result.
+ let current = { base: true };
+ tryReadFile.mockImplementation(async () => JSON.stringify(current));
+ atomicWrite.mockImplementation(async (_path, content) => {
+ current = JSON.parse(content);
+ });
+
+ // Fire both without awaiting the first — the queue must serialize them.
+ const [a, b] = await Promise.all([
+ updateSettings({ first: 1 }),
+ updateSettings({ second: 2 })
+ ]);
+
+ // Both writes happened, in order, and the final state carries both patches.
+ expect(atomicWrite).toHaveBeenCalledTimes(2);
+ expect(current).toEqual({ base: true, first: 1, second: 2 });
+ // The last resolved value is the fully-merged record; the first sees only
+ // its own patch applied to the base.
+ expect(b).toEqual({ base: true, first: 1, second: 2 });
+ expect(a).toEqual({ base: true, first: 1 });
+ });
+ });
+
describe('MortalLoom store key pollution guard', () => {
it('strips MortalLoom-store top-level keys on read', async () => {
// Simulates the historical corruption: settings.json contains both
@@ -162,7 +192,7 @@ describe('settings.js', () => {
profile: { name: 'X' },
mortalloom: { enabled: true }
};
- readFile.mockResolvedValue(JSON.stringify(polluted));
+ tryReadFile.mockResolvedValue(JSON.stringify(polluted));
const result = await getSettings();
@@ -178,13 +208,12 @@ describe('settings.js', () => {
it('strips MortalLoom-store keys before writing', async () => {
const existing = { theme: 'dark' };
- readFile.mockResolvedValue(JSON.stringify(existing));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(existing));
// Caller accidentally passes a payload with store keys.
await updateSettings({ alcoholDrinks: [], goals: [], voice: { enabled: true } });
- const [, content] = writeFile.mock.calls[0];
+ const [, content] = atomicWrite.mock.calls[0];
const written = JSON.parse(content);
expect(written).toEqual({ theme: 'dark', voice: { enabled: true } });
expect(written.alcoholDrinks).toBeUndefined();
@@ -199,24 +228,22 @@ describe('settings.js', () => {
bloodTests: [{ id: 'B' }],
habits: [{ id: 'H' }]
};
- readFile.mockResolvedValue(JSON.stringify(polluted));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(polluted));
// Any save (even unrelated) cleans up the file.
await updateSettings({ timezone: 'UTC' });
- const [, content] = writeFile.mock.calls[0];
+ const [, content] = atomicWrite.mock.calls[0];
const written = JSON.parse(content);
expect(written).toEqual({ theme: 'dark', timezone: 'UTC' });
});
it('preserves legitimate mortalloom config key (not in store-key list)', async () => {
- readFile.mockResolvedValue('{}');
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue('{}');
await updateSettings({ mortalloom: { enabled: true, path: '/foo' } });
- const [, content] = writeFile.mock.calls[0];
+ const [, content] = atomicWrite.mock.calls[0];
const written = JSON.parse(content);
expect(written.mortalloom).toEqual({ enabled: true, path: '/foo' });
});
@@ -227,8 +254,7 @@ describe('settings.js', () => {
theme: 'dark',
alcoholDrinks: [{ id: 'A' }]
};
- readFile.mockResolvedValue(JSON.stringify(polluted));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(polluted));
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
@@ -246,9 +272,9 @@ describe('settings.js', () => {
warnSpy.mockRestore();
});
- it('does not warn when writeFile throws (no misleading log for a write that did not happen)', async () => {
- readFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
- writeFile.mockRejectedValue(new Error('EROFS'));
+ it('does not warn when the write throws (no misleading log for a write that did not happen)', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
+ atomicWrite.mockRejectedValue(new Error('EROFS'));
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
@@ -260,8 +286,7 @@ describe('settings.js', () => {
it('emits exactly one warning per updateSettings even when both disk AND patch are polluted', async () => {
// Disk pollution: alcoholDrinks. Patch pollution: goals. Spec: one log line.
- readFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
@@ -280,8 +305,7 @@ describe('settings.js', () => {
// `{"__proto__":{"polluted":true}}`. Without the guard, the cleaned-object
// rebuild would invoke the __proto__ setter.
const malicious = JSON.parse('{"theme":"dark","__proto__":{"polluted":true},"constructor":{"polluted":true}}');
- readFile.mockResolvedValue(JSON.stringify(malicious));
- writeFile.mockResolvedValue();
+ tryReadFile.mockResolvedValue(JSON.stringify(malicious));
const result = await getSettings();