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
address review (claude): refuse control-dir reuse while a prior update script is alive + pin the no-unref handle contract
[._.]/ Adam Eivyc58d652db6b3
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.jsindex 5d7a6b26d5..2ba2c74886 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -436,6 +436,25 @@ export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, creturn handle;}+/**+ * Is the control dir's job still running (live PID, no exit sentinel)? Lets a+ * caller that REUSES a fixed control dir (e.g. the update executor) refuse to+ * spawn while a prior detached job is alive — spawnDetached's setup truncates+ * the pid/exit files, so the old supervisor's late `exit` write would satisfy+ * the NEW tailer's sentinel check and prematurely close the new handle with+ * the old job's status (the stale-late-write race reapDetached guards against).+ *+ * @param {string} controlDir - the job's spawnDetached control dir+ * @returns {Promise<boolean>}+ */+export async function isDetachedRunning(controlDir) {+ const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');+ const pid = Number.parseInt(pidRaw, 10);+ if (!Number.isFinite(pid) || pid <= 0) return false;+ const exitWritten = (await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '')).length > 0;+ return !exitWritten && isAlive(pid);+}+/*** Reap a detached job that outlived the server (boot recovery). Because* spawnDetached children reparent to init, a `pm2 restart` leaves them runningdiff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex 5a114b97e8..6ce156fa6b 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { execFile } from 'child_process';import { promisify } from 'util';-import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable } from './detachedSpawn.js';+import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable, isDetachedRunning } from './detachedSpawn.js';const execFileAsync = promisify(execFile);const dirs = [];@@ -268,6 +268,34 @@ describe('isReattachable', () => {});});+describe('isDetachedRunning', () => {+ it('is true while the recorded child is still alive with no exit sentinel', async () => {+ const controlDir = await tmpControlDir();+ const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });+ expect(await isDetachedRunning(controlDir)).toBe(true);+ handle.kill('SIGKILL');+ await onClose(handle);+ });++ it('is false once the job recorded its exit', async () => {+ const controlDir = await tmpControlDir();+ const handle = await spawnDetached('sh', ['-c', 'exit 0'], { controlDir, pollMs: 25 });+ await onClose(handle);+ expect(await isDetachedRunning(controlDir)).toBe(false);+ });++ it('is false when no pid was ever recorded', async () => {+ const controlDir = await tmpControlDir();+ expect(await isDetachedRunning(controlDir)).toBe(false);+ });++ it('is false for a dead pid with no exit sentinel', async () => {+ const controlDir = await tmpControlDir();+ await writeFile(join(controlDir, 'pid'), '2147483647');+ expect(await isDetachedRunning(controlDir)).toBe(false);+ });+});+describe('reattachDetached', () => {it('replays a still-running survivor from the start and closes with its exit code', async () => {const controlDir = await tmpControlDir();diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex 50cec25cc0..ea2dae7135 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -2,7 +2,7 @@ import { spawn } from 'child_process';import { readFile, unlink } from 'fs/promises';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';-import { spawnDetached } from '../lib/detachedSpawn.js';+import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';import { recordUpdateResult } from './updateChecker.js';const UPDATE_SH = join(PATHS.root, 'update.sh');@@ -66,6 +66,25 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {// progress parsing below works unchanged. The control dir is reused across// updates (spawnDetached truncates stale files) and kept afterward as the// post-mortem record of the launch.+ const controlDir = join(PATHS.data, 'update-detached');++ // Refuse to reuse the control dir while a prior update script is still+ // running (survival path: the old script outlives the server restart it+ // triggers, and its supervisor's late `exit` write into a truncated control+ // dir would prematurely close the new handle with the OLD script's status).+ // A still-running script also means a second update is wrong regardless.+ if (!isWindows && await isDetachedRunning(controlDir)) {+ const errorMessage = 'A previous update script is still running — wait for it to finish before starting another update';+ await recordUpdateResult({+ version: tag.replace(/^v/, ''),+ success: false,+ completedAt: new Date().toISOString(),+ log: errorMessage+ }).catch(e => console.error(`❌ Failed to record update result: ${e.message}`));+ emit('starting', 'error', errorMessage);+ return { success: false, failedStep: 'starting', errorMessage };+ }+const child = isWindows? spawn(cmd, args, {detached: true,@@ -76,7 +95,7 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {: await spawnDetached(cmd, args, {cwd: PATHS.root,env: childEnv,- controlDir: join(PATHS.data, 'update-detached')+ controlDir});return new Promise((resolve) => {diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.jsindex 5e9176ee6e..4d260c2b4e 100644--- a/server/services/updateExecutor.test.js+++ b/server/services/updateExecutor.test.js@@ -11,7 +11,8 @@ tryReadFile: vi.fn().mockResolvedValue(null),}));vi.mock('../lib/detachedSpawn.js', () => ({- spawnDetached: vi.fn()+ spawnDetached: vi.fn(),+ isDetachedRunning: vi.fn().mockResolvedValue(false)}));vi.mock('fs/promises', () => ({@@ -24,16 +25,18 @@ vi.mock('./updateChecker.js', () => ({}));import { spawn } from 'child_process';-import { spawnDetached } from '../lib/detachedSpawn.js';+import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';import { readFile } from 'fs/promises';import { recordUpdateResult } from './updateChecker.js';import { executeUpdate } from './updateExecutor.js';+// The spawnDetached handle deliberately has NO unref (its launcher already+// unref'd) — executeUpdate must use `child.unref?.()`. Only the win32+// plain-spawn test adds a real ChildProcess-style unref to its mock.function createMockChild() {const child = new EventEmitter();child.stdout = new EventEmitter();child.stderr = new EventEmitter();- child.unref = vi.fn();child.pid = 12345;return child;}@@ -55,6 +58,8 @@ beforeEach(() => {vi.clearAllMocks();// Default: marker file not found (tests that need it override this)readFile.mockRejectedValue(new Error('ENOENT'));+ // Default: no prior update script still running+ isDetachedRunning.mockResolvedValue(false);});describe('executeUpdate', () => {@@ -63,6 +68,7 @@ describe('executeUpdate', () => {try {Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });const child = createMockChild();+ child.unref = vi.fn();spawn.mockReturnValue(child);const { promise } = await startUpdate('v1.0.0', () => {});@@ -106,6 +112,27 @@ describe('executeUpdate', () => {);});+ // Reusing the fixed control dir while the prior update script is still+ // alive would let the old supervisor's late `exit` write prematurely close+ // the new handle with the old script's status — so a still-running script+ // must refuse the new update instead of spawning over it.+ it('refuses to spawn while a prior update script is still running', async () => {+ isDetachedRunning.mockResolvedValue(true);++ const emits = [];+ const { promise } = await startUpdate('v1.0.0', (...args) => emits.push(args));+ const result = await promise;++ expect(result.success).toBe(false);+ expect(result.failedStep).toBe('starting');+ expect(spawnDetached).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(recordUpdateResult).toHaveBeenCalledWith(+ expect.objectContaining({ success: false, log: expect.stringContaining('still running') })+ );+ expect(emits.some(e => e[0] === 'starting' && e[1] === 'error')).toBe(true);+ });+it('parses STEP markers from stdout', async () => {const child = createMockChild();spawnDetached.mockResolvedValue(child);