Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-749]): reuse shared fileUtils.atomicWrite in runner state layer
[._.]/ Adam Eivy72032289c788
diff --git a/server/cos-runner/runnerState.js b/server/cos-runner/runnerState.jsindex 3f9f5846f4..5ecc74b0f4 100644--- a/server/cos-runner/runnerState.js+++ b/server/cos-runner/runnerState.js@@ -2,14 +2,14 @@* CoS Runner — State persistence layer** Owns the on-disk runner-state.json: atomic writes, serialized saves, and- * loads. Kept self-contained (only fs + the shared fileUtils helper) so the+ * loads. Kept self-contained (only fs + the shared fileUtils helpers) so the* isolated `portos-cos` PM2 process stays standalone.*/-import { join, dirname } from 'path';-import { writeFile, readFile, rename } from 'fs/promises';+import { join } from 'path';+import { readFile } from 'fs/promises';import { existsSync } from 'fs';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { atomicWrite, PATHS } from '../lib/fileUtils.js';export const STATE_FILE = join(PATHS.cos, 'runner-state.json');@@ -20,15 +20,6 @@ const freshState = () => ({ ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_ST// Serializes saves so concurrent writes can't interleave and corrupt the file.let stateLock = Promise.resolve();-/**- * Write state atomically using temp file + rename to prevent partial-write corruption- */-export async function atomicWrite(filePath, data) {- const tmpPath = `${filePath}.tmp.${process.pid}`;- await writeFile(tmpPath, data);- await rename(tmpPath, filePath);-}-/*** Load runner state from disk*/@@ -42,13 +33,11 @@ export async function loadState() {}/**- * Save runner state to disk (serialized with atomic writes to prevent corruption)+ * Save runner state to disk (serialized with atomic writes to prevent corruption).+ * Delegates the temp-file-and-rename dance to the shared fileUtils.atomicWrite,+ * which also handles ensureDir, JSON stringification, and the Windows rename fallback.*/export function saveState(state) {- stateLock = stateLock.then(async () => {- const dir = dirname(STATE_FILE);- if (!existsSync(dir)) await ensureDir(dir);- await atomicWrite(STATE_FILE, JSON.stringify(state, null, 2));- });+ stateLock = stateLock.then(() => atomicWrite(STATE_FILE, state));return stateLock;}diff --git a/server/cos-runner/runnerState.test.js b/server/cos-runner/runnerState.test.jsnew file mode 100644index 0000000000..712200ce6d--- /dev/null+++ b/server/cos-runner/runnerState.test.js@@ -0,0 +1,56 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++describe('cos-runner runnerState', () => {+ let tmpDir;++ // STATE_FILE is computed from PATHS.cos at module-load time, so each test+ // points PATHS.cos at a fresh temp dir and re-imports the module.+ const loadModule = async () => {+ const fileUtils = await import('../lib/fileUtils.js');+ fileUtils.PATHS.cos = tmpDir;+ vi.resetModules();+ return import('./runnerState.js');+ };++ beforeEach(async () => {+ tmpDir = await mkdtemp(join(tmpdir(), 'cos-runner-state-'));+ });+ afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true });+ vi.resetModules();+ });++ it('returns a fresh default state (a copy, not the shared constant) when no file exists', async () => {+ const { loadState, DEFAULT_STATE } = await loadModule();+ const state = await loadState();+ expect(state).toEqual(DEFAULT_STATE);+ state.stats.spawned = 99;+ expect(DEFAULT_STATE.stats.spawned).toBe(0);+ });++ it('returns fresh default for an empty / whitespace-only file', async () => {+ const { loadState, STATE_FILE } = await loadModule();+ await writeFile(STATE_FILE, ' ');+ expect((await loadState()).stats.spawned).toBe(0);+ });++ it('round-trips state through save and load', async () => {+ const { saveState, loadState } = await loadModule();+ await saveState({ agents: { a1: { pid: 5 } }, stats: { spawned: 3, completed: 1, failed: 0 } });+ const state = await loadState();+ expect(state.agents.a1.pid).toBe(5);+ expect(state.stats).toEqual({ spawned: 3, completed: 1, failed: 0 });+ });++ it('serializes concurrent saves so the file is never a torn write', async () => {+ const { saveState, loadState } = await loadModule();+ await Promise.all([+ saveState({ agents: {}, stats: { spawned: 1, completed: 0, failed: 0 } }),+ saveState({ agents: {}, stats: { spawned: 2, completed: 0, failed: 0 } }),+ ]);+ expect([1, 2]).toContain((await loadState()).stats.spawned);+ });+});