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
fix: verify process recovery before recording a successful auto-restart (#9744)
[._.]/ Adam Eivyfaa3afa9fd80
diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex e8d7572961..1c6b2e32a6 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -6,12 +6,79 @@* snapshot to CoS state, and emits health events for downstream consumers.*/-import { execPm2, listProcessesStrict } from './pm2.js';+import { execPm2, listProcessesStrict, clearJlistCache } from './pm2.js';import { getMemoryStats } from '../lib/memoryStats.js';import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';import { annotateExpectedExit } from './appProcessStatus.js';+// A restart that PM2 accepted proves the command ran, not that the process+// stayed up. Verification is bounded: a few fresh reads, waiting only while PM2+// still reports a transitional state. Exported for tests to shrink the wait.+export const RESTART_VERIFY = { attempts: 3, delayMs: 2000 };+const TRANSITIONAL = new Set(['launching', 'waiting restart', 'stopping']);+const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));++// Stable identity: pm_id distinguishes cluster instances sharing a name.+const processKey = (p) => (p.pm_id ?? null) !== null ? `id:${p.pm_id}` : `name:${p.name}`;++async function summarizePm2(processes) {+ const annotated = await annotateExpectedExit(processes);+ const supervised = annotated.filter(p => !p.expectedExit);+ const erroredProcesses = supervised.filter(p => p.status === 'errored');+ // Reported on its own rather than folded into `errored` (which would+ // degrade health for a normal user action) or dropped from the totals.+ // Counted from the expected-exit processes only, so it never overlaps+ // `errored`/`stopped` — those count supervised processes exclusively.+ const desktopExited = annotated.filter(+ p => p.expectedExit && ['errored', 'stopped'].includes(p.status)+ ).length;+ // `online` counts EVERY process, exempt or not: the exemption is about+ // exit semantics, not liveness, so a running desktop app must still report+ // as online.+ return {+ erroredProcesses,+ pm2: {+ total: processes.length,+ online: annotated.filter(p => p.status === 'online').length,+ errored: erroredProcesses.length,+ stopped: supervised.filter(p => p.status === 'stopped').length,+ desktopExited+ }+ };+}++/**+ * Observe whether restarted processes came back. Returns+ * { processes: fresh list | null, unconfirmed: [{ name, reason }] }.+ */+async function verifyRecovery(restarted) {+ const wanted = new Map(restarted.map(p => [processKey(p), p]));+ let fresh = null;+ for (let attempt = 0; attempt < RESTART_VERIFY.attempts; attempt++) {+ if (attempt > 0) await sleep(RESTART_VERIFY.delayMs);+ clearJlistCache();+ fresh = await listProcessesStrict();+ if (fresh === null) continue;+ // Wait only while a restarted process is still in a transitional state;+ // online, errored, stopped or missing are all settled answers.+ const byKey = new Map(fresh.map(p => [processKey(p), p]));+ if (![...wanted.keys()].some(key => TRANSITIONAL.has(byKey.get(key)?.status))) break;+ }+ if (fresh === null) {+ return { processes: null, unconfirmed: [...wanted.values()].map(p => ({ name: p.name, reason: 'verification read failed' })) };+ }+ const byKey = new Map(fresh.map(p => [processKey(p), p]));+ const unconfirmed = [...wanted.entries()]+ .filter(([key]) => byKey.get(key)?.status !== 'online')+ .map(([key, p]) => {+ const status = byKey.get(key)?.status;+ if (!status) return { name: p.name, reason: 'missing after restart' };+ return { name: p.name, reason: TRANSITIONAL.has(status) ? `still ${status}` : status };+ });+ return { processes: fresh, unconfirmed };+}+/*** Run a daemon health check: inspect PM2 processes and memory, auto-restart* errored processes, store the result, and emit health events.@@ -48,29 +115,9 @@ export async function runHealthCheck() {// closed) must not be auto-restarted — that would reopen the window they// just closed, the same relaunch loop `autorestart: false` prevents,// arriving by another path. See issue #2991.- const annotated = await annotateExpectedExit(pm2Processes);- const supervised = annotated.filter(p => !p.expectedExit);-- const erroredProcesses = supervised.filter(p => p.status === 'errored');- // Reported on its own rather than folded into `errored` (which would- // degrade health for a normal user action) or dropped from the totals.- // Counted from the expected-exit processes only, so it never overlaps- // `errored`/`stopped` below — those now count supervised processes- // exclusively.- const desktopExited = annotated.filter(- p => p.expectedExit && ['errored', 'stopped'].includes(p.status)- ).length;- // `online` counts EVERY process, exempt or not: the exemption is about- // exit semantics, not liveness, so a running desktop app must still report- // as online (otherwise it lands in `total` and in no bucket, and the- // metric reads the same whether the game is running or quit).- metrics.pm2 = {- total: pm2Processes.length,- online: annotated.filter(p => p.status === 'online').length,- errored: erroredProcesses.length,- stopped: supervised.filter(p => p.status === 'stopped').length,- desktopExited- };+ const summary = await summarizePm2(pm2Processes);+ const erroredProcesses = summary.erroredProcesses;+ metrics.pm2 = summary.pm2;// Check for runaway processes (too many)if (pm2Processes.length > state.config.maxTotalProcesses) {@@ -86,18 +133,15 @@ export async function runHealthCheck() {const names = erroredProcesses.map(p => p.name);emitLog('warn', `🔄 ${names.length} errored PM2 process(es) detected: ${names.join(', ')} — attempting restart`);- const restartResults = await Promise.all(names.map(async (name) => {+ const restartResults = await Promise.all(erroredProcesses.map(async (proc) => {+ const name = proc.name;// execPm2, not execFileAsync('pm2', …, { shell: true }) — `shell: true`// resolves `pm2` to pm2.cmd and rebuilds the cmd.exe → pm2.cmd → node// chain that v1.6.7 removed, flashing a console window on every restart.const result = await execPm2(['restart', name]).catch(e => ({ stdout: '', stderr: e.message }));const failed = result.stderr && !result.stdout;- if (failed) {- emitLog('error', `❌ Failed to restart ${name}: ${result.stderr}`);- } else {- emitLog('success', `✅ Auto-restarted errored process: ${name}`);- }- return { name, success: !failed };+ if (failed) emitLog('error', `❌ Failed to restart ${name}: ${result.stderr}`);+ return { proc, success: !failed };}));const failedRestarts = restartResults.filter(r => !r.success);@@ -105,9 +149,30 @@ export async function runHealthCheck() {issues.push({type: 'error',category: 'processes',- message: `${failedRestarts.length} errored PM2 process(es) failed to auto-restart: ${failedRestarts.map(r => r.name).join(', ')}`+ message: `${failedRestarts.length} errored PM2 process(es) failed to auto-restart: ${failedRestarts.map(r => r.proc.name).join(', ')}`});}++ // Command acceptance is not recovery: observe process state afresh.+ const accepted = restartResults.filter(r => r.success).map(r => r.proc);+ if (accepted.length > 0) {+ const { processes: fresh, unconfirmed } = await verifyRecovery(accepted);+ const unconfirmedKeys = new Set(unconfirmed.map(u => u.name));+ for (const proc of accepted) {+ if (!unconfirmedKeys.has(proc.name)) emitLog('success', `✅ Auto-restarted errored process (observed online): ${proc.name}`);+ }+ if (unconfirmed.length > 0) {+ const detail = unconfirmed.map(u => `${u.name} (${u.reason})`).join(', ');+ emitLog('error', `❌ Restart accepted but recovery not confirmed: ${detail}`);+ issues.push({+ type: 'error',+ category: 'processes',+ message: `${unconfirmed.length} PM2 process(es) restarted but recovery is unconfirmed: ${detail}`+ });+ }+ // Report fresh post-restart metrics when the observation succeeded.+ if (fresh !== null) metrics.pm2 = (await summarizePm2(fresh)).pm2;+ }}}diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex 6c1057b234..d5677551d7 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -8,6 +8,13 @@ const mock = vi.hoisted(() => ({// (incl. []) = a successful read.pm2Processes: [],restartImpl: null,+ // What a fresh PM2 read returns once a restart has been issued (null = read+ // failed). Default models a healthy recovery; tests override to model a+ // process that falls straight back to errored, vanishes, or is unreadable.+ postRestart: null,+ restartIssued: false,+ readsAfterRestart: 0,+ cacheClears: 0,events: [],// PM2 process names belonging to desktop (GUI) apps — exempt from auto-restart.desktopProcessNames: new Set(),@@ -38,8 +45,13 @@ vi.mock('./cosState.js', () => ({// resolves to pm2.cmd on Windows and flashes a console window// (docs/WINDOWS_CONSOLE.md).vi.mock('./pm2.js', () => ({- execPm2: vi.fn(async (args) => mock.restartImpl(args)),- listProcessesStrict: vi.fn(async () => mock.pm2Processes)+ execPm2: vi.fn(async (args) => { mock.restartIssued = true; return mock.restartImpl(args); }),+ clearJlistCache: vi.fn(() => { mock.cacheClears += 1; }),+ listProcessesStrict: vi.fn(async () => {+ if (!mock.restartIssued) return mock.pm2Processes;+ mock.readsAfterRestart += 1;+ return mock.postRestart(mock.pm2Processes);+ })}));vi.mock('../lib/memoryStats.js', () => ({@@ -51,7 +63,10 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn()}));-import { runHealthCheck, getHealthStatus } from './cosHealthMonitor.js';+import { emitLog } from './cosEvents.js';+import { runHealthCheck, getHealthStatus, RESTART_VERIFY } from './cosHealthMonitor.js';++const recoverAll = (procs) => procs.map(p => (p.status === 'errored' ? { ...p, status: 'online' } : p));// The restart assertions differ only in what they record off the pm2 argv —// the whole argv, or just the process name.@@ -71,6 +86,12 @@ describe('cosHealthMonitor.runHealthCheck', () => {mock.state = baseState();mock.savedState = null;mock.pm2Processes = [];+ mock.postRestart = recoverAll;+ mock.restartIssued = false;+ mock.readsAfterRestart = 0;+ mock.cacheClears = 0;+ emitLog.mockClear();+ RESTART_VERIFY.delayMs = 0;mock.events = [];mock.desktopProcessNames = new Set();mock.desktopLookupError = null;@@ -123,6 +144,83 @@ describe('cosHealthMonitor.runHealthCheck', () => {expect(issues.some(i => i.type === 'error')).toBe(false);});+ describe('post-restart verification', () => {+ const errored = () => [{ name: 'boom', pm_id: 3, status: 'errored' }];+ const critical = () => mock.events.some(e => e.name === 'health:critical');++ it('observed online recovery clears the issue, logs success and reports fresh metrics', async () => {+ mock.pm2Processes = errored();+ const { issues, metrics } = await runHealthCheck();+ expect(issues).toEqual([]);+ expect(critical()).toBe(false);+ expect(mock.cacheClears).toBeGreaterThan(0);+ expect(metrics.pm2).toMatchObject({ errored: 0, online: 1 });+ expect(emitLog).toHaveBeenCalledWith('success', expect.stringContaining('boom'));+ expect(mock.savedState.stats.healthIssues).toEqual([]);+ });++ it('keeps a persisted issue and logs no success when the restarted process is errored again', async () => {+ mock.pm2Processes = errored();+ mock.postRestart = (p) => p;+ const { issues } = await runHealthCheck();+ expect(issues).toHaveLength(1);+ expect(issues[0]).toMatchObject({ type: 'error', category: 'processes' });+ expect(issues[0].message).toMatch(/unconfirmed.*boom \(errored\)/);+ expect(critical()).toBe(true);+ expect(emitLog).not.toHaveBeenCalledWith('success', expect.anything());+ expect((await getHealthStatus()).issues).toHaveLength(1);+ });++ it('keeps an issue when the process is missing after the restart', async () => {+ mock.pm2Processes = errored();+ mock.postRestart = () => [];+ const { issues } = await runHealthCheck();+ expect(issues[0].message).toMatch(/boom \(missing after restart\)/);+ });++ it('never reports healthy when the verification read fails', async () => {+ mock.pm2Processes = errored();+ mock.postRestart = () => null;+ const { issues } = await runHealthCheck();+ expect(issues).toHaveLength(1);+ expect(issues[0].message).toMatch(/boom \(verification read failed\)/);+ expect(mock.savedState.stats.healthIssues).toHaveLength(1);+ expect(emitLog).not.toHaveBeenCalledWith('success', expect.anything());+ });++ it('waits a bounded number of reads on a transitional state, then reports unconfirmed', async () => {+ mock.pm2Processes = errored();+ mock.postRestart = (p) => p.map(x => ({ ...x, status: 'launching' }));+ const { issues } = await runHealthCheck();+ expect(mock.readsAfterRestart).toBe(RESTART_VERIFY.attempts);+ expect(issues[0].message).toMatch(/boom \(still launching\)/);+ });++ it('confirms recovery once a launching process comes online within the bound', async () => {+ mock.pm2Processes = errored();+ let reads = 0;+ mock.postRestart = (p) => p.map(x => ({ ...x, status: ++reads < 2 ? 'launching' : 'online' }));+ const { issues } = await runHealthCheck();+ expect(issues).toEqual([]);+ expect(mock.readsAfterRestart).toBe(2);+ });++ it('identifies cluster instances by pm_id, not name alone', async () => {+ mock.pm2Processes = [{ name: 'web', pm_id: 1, status: 'errored' }, { name: 'web', pm_id: 2, status: 'online' }];+ mock.postRestart = (p) => p; // pm_id 1 stays errored; pm_id 2 online must not mask it+ const { issues } = await runHealthCheck();+ expect(issues[0].message).toMatch(/web \(errored\)/);+ });++ it('still reports a rejected restart command as actionable and does not verify it', async () => {+ mock.pm2Processes = errored();+ mock.restartImpl = async () => { throw new Error('nope'); };+ const { issues } = await runHealthCheck();+ expect(issues.map(i => i.message).join('|')).toMatch(/failed to auto-restart: boom/);+ expect(mock.readsAfterRestart).toBe(0);+ });+ });+it('records an error issue and emits health:critical when a restart fails', async () => {mock.pm2Processes = [{ name: 'boom', status: 'errored' }];mock.restartImpl = async () => { throw new Error('restart failed'); };@@ -196,13 +294,15 @@ describe('cosHealthMonitor.runHealthCheck', () => {const { metrics, issues } = await runHealthCheck();expect(restarted).toEqual(['web']);- expect(metrics.pm2.errored).toBe(1);+ // Fresh post-restart metrics: web recovered, the exempt game stays exited.+ expect(metrics.pm2).toMatchObject({ errored: 0, desktopExited: 1 });expect(issues).toEqual([]);});it('exempts nothing when the registry read fails (pre-existing behavior stands)', async () => {mock.desktopLookupError = new Error('registry unreadable');mock.pm2Processes = [{ name: 'web', status: 'errored' }];+ mock.postRestart = (p) => p; // keep the pre-restart counts under testconst restarted = [];mock.restartImpl = recordRestarts(restarted, (args) => args[1]);