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([issue-1837]): use atomicWrite for JSON persistence

[._.]/ Adam Eivy5508c266245b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7c55f4a528..cb7bf8df96 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -41,3 +41,4 @@
- **Decomposed `server/services/sharing/peerSync.js` (4,004-line god file mixing 3 sync protocols)** — the single module that inlined per-record subscription CRUD + the outbound push path (951-line region) + the receiver path (909-line region) + standalone media-library sync + CoS-history/tasks sync is now split into one concern per file: `peerSyncShared.js` (state machine, constants, peer-capability helpers, the cross-cutting event bus), `peerSyncAssets.js` (asset manifest build/diff/hash + the receiver-side asset-pull worker, reused by every receive path), `peerSyncPush.js` (the `pushRecordToPeer` pipeline + payload builder + schema-gate bookkeeping), `peerSyncReceive.js` (`applyIncomingPush` + reverse-subscribe + merge dispatch), `peerMediaLibrarySync.js` (#1566 media-library sweep), and `peerCosSync.js` (#1650 CoS history + tasks). `peerSync.js` (~985 lines) stays the orchestrator — subscription CRUD, the debounced push scheduler, the `recordEvents`/`peer:online` listeners, and the boot-time `registerSubscriptionAdapter` wiring — and re-exports the extracted modules' public surface so every existing importer (routes, `sharing/index.js`, `dataSync`, the test suite) keeps working unchanged. The leaf-`peerSyncShared` design keeps the only module cycle (`peerSync` ↔ `peerSyncReceive`, both call-time-only) safe under ESM. Verified behavior-preserving: the full server suite produces byte-identical pass/fail results before and after (zero regressions, 15,092 tests), the DB suite is 156/156 green, and the server smoke-boots cleanly. (#1830)
- **Decomposed `server/lib/editorial/checkRegistry.js` (7,474-line god file)** — the single module that held ~2,400 lines of shared infra plus a 68-entry `EDITORIAL_CHECKS` array (each embedding a full `run(ctx)` closure) is now split: shared infra lives in `checkInfra.js`, the 68 checks are grouped by category into `checks/*.js` (`naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`), and `checkRegistry.js` (~480 lines) stays the public entry point — assembling `EDITORIAL_CHECKS` from the per-category arrays and keeping the registry's lookup/state helpers. The check files import shared infra from `checkInfra.js` (not back through the registry) so the `EDITORIAL_CHECKS` spread can't hit a TDZ on the checks' eagerly-evaluated `configSchema`s. The editorial barrel's public API is byte-for-byte identical (173 exports, verified) and all editorial + runner tests pass unchanged. (#1829)
- **Dropped the `sax` dependency from the Apple Health XML importer** — the 500MB-export streaming path now uses a self-contained ~190-line `Record` parser (`server/services/appleHealthXmlParser.js`) that splits the byte stream on `<Record>` tag boundaries and parses attributes with a quote-aware scan, preserving the prior backpressure (caller pauses the source stream) and error-skip (malformed records dropped, not fatal) behavior. Per the PortOS "write small helpers yourself" policy; covered by new unit + chunk-boundary tests. Partial-ships the `sax` half of #1824; the client `three-fenestra` shader replacement is tracked separately. (#1824)
+- **[issue-1837] On-disk JSON writes are now crash-safe across ~50 service/route files** — ~73 persistence sites used a raw `writeFile(path, JSON.stringify(data, null, 2))`, which truncates the JSON file if the process crashes mid-write (leaving an unparseable half-record on disk). Each was swapped to the canonical `atomicWrite` helper (`server/lib/fileUtils.js`), which writes to a temp file and atomically renames it over the target so readers never see a partial write. Covers brain storage, run/agent metadata, decision log, meatspace (calendar/alcohol/nicotine/health/post), mortal-loom store, identity goals, image/video sidecars, GitHub/Google/Obsidian configs, taste/usage/genome/epigenetic stores, and the scaffolding routes. Sites that intentionally append a trailing newline keep their exact byte output (passed as a pre-stringified string), and `videoGen/local.js`'s `{ flag: 'wx' }` exclusive-create write is left as-is (atomicWrite can't replicate exclusive-create). (#1837)
diff --git a/server/routes/scaffoldExpress.js b/server/routes/scaffoldExpress.js
index 312ec54abc..a0728cc179 100644
--- a/server/routes/scaffoldExpress.js
+++ b/server/routes/scaffoldExpress.js
@@ -1,5 +1,6 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';
+import { atomicWrite } from '../lib/fileUtils.js';
// Inline CORS middleware snippet for generated projects (no cors package dependency)
const CORS_SNIPPET = `app.use((req, res, next) => {
@@ -23,7 +24,7 @@ export async function scaffoldExpress(repoPath, dirName, apiPort, addStep) {
express: '^4.21.2'
}
};
- await writeFile(join(repoPath, 'package.json'), JSON.stringify(pkg, null, 2));
+ await atomicWrite(join(repoPath, 'package.json'), pkg);
await writeFile(join(repoPath, 'index.js'), `import express from 'express';
diff --git a/server/routes/scaffoldPortOS.js b/server/routes/scaffoldPortOS.js
index 0b61dffa09..320ac4ddfe 100644
--- a/server/routes/scaffoldPortOS.js
+++ b/server/routes/scaffoldPortOS.js
@@ -1,6 +1,6 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, ensureDirs } from '../lib/fileUtils.js';
// Inline CORS middleware snippet for generated projects (no cors package dependency)
const CORS_SNIPPET = `app.use((req, res, next) => {
@@ -38,7 +38,7 @@ export async function scaffoldPortOS(repoPath, name, dirName, uiPort, apiPort, a
'concurrently': '^8.2.2'
}
};
- await writeFile(join(repoPath, 'package.json'), JSON.stringify(rootPkg, null, 2));
+ await atomicWrite(join(repoPath, 'package.json'), rootPkg);
// === Client package.json ===
const clientPkg = {
@@ -68,7 +68,7 @@ export async function scaffoldPortOS(repoPath, name, dirName, uiPort, apiPort, a
'vite': '^6.0.6'
}
};
- await writeFile(join(clientDir, 'package.json'), JSON.stringify(clientPkg, null, 2));
+ await atomicWrite(join(clientDir, 'package.json'), clientPkg);
// === Client vite.config.js ===
await writeFile(join(clientDir, 'vite.config.js'), `import { defineConfig } from 'vite';
@@ -277,7 +277,7 @@ export default function AIProvidersPage() {
'vitest': '^2.1.8'
}
};
- await writeFile(join(serverDir, 'package.json'), JSON.stringify(serverPkg, null, 2));
+ await atomicWrite(join(serverDir, 'package.json'), serverPkg);
// === Server index.js ===
await writeFile(join(serverDir, 'index.js'), `import express from 'express';
@@ -397,7 +397,7 @@ export default defineConfig({
}
}
};
- await writeFile(join(dataDir, 'providers.json'), JSON.stringify(defaultProviders, null, 2));
+ await atomicWrite(join(dataDir, 'providers.json'), defaultProviders);
addStep('Create default data', 'done');
// === GitHub Actions CI ===
diff --git a/server/routes/scaffoldVite.js b/server/routes/scaffoldVite.js
index dc1f0cda24..a63c1658f2 100644
--- a/server/routes/scaffoldVite.js
+++ b/server/routes/scaffoldVite.js
@@ -2,7 +2,7 @@ import { writeFile, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { spawn } from 'child_process';
-import { ensureDir } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir } from '../lib/fileUtils.js';
import { safeJSONParse } from '../lib/fileUtils.js';
// Inline CORS middleware snippet for generated projects (no cors package dependency)
@@ -80,7 +80,7 @@ app.listen(PORT, '0.0.0.0', () => {
pkg.scripts['dev:all'] = 'concurrently "npm run dev" "npm run server"';
pkg.devDependencies = pkg.devDependencies || {};
pkg.devDependencies.concurrently = '^8.2.2';
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2));
+ await atomicWrite(pkgPath, pkg);
addStep('Add Express server', 'done');
}
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 8cd6882294..f0524557dc 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -9,7 +9,7 @@ import { writeFile, mkdir } from 'fs/promises';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { recordSession, recordMessages } from './usage.js';
import { bufferedSpawn } from '../lib/bufferedSpawn.js';
-import { ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';
const RUNS_DIR = PATHS.runs;
@@ -45,7 +45,7 @@ export async function createAgentRun(agentId, task, model, provider, workspacePa
outputSize: 0
};
- await writeFile(join(runDir, 'metadata.json'), JSON.stringify(metadata, null, 2));
+ await atomicWrite(join(runDir, 'metadata.json'), metadata);
await writeFile(join(runDir, 'prompt.txt'), task.description || '');
await writeFile(join(runDir, 'output.txt'), '');
@@ -127,7 +127,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
}
}
- await writeFile(metaPath, JSON.stringify(metadata, null, 2));
+ await atomicWrite(metaPath, metadata);
await writeFile(join(runDir, 'output.txt'), output || '');
// Record usage for successful CoS agent runs (estimate ~4 chars per token)
diff --git a/server/services/appleHealthClinical.js b/server/services/appleHealthClinical.js
index 4bce05f5f2..fb386f7ff2 100644
--- a/server/services/appleHealthClinical.js
+++ b/server/services/appleHealthClinical.js
@@ -6,9 +6,8 @@
* into blood-tests.json.
*/
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { atomicWrite, safeJSONParse } from '../lib/fileUtils.js';
import { getBloodTests } from './meatspaceHealth.js';
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
@@ -285,7 +284,7 @@ export async function importClinicalRecords(jsonStrings, io) {
const newValues = fhirData.totalParsed;
await ensureDir(PATHS.meatspace);
- await writeFile(BLOOD_TESTS_FILE, JSON.stringify(merged, null, 2));
+ await atomicWrite(BLOOD_TESTS_FILE, merged);
const summary = {
clinicalRecords: jsonStrings.length,
diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.js
index e32fcdaba0..7ee7ce138e 100644
--- a/server/services/appleHealthIngest.js
+++ b/server/services/appleHealthIngest.js
@@ -5,9 +5,8 @@
* metric+timestamp, and day-partitioned file storage at data/health/YYYY-MM-DD.json.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
// === Pure Functions ===
@@ -61,7 +60,7 @@ export async function writeDayFile(dateStr, data) {
await ensureDir(PATHS.health);
data.updated = new Date().toISOString();
const filePath = join(PATHS.health, `${dateStr}.json`);
- await writeFile(filePath, JSON.stringify(data, null, 2));
+ await atomicWrite(filePath, data);
}
/**
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index 19510acbd5..f5b06abe0f 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -7,10 +7,9 @@
* Stories are stored as part of the digital twin data.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
@@ -175,7 +174,7 @@ async function loadStories() {
async function saveStories(data) {
await ensureDir(DATA_DIR);
- await writeFile(STORIES_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(STORIES_FILE, data);
}
async function loadConfig() {
@@ -185,7 +184,7 @@ async function loadConfig() {
async function saveConfig(config) {
await ensureDir(DATA_DIR);
- await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
+ await atomicWrite(CONFIG_FILE, config);
}
/**
diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.js
index f79be2c39c..9e9d89ee04 100644
--- a/server/services/autobiography.test.js
+++ b/server/services/autobiography.test.js
@@ -48,6 +48,13 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
const fs = await import('fs');
return {
ensureDir: vi.fn(),
+ // atomicWrite replaced raw writeFile(JSON.stringify) sites (#1837). Route it
+ // through the mocked fs/promises.writeFile so each test's existing
+ // writeFile.mockImplementation capture keeps working unchanged.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ return fsPromises.writeFile(filePath, payload);
+ }),
PATHS: { digitalTwin: '/mock/data/digital-twin' },
readJSONFile: vi.fn(async (filePath, defaultValue) => {
if (!fs.existsSync(filePath)) return defaultValue;
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index 3dcea42230..0d512b4632 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -22,10 +22,9 @@
* — that would bypass the sync log and silently diverge peers again.
*/
-import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import * as brainStorage from './brainStorage.js';
import { brainEvents, now } from './brainStorage.js';
@@ -61,7 +60,7 @@ export async function getSettings() {
export async function updateSettings(partial) {
const current = await getSettings();
const next = { ...current, ...partial };
- await writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2));
+ await atomicWrite(SETTINGS_FILE, next);
return next;
}
@@ -101,7 +100,7 @@ async function saveObsidianLocation(date, { obsidianPath, obsidianVaultId }) {
} else {
map[date] = { obsidianPath: obsidianPath ?? null, obsidianVaultId: obsidianVaultId ?? null };
}
- await writeFile(OBSIDIAN_LOCATIONS_FILE, JSON.stringify(map, null, 2));
+ await atomicWrite(OBSIDIAN_LOCATIONS_FILE, map);
}
// ── Synced journal entry store ───────────────────────────────────────────────
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
index 268fa20df3..ce1d947a82 100644
--- a/server/services/brainMemoryBridge.js
+++ b/server/services/brainMemoryBridge.js
@@ -9,14 +9,14 @@
* tagged with sourceAppId='brain'.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { brainEvents } from './brainStorage.js';
import * as brainStorage from './brainStorage.js';
import * as memory from './memoryBackend.js';
import * as embeddings from './memoryEmbeddings.js';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS } from '../lib/fileUtils.js';
import { listJournals, getJournal } from './brainJournal.js';
const BRIDGE_MAP_PATH = join(PATHS.brain, 'memory-bridge-map.json');
@@ -57,7 +57,7 @@ export async function loadBridgeMap() {
async function saveBridgeMap() {
const dir = dirname(BRIDGE_MAP_PATH);
if (!existsSync(dir)) await ensureDir(dir);
- await writeFile(BRIDGE_MAP_PATH, JSON.stringify(bridgeMap, null, 2));
+ await atomicWrite(BRIDGE_MAP_PATH, bridgeMap);
}
export function bridgeKey(brainType, brainId) {
diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.js
index 36d0ff0795..b2dbf720fa 100644
--- a/server/services/brainMemoryBridge.test.js
+++ b/server/services/brainMemoryBridge.test.js
@@ -28,6 +28,14 @@ vi.mock('fs/promises', () => ({
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { brain: '/tmp/test-brain' },
ensureDir: vi.fn(async () => {}),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) bridge-map site (#1837);
+ // route it through the mocked fs/promises.writeFile so it updates
+ // bridgeFileContents and a reloaded bridge sees the persisted map.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
}));
vi.mock('./memoryBackend.js', () => ({ createMemory, updateMemory, updateMemoryEmbedding, deleteMemory }));
vi.mock('./memoryEmbeddings.js', () => ({ generateMemoryEmbedding }));
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 00b5018240..4526923991 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -7,12 +7,12 @@
* - In-memory caching with TTL for performance
*/
-import { readFile, writeFile, appendFile } from 'fs/promises';
+import { readFile, appendFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import EventEmitter from 'events';
-import { ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { getInstanceId } from './instances.js';
import * as brainSyncLog from './brainSyncLog.js';
@@ -177,7 +177,7 @@ export async function loadMeta() {
*/
export async function saveMeta(meta) {
await ensureBrainDir();
- await writeFile(FILES.meta, JSON.stringify(meta, null, 2));
+ await atomicWrite(FILES.meta, meta);
caches.meta.data = meta;
caches.meta.timestamp = Date.now();
brainEvents.emit('meta:changed', meta);
@@ -219,7 +219,7 @@ async function loadJsonStore(type) {
*/
async function saveJsonStore(type, data) {
await ensureBrainDir();
- await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ await atomicWrite(FILES[type], data);
caches[type].data = data;
caches[type].timestamp = Date.now();
brainEvents.emit(`${type}:changed`, data);
@@ -825,7 +825,7 @@ export async function applyRemoteRecord(type, id, record, op) {
}
await ensureBrainDir();
- await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ await atomicWrite(FILES[type], data);
caches[type].data = data;
caches[type].timestamp = Date.now();
@@ -853,7 +853,7 @@ export async function pruneTombstones(type, cutoffMs) {
}
if (pruned > 0) {
await ensureBrainDir();
- await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ await atomicWrite(FILES[type], data);
caches[type].data = data;
caches[type].timestamp = Date.now();
}
@@ -884,7 +884,7 @@ export async function backfillOriginInstanceId() {
if (changed) {
await ensureBrainDir();
- await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ await atomicWrite(FILES[type], data);
caches[type].data = data;
caches[type].timestamp = Date.now();
}
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index f2d65365be..b87c42d321 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -1,6 +1,6 @@
-import { readdir, unlink, writeFile } from 'fs/promises';
+import { readdir, unlink } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, filterBySearch as genericFilterBySearch, PATHS, readJSONFile, safeDate, UUID_RE } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, readJSONFile, safeDate, UUID_RE } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import { getAccount, updateSyncStatus } from './calendarAccounts.js';
@@ -38,7 +38,7 @@ export async function loadCache(accountId) {
export async function saveCache(accountId, cache) {
await ensureDir(CACHE_DIR);
const filePath = join(CACHE_DIR, `${accountId}.json`);
- await writeFile(filePath, JSON.stringify(cache, null, 2));
+ await atomicWrite(filePath, cache);
}
function filterDeclinedAndCancelled(events) {
diff --git a/server/services/character.js b/server/services/character.js
index 934df766c1..793d5a3d01 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -5,8 +5,7 @@
import crypto from 'crypto';
import path from 'path';
-import { writeFile } from 'fs/promises';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import * as jiraService from './jira.js';
import * as cosService from './cos.js';
@@ -86,7 +85,7 @@ export async function getCharacter() {
export async function saveCharacter(data) {
await ensureDir(PATHS.data);
data.updatedAt = new Date().toISOString();
- await writeFile(CHARACTER_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(CHARACTER_FILE, data);
return data;
}
diff --git a/server/services/character.test.js b/server/services/character.test.js
index 46827710f1..b029eaa490 100644
--- a/server/services/character.test.js
+++ b/server/services/character.test.js
@@ -9,6 +9,14 @@ vi.mock('../lib/fileUtils.js', () => ({
ensureDir: vi.fn(async () => {}),
readJSONFile: vi.fn(async (_file, fallback) => (store.value ?? fallback)),
writeFile: vi.fn(),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) site (#1837); route
+ // it through the mocked fs/promises.writeFile so the in-memory store update
+ // (and read-modify-save round-trip) keeps working unchanged.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
}));
// character.js eagerly imports the jira/cos services at module load; stub them
diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.js
index f05cf430a6..f2ccb60106 100644
--- a/server/services/chatgptImport.js
+++ b/server/services/chatgptImport.js
@@ -20,8 +20,8 @@
*/
import { join } from 'path';
-import { writeFile, unlink } from 'fs/promises';
-import { ensureDir, PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { unlink } from 'fs/promises';
+import { atomicWrite, ensureDir, PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
import { createMemoryEntry } from './brainStorage.js';
const MAX_MEMORY_CONTENT = 9800;
@@ -445,7 +445,7 @@ async function archiveConversation(summary) {
transcript: summary.transcript,
importedAt: new Date().toISOString()
};
- await writeFile(filePath, JSON.stringify(payload, null, 2), 'utf8');
+ await atomicWrite(filePath, payload);
return fname;
}
diff --git a/server/services/clinvar.js b/server/services/clinvar.js
index c1f2239054..b2ae416835 100644
--- a/server/services/clinvar.js
+++ b/server/services/clinvar.js
@@ -4,7 +4,7 @@ import { join } from 'path';
import { createGunzip } from 'zlib';
import { createInterface } from 'readline';
import { pipeline } from 'stream/promises';
-import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const GENOME_DIR = PATHS.meatspace;
const CLINVAR_GZ = join(GENOME_DIR, 'clinvar-raw.txt.gz');
@@ -274,7 +274,7 @@ export async function syncClinvar(onProgress) {
downloadSize: downloadResult.size,
indexSize: Buffer.byteLength(indexJson)
};
- await writeFile(CLINVAR_META, JSON.stringify(meta, null, 2));
+ await atomicWrite(CLINVAR_META, meta);
// Clean up the raw gz file to save disk space
await unlink(CLINVAR_GZ).catch(() => {});
diff --git a/server/services/codexSummaryRepair.js b/server/services/codexSummaryRepair.js
index ed4f529cca..20d8b25ba1 100644
--- a/server/services/codexSummaryRepair.js
+++ b/server/services/codexSummaryRepair.js
@@ -5,10 +5,9 @@
// display, this module re-extracts the real assistant tail from the
// matching output.txt and rewrites metadata.json in place.
-import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
-import { tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
// Any taskSummary above this size is almost certainly a transcript dump —
@@ -46,7 +45,7 @@ export async function repairCodexTaskSummary(agentDir, agent) {
if (!rawContent) return null;
const raw = JSON.parse(rawContent);
raw.metadata = { ...(raw.metadata || {}), taskSummary: repaired, simplifySummary: null };
- await writeFile(metaPath, JSON.stringify(raw, null, 2));
+ await atomicWrite(metaPath, raw);
const beforeSize = (storedTask?.length || 0) + (storedSimplify?.length || 0);
console.log(`🔧 Repaired Codex task summary for ${agent.id} (${beforeSize} → ${repaired.length} chars)`);
diff --git a/server/services/cos.js b/server/services/cos.js
index 88783d534c..2b3c1dd5b2 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -24,7 +24,7 @@ import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningIns
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
import { recordJobExecution } from './autonomousJobs.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { atomicWrite, safeJSONParse } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
@@ -592,11 +592,11 @@ export async function saveScript(name, content, metadata = {}) {
// Save metadata
const metaPath = join(SCRIPTS_DIR, `${name}.json`);
- await writeFile(metaPath, JSON.stringify({
+ await atomicWrite(metaPath, {
name,
createdAt: new Date().toISOString(),
...metadata
- }, null, 2));
+ });
return { path: scriptPath, name };
}
diff --git a/server/services/decisionLog.js b/server/services/decisionLog.js
index 8844f5f4cc..d444ad493e 100644
--- a/server/services/decisionLog.js
+++ b/server/services/decisionLog.js
@@ -6,9 +6,8 @@
* This helps users understand CoS behavior and identify patterns.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { cosEvents } from './cosEvents.js';
const DATA_DIR = PATHS.cos;
@@ -65,7 +64,7 @@ async function loadDecisions() {
*/
async function saveDecisions(data) {
decisionCache = data;
- await writeFile(DECISION_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(DECISION_FILE, data);
}
/**
diff --git a/server/services/decisionLog.test.js b/server/services/decisionLog.test.js
index 8cb50d77d1..fd06c6ae18 100644
--- a/server/services/decisionLog.test.js
+++ b/server/services/decisionLog.test.js
@@ -17,6 +17,14 @@ vi.mock('./cosEvents.js', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) site (#1837); route
+ // it through the mocked fs/promises.writeFile so writeFile.mockImplementation
+ // capture in the tests keeps working unchanged.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
PATHS: { cos: '/mock/data/cos' },
readJSONFile: vi.fn()
}));
@@ -71,6 +79,11 @@ describe('decisionLog.js', () => {
}));
vi.doMock('../lib/fileUtils.js', () => ({
ensureDir: vi.fn(),
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
PATHS: { cos: '/mock/data/cos' },
readJSONFile: vi.fn()
}));
diff --git a/server/services/epigenetic.js b/server/services/epigenetic.js
index 6716733ba6..10b5e40b4a 100644
--- a/server/services/epigenetic.js
+++ b/server/services/epigenetic.js
@@ -1,7 +1,6 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.meatspace;
const EPIGENETIC_FILE = join(DATA_DIR, 'epigenetic.json');
@@ -200,7 +199,7 @@ async function loadData() {
async function saveData(data) {
await ensureDir(DATA_DIR);
data.lastUpdated = new Date().toISOString();
- await writeFile(EPIGENETIC_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(EPIGENETIC_FILE, data);
}
/**
diff --git a/server/services/feedbackLoop.js b/server/services/feedbackLoop.js
index 774c95ec6c..0d516f7cd4 100644
--- a/server/services/feedbackLoop.js
+++ b/server/services/feedbackLoop.js
@@ -6,11 +6,11 @@
* Tracks feedback patterns and adjusts document weights for confidence scoring.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { digitalTwinEvents } from './digital-twin.js';
const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
@@ -52,7 +52,7 @@ async function saveFeedback(data) {
await ensureDir(DIGITAL_TWIN_DIR);
}
data.updatedAt = now();
- await writeFile(FEEDBACK_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(FEEDBACK_FILE, data);
feedbackCache = data;
}
diff --git a/server/services/genome.js b/server/services/genome.js
index 447bea9ab5..4915119b26 100644
--- a/server/services/genome.js
+++ b/server/services/genome.js
@@ -1,7 +1,7 @@
import { writeFile, unlink } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { CURATED_MARKERS, MARKER_CATEGORIES, classifyGenotype, formatGenotype, resolveApoeHaplotype } from '../lib/curatedGenomeMarkers.js';
const GENOME_DIR = PATHS.meatspace;
@@ -36,7 +36,7 @@ async function loadMeta() {
async function saveMeta(meta) {
await ensureGenomeDir();
- await writeFile(META_FILE, JSON.stringify(meta, null, 2));
+ await atomicWrite(META_FILE, meta);
}
/**
diff --git a/server/services/github.js b/server/services/github.js
index 613b2192ec..d1d39988f0 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -1,7 +1,6 @@
import { spawn } from 'child_process';
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { readJSONFile, PATHS, ensureDir } from '../lib/fileUtils.js';
+import { atomicWrite, readJSONFile, PATHS, ensureDir } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import { getSettings, updateSettings } from './settings.js';
@@ -31,7 +30,7 @@ async function load() {
async function save(data) {
await ensureDir(DATA_DIR);
- await writeFile(REPOS_FILE, JSON.stringify(data, null, 2) + '\n');
+ await atomicWrite(REPOS_FILE, JSON.stringify(data, null, 2) + '\n');
cache = data;
cacheTimestamp = Date.now();
}
diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.js
index 401f297527..6fa7e38017 100644
--- a/server/services/goalCheckIn.js
+++ b/server/services/goalCheckIn.js
@@ -1,7 +1,6 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { PATHS, readJSONFile, ensureDir } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
@@ -114,7 +113,7 @@ export async function runGoalCheckIn() {
goals.updatedAt = now;
await ensureDir(PATHS.digitalTwin);
- await writeFile(GOALS_FILE, JSON.stringify(goals, null, 2));
+ await atomicWrite(GOALS_FILE, goals);
// Send Telegram notification
const statusEmoji = { 'on-track': '🟢', 'behind': '🟡', 'at-risk': '🔴' };
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 9c0897a3b8..b96ca97f1f 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -1,7 +1,7 @@
import { OAuth2Client } from 'google-auth-library';
import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
const AUTH_DIR = join(PATHS.calendar, 'google-auth');
@@ -29,7 +29,7 @@ export async function getCredentials() {
export async function saveCredentials({ clientId, clientSecret }) {
await ensureAuthDir();
const credentials = { clientId, clientSecret, redirectUri: OAUTH_REDIRECT_URI };
- await writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2));
+ await atomicWrite(CREDENTIALS_FILE, credentials);
oAuth2Client = null; // Reset client
console.log('📅 Google OAuth credentials saved');
return credentials;
@@ -44,7 +44,7 @@ export async function getTokens() {
async function saveTokens(tokens) {
await ensureAuthDir();
- await writeFile(TOKENS_FILE, JSON.stringify(tokens, null, 2));
+ await atomicWrite(TOKENS_FILE, tokens);
console.log('📅 Google OAuth tokens saved');
}
diff --git a/server/services/identity.test.js b/server/services/identity.test.js
index 4fd368d394..6d278f4db7 100644
--- a/server/services/identity.test.js
+++ b/server/services/identity.test.js
@@ -1,5 +1,29 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+// identity/store.js now persists via the canonical atomicWrite (#1837), which
+// writes to a temp file then renames it over the target (with unlink cleanup on
+// error) and ensureDir's the parent. The integration tests below mock
+// fs/promises with a simple path-keyed in-memory store; makeFsPromisesStore()
+// supplies the rename/unlink/mkdir the real atomicWrite needs so the temp→final
+// move lands in the same store the reads come from.
+function makeFsPromisesStore() {
+ const store = {};
+ return {
+ readFile: vi.fn(async (path) => {
+ if (path in store) return store[path];
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+ }),
+ writeFile: vi.fn(async (path, data) => { store[path] = data; }),
+ rename: vi.fn(async (from, to) => {
+ if (!(from in store)) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+ store[to] = store[from];
+ delete store[from];
+ }),
+ unlink: vi.fn(async (path) => { delete store[path]; }),
+ mkdir: vi.fn(async () => {}),
+ };
+}
+
// === Pure function copies for unit testing (avoids complex mocking) ===
const SLEEP_MARKERS = {
@@ -848,19 +872,7 @@ describe('Integration: deriveChronotype', () => {
vi.resetModules();
// Mock fs/promises
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
// Mock genome service
vi.doMock('./genome.js', () => ({
@@ -949,19 +961,7 @@ describe('Integration: getIdentityStatus', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -998,17 +998,7 @@ describe('Integration: getIdentityStatus', () => {
it('should show genome as active when markers exist', async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => { store[path] = data; }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1062,19 +1052,7 @@ describe('Integration: deriveLongevity', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1150,19 +1128,7 @@ describe('Integration: Goal CRUD', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1355,19 +1321,7 @@ describe('Integration: Goal Tree', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1425,19 +1379,7 @@ describe('Integration: Progress Log', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1498,19 +1440,7 @@ describe('Integration: Calendar Linking', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1594,19 +1524,7 @@ describe('Integration: applyGoalOrganization', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1763,19 +1681,7 @@ describe('Integration: organizeGoals', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => {
- store[path] = data;
- }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1851,17 +1757,7 @@ describe('Integration: organizeGoals', () => {
it('should throw when no AI provider is available', async () => {
vi.resetModules();
- vi.doMock('fs/promises', () => {
- const store = {};
- return {
- readFile: vi.fn(async (path) => {
- if (store[path]) return store[path];
- throw new Error('ENOENT');
- }),
- writeFile: vi.fn(async (path, data) => { store[path] = data; }),
- mkdir: vi.fn(async () => {})
- };
- });
+ vi.doMock('fs/promises', makeFsPromisesStore);
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
diff --git a/server/services/identity/store.js b/server/services/identity/store.js
index 7894d98afd..18bf3481fb 100644
--- a/server/services/identity/store.js
+++ b/server/services/identity/store.js
@@ -1,6 +1,5 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';
import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';
// === Goal normalization defaults ===
@@ -100,7 +99,7 @@ export async function loadJSON(filePath, defaultVal) {
export async function saveJSON(filePath, data) {
await ensureIdentityDir();
- await writeFile(filePath, JSON.stringify(data, null, 2));
+ await atomicWrite(filePath, data);
// Mirror goals array into MortalLoom.json so iOS/macOS app sees the change.
if (filePath === GOALS_FILE && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {
await mlReplace('goals', data.goals);
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 0da735332c..e86bf43696 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -26,7 +26,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { randomUUID } from 'crypto';
-import { ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -364,7 +364,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
// (which doesn't expose one) — uniquely identifies the run and is
// useful for traceability even though it doesn't reproduce the output.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
- await writeFile(sidecar, JSON.stringify({ ...meta, codexSessionId: sessionId }, null, 2)).catch(() => {});
+ await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId }).catch(() => {});
// Cleaners run BEFORE the SSE complete + completed events so subscribers
// see the cleaned bytes. codex output is the highest-value target for
// C2PA stripping because gpt-image is the one provider that embeds
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 88e89b03f5..3384aa1719 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -19,7 +19,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
+import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -784,7 +784,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// and Remix flow can recover prompt/seed/steps even if mflux's own
// --metadata sidecar lives at a slightly different filename shape.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
- await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});
+ await atomicWrite(sidecar, meta).catch(() => {});
// Cleaners run BEFORE the SSE complete + completed events so subscribers
// see the cleaned bytes. Local FLUX renders never carry C2PA chunks so
// cleanC2PA is a no-op on local — denoise is the only mode that does
@@ -913,7 +913,7 @@ export async function setImageHidden(filename, hidden) {
assertGalleryFilename(filename);
const { path: sidecarPath, metadata } = await readImageSidecar(filename);
metadata.hidden = !!hidden;
- await writeFile(sidecarPath, JSON.stringify(metadata, null, 2));
+ await atomicWrite(sidecarPath, metadata);
return { ok: true, hidden: metadata.hidden };
}
diff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.js
index e7283a4d0a..1f07b6d056 100644
--- a/server/services/imageGen/variants.js
+++ b/server/services/imageGen/variants.js
@@ -21,7 +21,7 @@
import { readFile, writeFile } from 'fs/promises';
import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
-import { PATHS } from '../../lib/fileUtils.js';
+import { atomicWrite, PATHS } from '../../lib/fileUtils.js';
import { cleanImageBuffer } from '../../lib/imageClean.js';
import { removeCornerWatermark } from '../../lib/imageWatermark.js';
import { applyLightRegen, computePixelDelta } from './regen.js';
@@ -91,7 +91,7 @@ export async function persistVariant({
await Promise.all([
writeFile(outPath, data),
- writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
+ atomicWrite(sidecarPath, variantMeta),
]);
const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {
diff --git a/server/services/insightsService.js b/server/services/insightsService.js
index 13d70ae3ee..ce4d0fc8b9 100644
--- a/server/services/insightsService.js
+++ b/server/services/insightsService.js
@@ -11,9 +11,8 @@
* 3. Cross-domain narrative (INS-04) — LLM generation with diff support
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { getGenomeSummary } from './genome.js';
import { getBloodTests } from './meatspaceHealth.js';
import { MARKER_CATEGORIES, CURATED_MARKERS } from '../lib/curatedGenomeMarkers.js';
@@ -407,7 +406,7 @@ Example format:
generatedAt: new Date().toISOString(),
model: selectedModel
};
- await writeFile(THEMES_FILE, JSON.stringify(output, null, 2));
+ await atomicWrite(THEMES_FILE, output);
console.log(`🧠 Taste-identity themes generated: ${themes.length} themes`);
@@ -512,7 +511,7 @@ Respond with only the narrative text, no JSON, no headings, no markdown.`;
previousGeneratedAt: existingNarrative?.generatedAt ?? null,
model: selectedModel
};
- await writeFile(NARRATIVE_FILE, JSON.stringify(output, null, 2));
+ await atomicWrite(NARRATIVE_FILE, output);
console.log(`🔮 Cross-domain narrative generated (${newText.length} chars)`);
diff --git a/server/services/jiraReports.js b/server/services/jiraReports.js
index 861a84c8e5..f4c680bd13 100644
--- a/server/services/jiraReports.js
+++ b/server/services/jiraReports.js
@@ -3,9 +3,9 @@
* Generates weekly status reports from JIRA for JIRA-enabled projects
*/
-import { writeFile, readdir } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { getInstances, createJiraClient } from './jira.js';
import { getActiveApps } from './apps.js';
import { callProviderAISimple } from '../lib/aiProvider.js';
@@ -239,7 +239,7 @@ export async function generateReport(appId, app) {
await ensureDir(REPORTS_DIR);
const filename = `${appId}-${report.date}.json`;
- await writeFile(join(REPORTS_DIR, filename), JSON.stringify(report, null, 2));
+ await atomicWrite(join(REPORTS_DIR, filename), report);
console.log(`📊 JIRA status report generated for ${app.name} (${jiraConfig.projectKey})`);
return report;
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 8cb505c385..feb40cb307 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -990,7 +990,7 @@ async function registerTrainedLora({
const sidecar = buildTrainedSidecar({
run, result, filename, previewImageUrl, sizeBytes, selectedStep, autoSelected,
});
- await writeFile(`${dest}.metadata.json`, JSON.stringify(sidecar, null, 2) + '\n');
+ await atomicWrite(`${dest}.metadata.json`, JSON.stringify(sidecar, null, 2) + '\n');
return { sizeBytes, sidecar };
}
diff --git a/server/services/loras.js b/server/services/loras.js
index d54d8f9ca1..3f5ae45c43 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -18,14 +18,14 @@
*/
import { existsSync } from 'fs';
-import { link, readFile, rename, rm, stat, unlink, writeFile } from 'fs/promises';
+import { link, readFile, rename, rm, stat, unlink } from 'fs/promises';
import { createWriteStream } from 'fs';
import { randomBytes } from 'crypto';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import {
applyDownloadToken,
@@ -235,7 +235,7 @@ export const patchLoraSidecar = async (filename, patch) => {
}
const current = (await readSidecar(filename)) || { filename };
const next = { ...current, ...patch, filename };
- await writeFile(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
+ await atomicWrite(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
return next;
};
@@ -403,7 +403,7 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
});
const sidecar = buildSidecar({ model, version, file, filename });
- await writeFile(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
console.log(`✅ Installed Civitai LoRA: ${filename}`);
return sidecar;
};
@@ -472,7 +472,7 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch } = {})
});
const sidecar = buildHfLoraSidecar({ repo, revision, file, model, family, filename });
- await writeFile(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
console.log(`✅ Installed HuggingFace LoRA: ${filename}`);
return sidecar;
};
diff --git a/server/services/meatspace.js b/server/services/meatspace.js
index 03c75da8d6..8982fc0824 100644
--- a/server/services/meatspace.js
+++ b/server/services/meatspace.js
@@ -5,9 +5,9 @@
* and LEV 2045 tracker. Reads genome/longevity data from Digital Twin.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { getSnpIndex } from './genome.js';
import { mlGetProfileIfEnabled, mlPatchProfileIfEnabled } from './mortalLoomStore.js';
@@ -68,7 +68,7 @@ async function loadConfig() {
async function saveConfig(config) {
await ensureMeatspaceDir();
- await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
+ await atomicWrite(CONFIG_FILE, config);
}
// === Sex Detection ===
@@ -292,7 +292,7 @@ export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {
if (goals) {
goals.birthDate = birthDate;
goals.updatedAt = new Date().toISOString();
- await writeFile(join(PATHS.digitalTwin, 'goals.json'), JSON.stringify(goals, null, 2));
+ await atomicWrite(join(PATHS.digitalTwin, 'goals.json'), goals);
}
}
diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.js
index 5b735bf748..043559a4ea 100644
--- a/server/services/meatspaceAlcohol.js
+++ b/server/services/meatspaceAlcohol.js
@@ -5,9 +5,9 @@
* Reads/writes daily-log.json entries for alcohol data.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
import {
isMortalLoomEnabled,
readDailyLogIfEnabled,
@@ -150,7 +150,7 @@ async function loadDailyLog() {
async function saveDailyLog(log) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));
+ await atomicWrite(DAILY_LOG_FILE, log);
averageCache = null; // Invalidate cache
}
@@ -334,7 +334,7 @@ async function loadCustomDrinks() {
async function saveCustomDrinks(data) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(CUSTOM_DRINKS_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(CUSTOM_DRINKS_FILE, data);
}
export async function getCustomDrinks() {
diff --git a/server/services/meatspaceCalendar.js b/server/services/meatspaceCalendar.js
index 42d6981c53..8efbfe6c57 100644
--- a/server/services/meatspaceCalendar.js
+++ b/server/services/meatspaceCalendar.js
@@ -6,10 +6,10 @@
* based on birth date and life expectancy.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { getDeathClock } from './meatspace.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -190,7 +190,7 @@ async function loadActivities() {
async function saveActivities(data) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(ACTIVITIES_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(ACTIVITIES_FILE, data);
}
// === Default Activities ===
@@ -223,7 +223,7 @@ async function loadEvents() {
async function saveEvents(data) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(EVENTS_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(EVENTS_FILE, data);
}
export async function getLifeEvents() {
diff --git a/server/services/meatspaceCustomDrinks.test.js b/server/services/meatspaceCustomDrinks.test.js
index 889eeb73b1..0481e3341a 100644
--- a/server/services/meatspaceCustomDrinks.test.js
+++ b/server/services/meatspaceCustomDrinks.test.js
@@ -12,7 +12,15 @@ tryReadFile: vi.fn().mockResolvedValue(null),
data: '/mock/data',
meatspace: '/mock/data/meatspace'
},
- ensureDir: vi.fn().mockResolvedValue(undefined)
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) sites (#1837); route
+ // it through the mocked fs/promises.writeFile so the existing
+ // writeFile.toHaveBeenCalled / JSON.parse(calls[0][1]) asserts keep working.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ })
}));
import { writeFile } from 'fs/promises';
diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.js
index a6d8fb99a0..7cc9c9cd91 100644
--- a/server/services/meatspaceHealth.js
+++ b/server/services/meatspaceHealth.js
@@ -6,9 +6,8 @@
* to the shared MortalLoom.json; otherwise local PortOS data files are used.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import {
isMortalLoomEnabled,
mlArrayIfEnabled,
@@ -30,7 +29,7 @@ const byDate = (a, b) => (a.date || '').localeCompare(b.date || '');
async function writeLocal(file, data) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(file, JSON.stringify(data, null, 2));
+ await atomicWrite(file, data);
}
// === Blood Tests ===
diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.js
index f8b438d33c..2399af1ce2 100644
--- a/server/services/meatspaceNicotine.js
+++ b/server/services/meatspaceNicotine.js
@@ -5,9 +5,8 @@
* Stores data in the shared daily-log.json under the `nicotine` key per entry.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
import {
isMortalLoomEnabled,
readDailyLogIfEnabled,
@@ -110,7 +109,7 @@ async function loadDailyLog() {
async function saveDailyLog(log) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));
+ await atomicWrite(DAILY_LOG_FILE, log);
averageCache = null;
}
@@ -281,7 +280,7 @@ async function loadCustomProducts() {
async function saveCustomProducts(data) {
await ensureDir(MEATSPACE_DIR);
- await writeFile(CUSTOM_PRODUCTS_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(CUSTOM_PRODUCTS_FILE, data);
}
export async function getCustomProducts() {
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index aed5b38d76..0ebee2326d 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -5,10 +5,9 @@
* Reads/writes to meatspace data files.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { deepMerge, isPlainObject } from '../lib/objects.js';
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
@@ -61,7 +60,7 @@ export async function updatePostConfig(updates) {
const config = await getPostConfig();
const merged = deepMerge(config, updates);
await ensureMeatspaceDir();
- await writeFile(CONFIG_FILE, JSON.stringify(merged, null, 2));
+ await atomicWrite(CONFIG_FILE, merged);
console.log(`🧪 POST config updated`);
return merged;
}
@@ -144,7 +143,7 @@ export async function submitPostSession(sessionData) {
data.sessions.push(session);
data.sessions.sort((a, b) => a.date.localeCompare(b.date));
await ensureMeatspaceDir();
- await writeFile(SESSIONS_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(SESSIONS_FILE, data);
console.log(`🧪 POST session saved: score=${session.score} modules=${session.modules.join(',')}`);
return session;
}
diff --git a/server/services/memoryBM25.js b/server/services/memoryBM25.js
index 1e279639d3..ec88e882f7 100644
--- a/server/services/memoryBM25.js
+++ b/server/services/memoryBM25.js
@@ -17,7 +17,7 @@ import {
deserializeIndex,
getIndexStats
} from '../lib/bm25.js'
-import { ensureDir, PATHS } from '../lib/fileUtils.js'
+import { atomicWrite, ensureDir, PATHS } from '../lib/fileUtils.js'
const DATA_DIR = PATHS.memory
const INDEX_FILE = path.join(DATA_DIR, 'bm25-index.json')
@@ -77,7 +77,7 @@ async function saveIndex() {
await ensureDir(DATA_DIR)
const serialized = serializeIndex(indexCache)
- await fs.writeFile(INDEX_FILE, JSON.stringify(serialized, null, 2))
+ await atomicWrite(INDEX_FILE, serialized)
isDirty = false
console.log(`💾 BM25 index saved: ${indexCache.totalDocs} docs, ${Object.keys(indexCache.terms).length} terms`)
diff --git a/server/services/memoryBM25.test.js b/server/services/memoryBM25.test.js
index 43c2b58720..4efdba532b 100644
--- a/server/services/memoryBM25.test.js
+++ b/server/services/memoryBM25.test.js
@@ -11,6 +11,14 @@ vi.mock('fs', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(),
+ // atomicWrite replaced the raw fs.writeFile(JSON.stringify) index-save site (#1837);
+ // route it through the mocked fs.promises.writeFile (this file mocks 'fs', not
+ // 'fs/promises') so saveIndex resolves cleanly without touching real disk.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2)
+ const { promises } = await import('fs')
+ return promises.writeFile(filePath, payload)
+ }),
PATHS: { memory: '/mock/data/memory' }
}))
diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.js
index 43618e50d0..2fbba0b1ae 100644
--- a/server/services/memoryClassifier.js
+++ b/server/services/memoryClassifier.js
@@ -5,11 +5,11 @@
* Falls back to pattern-based extraction if LLM is unavailable.
*/
-import { readFile, writeFile } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { getStageTemplate } from './promptService.js';
-import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { readResponseJson } from '../lib/readResponseJson.js';
import { getMemories } from './memoryBackend.js';
@@ -74,7 +74,7 @@ export async function updateConfig(updates) {
await ensureDir(PATHS.data);
}
- await writeFile(MEMORY_CONFIG_FILE, JSON.stringify(newConfig, null, 2));
+ await atomicWrite(MEMORY_CONFIG_FILE, newConfig);
configCache = newConfig;
return newConfig;
diff --git a/server/services/messageActions.js b/server/services/messageActions.js
index b061a33c52..da4d5293bf 100644
--- a/server/services/messageActions.js
+++ b/server/services/messageActions.js
@@ -2,9 +2,8 @@ import { getAccount } from './messageAccounts.js';
import { getMessage } from './messageSync.js';
import { findOrOpenPage, getPages, isAuthPage, evaluateOnPage } from './messagePlaywrightSync.js';
import { recordCorrection } from './messageTriageRules.js';
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';
const CACHE_DIR = join(PATHS.messages, 'cache');
@@ -24,7 +23,7 @@ async function loadCache(accountId) {
async function saveCache(accountId, cache) {
await ensureDir(CACHE_DIR);
const filePath = join(CACHE_DIR, `${accountId}.json`);
- await writeFile(filePath, JSON.stringify(cache, null, 2));
+ await atomicWrite(filePath, cache);
}
async function removeFromCache(accountId, messageId) {
diff --git a/server/services/messageTriageRules.js b/server/services/messageTriageRules.js
index 667488c330..db18b2a484 100644
--- a/server/services/messageTriageRules.js
+++ b/server/services/messageTriageRules.js
@@ -1,6 +1,5 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const RULES_FILE = join(PATHS.messages, 'triage-rules.json');
@@ -13,7 +12,7 @@ async function loadRules() {
async function saveRules(data) {
await ensureDir(PATHS.messages);
- await writeFile(RULES_FILE, JSON.stringify(data, null, 2));
+ await atomicWrite(RULES_FILE, data);
}
/**
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index c3015d0a50..9963b90d02 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -10,11 +10,11 @@
import { homedir } from 'os';
import { join, dirname, basename } from 'path';
-import { readFile, writeFile, stat } from 'fs/promises';
+import { readFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { spawn } from 'child_process';
-import { safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
+import { atomicWrite, safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
import { bufferedSpawn } from '../lib/bufferedSpawn.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, settingsEvents } from './settings.js';
@@ -334,7 +334,7 @@ export async function readStore() {
}
async function writeStoreAtPath(path, data) {
- await withTransientRetry(() => writeFile(path, JSON.stringify(data, null, 2)));
+ await withTransientRetry(() => atomicWrite(path, data));
}
/** Atomic read → mutate → write. Ensures all array keys are initialized. */
@@ -607,7 +607,7 @@ export async function importToPortOS() {
}
if (added > 0) {
await ensureDir(pathDir);
- await writeFile(localPath, JSON.stringify(localArr, null, 2));
+ await atomicWrite(localPath, localArr);
}
return { added, skipped };
};
@@ -624,7 +624,7 @@ export async function importToPortOS() {
if (gAdded > 0) {
await ensureDir(dataPath('digital-twin'));
localGoals.updatedAt = new Date().toISOString();
- await writeFile(goalsPath, JSON.stringify(localGoals, null, 2));
+ await atomicWrite(goalsPath, localGoals);
}
report.added.goals = gAdded; report.skipped.goals = gSkipped;
@@ -649,7 +649,7 @@ export async function importToPortOS() {
const profilePath = dataPath('meatspace', 'profile.json');
if (!existsSync(profilePath)) {
await ensureDir(dataPath('meatspace'));
- await writeFile(profilePath, JSON.stringify(store.profile, null, 2));
+ await atomicWrite(profilePath, store.profile);
report.added.profile = 1; report.skipped.profile = 0;
} else {
report.added.profile = 0; report.skipped.profile = 1;
diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.js
index 0548f58c28..ccc1e9b0bc 100644
--- a/server/services/mortalLoomStore.test.js
+++ b/server/services/mortalLoomStore.test.js
@@ -40,6 +40,14 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn(async () => null),
dataPath: (...segs) => `/mock/data/${segs.join('/')}`,
ensureDir: vi.fn(async () => {}),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) sites (#1837); route
+ // it through the mocked fs/promises.writeFile (writeFileMock) so the existing
+ // writeFileMock.toHaveBeenCalled / JSON.parse(calls[0][1]) asserts keep working.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
}));
vi.mock('../lib/objects.js', () => ({
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index af1bcf0195..ab98d1c101 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -10,7 +10,7 @@ import { readFile, writeFile, readdir, stat, unlink } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { join, relative, resolve, basename, dirname, extname, isAbsolute } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
const VAULTS_FILE = join(PATHS.brain, 'obsidian-vaults.json');
@@ -33,7 +33,7 @@ export async function getVaults() {
async function saveVaults(vaults) {
await ensureDir(PATHS.brain);
- await writeFile(VAULTS_FILE, JSON.stringify({ vaults }, null, 2));
+ await atomicWrite(VAULTS_FILE, { vaults });
}
export async function addVault({ name, path }) {
diff --git a/server/services/runner.js b/server/services/runner.js
index ee4691ee0b..ee59ddf210 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -5,7 +5,7 @@
import { spawn } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildCliArgs } from '../lib/cliProviderArgs.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
@@ -113,7 +113,7 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro
metadata.errorAnalysis = errorAnalysis;
}
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
+ await atomicWrite(metadataPath, metadata).catch(() => {});
if (success) {
runnerConfig.hooks?.onRunCompleted?.(metadata, output);
@@ -154,7 +154,7 @@ export async function patchRunMetadata(runId, patch) {
let metadata;
try { metadata = JSON.parse(metadataStr); } catch { return; }
Object.assign(metadata, patch);
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
+ await atomicWrite(metadataPath, metadata).catch(() => {});
}
/**
@@ -247,7 +247,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
};
await writeFile(outputPath, output).catch(() => {});
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
+ await atomicWrite(metadataPath, metadata).catch(() => {});
// Isolate the hook from onComplete — a throwing onRunFailed must not block
// the caller from settling, and an uncaught throw here would crash the
// process (this runs outside the request lifecycle).
@@ -286,7 +286,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
metadata.errorAnalysis = errorAnalysis;
}
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ await atomicWrite(metadataPath, metadata);
// Isolate the completion hooks + onComplete from the outer catch — a
// throwing onRunCompleted must NOT be reinterpreted as a finalization
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index f694562603..b9c24e429a 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -9,6 +9,13 @@ vi.mock('child_process', async (importOriginal) => {
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) metadata sites (#1837);
+ // route it through the mocked fs/promises.writeFile so it resolves cleanly.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
}));
vi.mock('fs/promises', () => ({
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index bedc3929a3..97a6d99bce 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -19,11 +19,10 @@
* perpetual gate in cosTaskGenerator.generateManagedAppImprovementTaskForType.
*/
-import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
-import { DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
+import { atomicWrite, DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
@@ -552,7 +551,7 @@ export async function loadSchedule() {
async function saveSchedule(schedule) {
await ensureDataDir();
schedule.lastUpdated = new Date().toISOString();
- await writeFile(SCHEDULE_FILE, JSON.stringify(schedule, null, 2));
+ await atomicWrite(SCHEDULE_FILE, schedule);
}
// ============================================================
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 60bd8c8c80..ee9ad99f6c 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -14,7 +14,14 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn(),
loadSlashdoFile: vi.fn().mockResolvedValue(''),
safeJSONParse: (content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } },
- atomicWrite: vi.fn().mockResolvedValue(),
+ // atomicWrite replaced the raw writeFile(JSON.stringify) schedule-save site (#1837);
+ // route it through the mocked fs/promises.writeFile so the tests that read
+ // writeFile.mock.calls.at(-1)[1] still observe the persisted schedule JSON.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
PATHS: { cos: '/mock/data/cos', root: '/mock', reports: '/mock/reports', scripts: '/mock/scripts' },
HOUR: 60 * 60 * 1000,
DAY: 24 * 60 * 60 * 1000,
diff --git a/server/services/taskTemplates.js b/server/services/taskTemplates.js
index dd14d6a527..0bffa2cf7f 100644
--- a/server/services/taskTemplates.js
+++ b/server/services/taskTemplates.js
@@ -5,9 +5,8 @@
* Helps users quickly create tasks for frequently needed operations.
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.cos;
const TEMPLATES_FILE = join(DATA_DIR, 'task-templates.json');
@@ -112,7 +111,7 @@ async function saveState(state) {
state.lastUpdated = new Date().toISOString();
await ensureDir(DATA_DIR);
- await writeFile(TEMPLATES_FILE, JSON.stringify(state, null, 2));
+ await atomicWrite(TEMPLATES_FILE, state);
}
/**
diff --git a/server/services/taskTemplates.test.js b/server/services/taskTemplates.test.js
index fd8daca4e6..ebf402a78d 100644
--- a/server/services/taskTemplates.test.js
+++ b/server/services/taskTemplates.test.js
@@ -5,7 +5,14 @@ vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
readJSONFile: vi.fn(),
- PATHS: { cos: '/tmp/test/cos' }
+ PATHS: { cos: '/tmp/test/cos' },
+ // atomicWrite replaced the raw writeFile(JSON.stringify) site (#1837); route
+ // it through the mocked fs/promises.writeFile so writeFile.toHaveBeenCalled holds.
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ })
}));
vi.mock('fs/promises', () => ({
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index 5ecc207865..c52cf6ee51 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -10,7 +10,7 @@ import { readFile, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { resolveAPIProvider, callProviderAISimple } from '../lib/aiProvider.js';
import { buildPrompt } from './promptService.js';
import { digitalTwinEvents } from './digital-twin.js';
@@ -424,7 +424,7 @@ async function saveTasteProfile(profile) {
await ensureDir(DIGITAL_TWIN_DIR);
}
profile.updatedAt = now();
- await writeFile(TASTE_PROFILE_FILE, JSON.stringify(profile, null, 2));
+ await atomicWrite(TASTE_PROFILE_FILE, profile);
profileCache = profile;
}
diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.js
index e357c1f354..2f737e369c 100644
--- a/server/services/timeCapsule.js
+++ b/server/services/timeCapsule.js
@@ -5,12 +5,12 @@
* Supports creating, listing, viewing, comparing, and deleting snapshots.
*/
-import { readFile, writeFile, unlink, readdir, stat } from 'fs/promises';
+import { readFile, unlink, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { createHash } from 'crypto';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS } from '../lib/fileUtils.js';
const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
const SNAPSHOTS_DIR = join(DIGITAL_TWIN_DIR, 'snapshots');
@@ -31,7 +31,7 @@ async function loadIndex() {
async function saveIndex(index) {
await ensureSnapshotsDir();
- await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));
+ await atomicWrite(INDEX_FILE, index);
}
/**
@@ -122,7 +122,7 @@ export async function createSnapshot(label, description = '') {
// Save snapshot data
const snapshotFile = join(SNAPSHOTS_DIR, `${snapshot.id}.json`);
- await writeFile(snapshotFile, JSON.stringify({ ...snapshot, data }, null, 2));
+ await atomicWrite(snapshotFile, { ...snapshot, data });
// Update index
const index = await loadIndex();
diff --git a/server/services/usage.js b/server/services/usage.js
index a2cf6fbca7..49f0bb1f18 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -1,6 +1,5 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.data;
const USAGE_FILE = join(DATA_DIR, 'usage.json');
@@ -48,7 +47,7 @@ export async function loadUsage() {
*/
async function saveUsage() {
usageData.lastUpdated = new Date().toISOString();
- await writeFile(USAGE_FILE, JSON.stringify(usageData, null, 2));
+ await atomicWrite(USAGE_FILE, usageData);
}
/**
diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.js
index 092332934e..afc01f89c4 100644
--- a/server/services/weeklyDigest.js
+++ b/server/services/weeklyDigest.js
@@ -6,12 +6,12 @@
* error patterns, and accomplishments.
*/
-import { writeFile, readdir } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { getAgents, getAgentDates, getAgentsByDate } from './cosAgents.js';
-import { ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';
const DIGESTS_DIR = PATHS.digests;
@@ -75,7 +75,7 @@ async function loadDigest(weekId) {
async function saveDigest(digest) {
await ensureDigestDir();
const path = getDigestPath(digest.weekId);
- await writeFile(path, JSON.stringify(digest, null, 2));
+ await atomicWrite(path, digest);
return path;
}