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

fix update/reconcile stranding PortOS stopped: launch update.sh via double-fork so it survives pm2's tree-kill

[._.]/ Adam Eivy19081da9a7eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 86ab142439..83dc7ad549 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,7 @@
+## Self-Update
+
+- **The in-app update/reconcile no longer strands PortOS stopped.** `updateExecutor` launched `update.sh` with a plain `spawn(..., { detached: true })`, assuming it would survive the restart phase — but PM2's TreeKill walks PPID, not the process group, so the moment the script's own `pm2-stop` step ran `pm2 delete ecosystem.config.cjs`, the script (still a PPID-child of portos-server) was killed along with the server. Every app was stopped and the only process that would have run the final `pm2 start` was dead — the "update/reconcile shuts everything down but never comes back" failure. On POSIX the script now launches through `spawnDetached()`'s double-fork (the same reparent-to-init machinery LoRA training uses to survive PM2 restarts, #1332), with `STEP:` progress streamed via the control-dir log tailer, so the update runs to completion and restarts PortOS even after the server dies mid-script. Windows keeps its prior plain-spawn behavior (PM2 there is taskkill-based; detached survival is a POSIX-only guarantee). (`server/services/updateExecutor.js`)
+
## CI
- **CI and release workflows now run Node 24.x** (matching `.nvmrc`, which has pinned 24 while the workflows still ran 20.x). Also removed the stale v1.14-era GSD planning workspace (`.planning/`, `.plan-questions.md`) from the repo root — the milestone it tracked shipped in February and GSD is no longer in use for PortOS itself (the GSD feature for managed apps is unaffected; it simply no longer lists PortOS).
diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.js
index fc1ae1b854..50cec25cc0 100644
--- a/server/services/updateExecutor.js
+++ b/server/services/updateExecutor.js
@@ -2,6 +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 { recordUpdateResult } from './updateChecker.js';
const UPDATE_SH = join(PATHS.root, 'update.sh');
@@ -9,8 +10,20 @@ const UPDATE_PS1 = join(PATHS.root, 'update.ps1');
/**
* Execute the PortOS update script (git pull to latest).
- * Spawns update.sh (or update.ps1 on Windows) detached so it survives
- * the Node process dying during the PM2 restart phase.
+ *
+ * On POSIX the script is launched via spawnDetached's double-fork so it
+ * reparents to init and SURVIVES pm2's TreeKill. A plain
+ * `spawn(..., { detached: true })` does NOT survive: pm2 walks PPID
+ * (`ps -e -o pid=,ppid=`), not the process group, so when update.sh reaches
+ * its `pm2-stop` step (`pm2 delete ecosystem.config.cjs`) the script itself —
+ * still a PPID-child of portos-server — was tree-killed with the server,
+ * leaving every app stopped with nothing alive to run the final `pm2 start`
+ * (the reconcile/update "shuts down but never comes back" failure). See the
+ * rationale in `server/lib/detachedSpawn.js`.
+ *
+ * Windows keeps the prior plain-spawn behavior (pm2 there is taskkill-based;
+ * detached survival is a POSIX-only guarantee — same trade-off as
+ * spawnDetached's own win32 fallback).
*
* The scripts pull the latest code via `git pull --rebase --autostash` and
* write the actual resulting version to `data/update-complete.json`.
@@ -46,14 +59,27 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {
? { ...process.env, PORTOS_FORCE_CLEAN_WORKSPACES: cleanList.join(',') }
: process.env;
- return new Promise((resolve) => {
- const child = spawn(cmd, args, {
- detached: true,
- stdio: ['ignore', 'pipe', 'pipe'],
- cwd: PATHS.root,
- env: childEnv
- });
+ // POSIX: double-fork via spawnDetached so the script reparents to init and
+ // survives the pm2 TreeKill its own `pm2 delete`/`pm2 start` steps trigger.
+ // The returned handle is ChildProcess-like (stdout/stderr 'data', 'close',
+ // 'error'), streamed by tailing the control dir's log files — so the STEP:
+ // 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 child = isWindows
+ ? spawn(cmd, args, {
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ cwd: PATHS.root,
+ env: childEnv
+ })
+ : await spawnDetached(cmd, args, {
+ cwd: PATHS.root,
+ env: childEnv,
+ controlDir: join(PATHS.data, 'update-detached')
+ });
+ return new Promise((resolve) => {
let lastStep = 'starting';
// Parse STEP:name:status:message lines from stdout/stderr streams
@@ -149,7 +175,9 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {
resolve({ success: false, failedStep: 'starting', errorMessage });
});
- // Unref so the parent process doesn't wait for the detached child
- child.unref();
+ // Unref so the parent process doesn't wait for the detached child.
+ // The spawnDetached handle has no unref (its launcher already unref'd);
+ // only the Windows plain-spawn child needs it.
+ child.unref?.();
});
}
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index c195319956..5e9176ee6e 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -10,6 +10,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { root: '/mock', data: '/mock/data' }
}));
+vi.mock('../lib/detachedSpawn.js', () => ({
+ spawnDetached: vi.fn()
+}));
+
vi.mock('fs/promises', () => ({
readFile: vi.fn(),
unlink: vi.fn().mockResolvedValue(undefined)
@@ -20,6 +24,7 @@ vi.mock('./updateChecker.js', () => ({
}));
import { spawn } from 'child_process';
+import { spawnDetached } from '../lib/detachedSpawn.js';
import { readFile } from 'fs/promises';
import { recordUpdateResult } from './updateChecker.js';
import { executeUpdate } from './updateExecutor.js';
@@ -33,6 +38,19 @@ function createMockChild() {
return child;
}
+// executeUpdate awaits spawnDetached before wiring its event listeners, so
+// tests must flush the microtask/immediate queue after calling it and before
+// emitting child events, or the emission fires into the void.
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+async function startUpdate(...args) {
+ const promise = executeUpdate(...args);
+ await flush();
+ // Wrapped in an object so `await startUpdate(...)` does not flatten the
+ // still-pending executeUpdate promise (which only settles after 'close').
+ return { promise };
+}
+
beforeEach(() => {
vi.clearAllMocks();
// Default: marker file not found (tests that need it override this)
@@ -40,14 +58,14 @@ beforeEach(() => {
});
describe('executeUpdate', () => {
- it('spawns powershell on Windows', async () => {
+ it('spawns powershell on Windows (plain spawn, not spawnDetached)', async () => {
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
try {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
const child = createMockChild();
spawn.mockReturnValue(child);
- const promise = executeUpdate('v1.0.0', () => {});
+ const { promise } = await startUpdate('v1.0.0', () => {});
child.emit('close', 0);
await promise;
@@ -56,6 +74,7 @@ describe('executeUpdate', () => {
expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),
expect.any(Object)
);
+ expect(spawnDetached).not.toHaveBeenCalled();
} finally {
if (originalPlatformDescriptor) {
Object.defineProperty(process, 'platform', originalPlatformDescriptor);
@@ -63,12 +82,36 @@ describe('executeUpdate', () => {
}
});
+ // Regression for the reconcile "shuts down but never restarts" failure: a
+ // plain spawn(detached:true) child is still a PPID-descendant of
+ // portos-server, so update.sh's own `pm2 delete` tree-killed the script
+ // before it could run the final `pm2 start`. POSIX must launch through
+ // spawnDetached's double-fork (reparent to init) instead.
+ it('launches via spawnDetached with a control dir on POSIX', async () => {
+ const child = createMockChild();
+ spawnDetached.mockResolvedValue(child);
+
+ const { promise } = await startUpdate('v1.0.0', () => {});
+ child.emit('close', 0);
+ await promise;
+
+ expect(spawn).not.toHaveBeenCalled();
+ expect(spawnDetached).toHaveBeenCalledWith(
+ 'bash',
+ [expect.stringContaining('update.sh')],
+ expect.objectContaining({
+ cwd: '/mock',
+ controlDir: expect.stringContaining('update-detached')
+ })
+ );
+ });
+
it('parses STEP markers from stdout', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
const emits = [];
- const promise = executeUpdate('v1.0.0', (...args) => emits.push(args));
+ const { promise } = await startUpdate('v1.0.0', (...args) => emits.push(args));
// Simulate STEP output
child.stdout.emit('data', Buffer.from('STEP:git-pull:running:Pulling latest changes\n'));
@@ -84,9 +127,9 @@ describe('executeUpdate', () => {
it('records update result on success with tag fallback when marker missing', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
- const promise = executeUpdate('v1.0.0', () => {});
+ const { promise } = await startUpdate('v1.0.0', () => {});
child.emit('close', 0);
const result = await promise;
@@ -99,9 +142,9 @@ describe('executeUpdate', () => {
it('records failure on non-zero exit code', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
- const promise = executeUpdate('v1.0.0', () => {});
+ const { promise } = await startUpdate('v1.0.0', () => {});
child.emit('close', 1);
const result = await promise;
@@ -113,10 +156,10 @@ describe('executeUpdate', () => {
it('handles CRLF line endings from Windows PowerShell', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
const emits = [];
- const promise = executeUpdate('v1.0.0', (...args) => emits.push(args));
+ const { promise } = await startUpdate('v1.0.0', (...args) => emits.push(args));
// Simulate CRLF output (Windows PowerShell)
child.stdout.emit('data', Buffer.from('STEP:git-pull:running:Pulling latest changes\r\n'));
@@ -133,10 +176,10 @@ describe('executeUpdate', () => {
it('returns actual version from completion marker and records result on success', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
readFile.mockResolvedValue(JSON.stringify({ version: '2.0.0', completedAt: '2026-01-01T00:00:00Z' }));
- const promise = executeUpdate('v1.0.0', () => {});
+ const { promise } = await startUpdate('v1.0.0', () => {});
child.emit('close', 0);
const result = await promise;
@@ -149,10 +192,10 @@ describe('executeUpdate', () => {
it('handles spawn error', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
const emits = [];
- const promise = executeUpdate('v1.0.0', (...args) => emits.push(args));
+ const { promise } = await startUpdate('v1.0.0', (...args) => emits.push(args));
child.emit('error', new Error('spawn failed'));
const result = await promise;
@@ -167,41 +210,41 @@ describe('executeUpdate', () => {
// reinstalls exactly those, regardless of the commit diff.
it('passes allowlisted forceCleanWorkspaces as PORTOS_FORCE_CLEAN_WORKSPACES', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
- const promise = executeUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['.', 'client'] });
+ spawnDetached.mockResolvedValue(child);
+ const { promise } = await startUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['.', 'client'] });
child.emit('close', 0);
await promise;
- const env = spawn.mock.calls[0][2].env;
+ const env = spawnDetached.mock.calls[0][2].env;
expect(env.PORTOS_FORCE_CLEAN_WORKSPACES).toBe('.,client');
});
it('does NOT set PORTOS_FORCE_CLEAN_WORKSPACES when none are given', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
- const promise = executeUpdate('v1.0.0', () => {});
+ spawnDetached.mockResolvedValue(child);
+ const { promise } = await startUpdate('v1.0.0', () => {});
child.emit('close', 0);
await promise;
- const env = spawn.mock.calls[0][2].env;
+ const env = spawnDetached.mock.calls[0][2].env;
expect(env.PORTOS_FORCE_CLEAN_WORKSPACES).toBeUndefined();
});
it('filters out non-allowlisted workspace names (no injection)', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
- const promise = executeUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['client', '../../etc', 'rm -rf /'] });
+ spawnDetached.mockResolvedValue(child);
+ const { promise } = await startUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['client', '../../etc', 'rm -rf /'] });
child.emit('close', 0);
await promise;
- const env = spawn.mock.calls[0][2].env;
+ const env = spawnDetached.mock.calls[0][2].env;
expect(env.PORTOS_FORCE_CLEAN_WORKSPACES).toBe('client');
});
it('does NOT set the env when every workspace name is rejected', async () => {
const child = createMockChild();
- spawn.mockReturnValue(child);
- const promise = executeUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['bogus'] });
+ spawnDetached.mockResolvedValue(child);
+ const { promise } = await startUpdate('v1.0.0', () => {}, { forceCleanWorkspaces: ['bogus'] });
child.emit('close', 0);
await promise;
- const env = spawn.mock.calls[0][2].env;
+ const env = spawnDetached.mock.calls[0][2].env;
expect(env.PORTOS_FORCE_CLEAN_WORKSPACES).toBeUndefined();
});
});