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

restart PortOS's PM2 apps when an update aborts between the delete and the start

[._.]/ Adam Eivy164ff8f3d996
diff --git a/scripts/update-headless-recovery.test.js b/scripts/update-headless-recovery.test.js
new file mode 100644
index 0000000000..ba033d6dc0
--- /dev/null
+++ b/scripts/update-headless-recovery.test.js
@@ -0,0 +1,183 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { spawn } from 'child_process';
+import { mkdirSync, writeFileSync, copyFileSync, readFileSync, existsSync, chmodSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../server/lib/gitTestRepo.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const UPDATE_SH = join(REPO_ROOT, 'update.sh');
+
+// Everything update.sh shells out to between the pm2 delete and the pm2 start.
+// Stubbing them lets the success path run end to end offline, which is the only
+// way to prove the exit trap does NOT start the apps a second time.
+const STUB_SCRIPTS = [
+ 'setup-data.js', 'setup-db.js', 'setup-browser.js', 'setup-ghostty.js',
+ 'setup-cert.js', 'setup-guide.js', 'run-migrations.js',
+ 'verify-server-health.js', 'print-access-url.js', 'open-ui-in-browser.js'
+];
+
+/**
+ * A throwaway checkout of update.sh with `npm`, `npx` and `pm2` shimmed, so the
+ * assertions below are what the script actually does to PM2 rather than a grep
+ * for the guard's source text. The rationale for the guard itself lives with it
+ * in update.sh.
+ *
+ * @param {{origin?: boolean, failInstall?: boolean, healthy?: boolean}} options
+ * origin:false leaves the checkout with no upstream, so the git-pull step
+ * fails before anything is deleted. failInstall fails the first step AFTER
+ * the pm2 delete that does not also wipe node_modules (safe_install's retry
+ * would delete the pm2 shim with it). healthy:false makes the health probe
+ * report the restarted server never came back.
+ */
+async function makeSandbox({ origin = true, failInstall = true, healthy = true } = {}) {
+ const { scratch, repo } = await makeGitSandbox({ origin, prefix: 'portos-update-guard-' });
+ const bin = join(scratch, 'bin');
+ const calls = join(scratch, 'pm2-calls.log');
+
+ mkdirSync(bin, { recursive: true });
+ mkdirSync(join(repo, 'scripts'), { recursive: true });
+ mkdirSync(join(repo, 'node_modules', 'pm2', 'bin'), { recursive: true });
+
+ copyFileSync(UPDATE_SH, join(repo, 'update.sh'));
+ chmodSync(join(repo, 'update.sh'), 0o755);
+ writeFileSync(join(repo, 'package.json'), JSON.stringify({ name: 'sandbox', version: '0.0.0' }));
+ writeFileSync(join(repo, 'ecosystem.config.cjs'), 'module.exports = { apps: [] };\n');
+
+ // Records every pm2 invocation the script makes, in order.
+ writeFileSync(join(repo, 'node_modules', 'pm2', 'package.json'), JSON.stringify({ name: 'pm2', version: '0.0.0' }));
+ writeFileSync(
+ join(repo, 'node_modules', 'pm2', 'bin', 'pm2'),
+ `require('fs').appendFileSync(${JSON.stringify(calls)}, process.argv.slice(2).join(' ') + '\\n');\n`
+ );
+
+ writeFileSync(join(repo, 'scripts', 'trusted-rebuilds.js'), `process.exit(${failInstall ? 1 : 0});\n`);
+ for (const stub of STUB_SCRIPTS) {
+ writeFileSync(join(repo, 'scripts', stub), 'process.exit(0);\n');
+ }
+ writeFileSync(join(repo, 'scripts', 'verify-server-health.js'), `process.exit(${healthy ? 0 : 1});\n`);
+ // Non-zero means "the daemon is already ours", which skips the co-located
+ // `pm2 update` restart — the branch a healthy install takes.
+ writeFileSync(join(repo, 'scripts', 'pm2-daemon-refresh.js'), 'process.exit(1);\n');
+
+ // The workspaces safe_install cd's into, and the dependency it sanity-checks.
+ for (const ws of ['client', 'server', 'autofixer']) {
+ mkdirSync(join(repo, ws), { recursive: true });
+ writeFileSync(join(repo, ws, 'package.json'), JSON.stringify({ name: ws, version: '0.0.0' }));
+ }
+ mkdirSync(join(repo, 'client', 'node_modules', 'vite', 'bin'), { recursive: true });
+ writeFileSync(join(repo, 'client', 'node_modules', 'vite', 'bin', 'vite.js'), '');
+
+ // update.sh only ever calls these as bare commands, so a PATH shim covers
+ // every install and the slash-do refresh without touching the network.
+ for (const shim of ['npm', 'npx']) {
+ writeFileSync(join(bin, shim), '#!/bin/sh\nexit 0\n');
+ chmodSync(join(bin, shim), 0o755);
+ }
+
+ return { scratch, repo, bin, calls };
+}
+
+// The three runs share no state, so they go out concurrently rather than
+// serializing three full update scripts.
+function runUpdate(sandbox) {
+ return new Promise((resolve) => {
+ const child = spawn('bash', [join(sandbox.repo, 'update.sh')], {
+ cwd: sandbox.repo,
+ env: { ...process.env, PATH: `${sandbox.bin}:${process.env.PATH}` }
+ });
+ let stdout = '';
+ child.stdout.on('data', (d) => { stdout += d; });
+ child.stderr.on('data', () => {});
+ child.on('close', (status) => resolve({ status, stdout }));
+ });
+}
+
+const pm2Calls = (sandbox) =>
+ (existsSync(sandbox.calls) ? readFileSync(sandbox.calls, 'utf8') : '').split('\n').filter(Boolean);
+
+describe.skipIf(process.platform === 'win32' || SKIP_HEAVY_INTEGRATION)('update.sh headless-install guard', () => {
+ const sandboxes = {};
+ const results = {};
+
+ beforeAll(async () => {
+ const cases = {
+ failed: { failInstall: true },
+ clean: { failInstall: false },
+ preDelete: { origin: false },
+ unhealthy: { failInstall: true, healthy: false }
+ };
+ await Promise.all(Object.entries(cases).map(async ([name, options]) => {
+ sandboxes[name] = await makeSandbox(options);
+ }));
+ await Promise.all(Object.keys(cases).map(async (name) => {
+ results[name] = await runUpdate(sandboxes[name]);
+ }));
+ }, 180000);
+
+ afterAll(async () => {
+ await Promise.all(Object.values(sandboxes).map(box => destroyGitSandbox(box.scratch)));
+ });
+
+ it('restarts the PM2 apps it deleted when a later step aborts the update', () => {
+ const calls = pm2Calls(sandboxes.failed);
+ const deleteAt = calls.findIndex(c => c.startsWith('delete ecosystem.config.cjs'));
+ const startAt = calls.findIndex(c => c.startsWith('start ecosystem.config.cjs'));
+ expect(deleteAt, `pm2 calls were: ${JSON.stringify(calls)}`).toBeGreaterThan(-1);
+ expect(startAt, `pm2 calls were: ${JSON.stringify(calls)}`).toBeGreaterThan(deleteAt);
+ });
+
+ it('still reports the update as failed after recovering', () => {
+ expect(results.failed.status).not.toBe(0);
+ expect(results.failed.stdout).toContain('STEP:restart:warning:');
+ });
+
+ it('starts the apps exactly once on an update that succeeds', () => {
+ expect(results.clean.status, results.clean.stdout).toBe(0);
+ expect(pm2Calls(sandboxes.clean).filter(c => c.startsWith('start ecosystem.config.cjs'))).toHaveLength(1);
+ expect(results.clean.stdout).toContain('STEP:restart:done:');
+ expect(results.clean.stdout).not.toContain('STEP:restart:warning:');
+ });
+
+ it('does not claim a recovery the health probe never confirmed', () => {
+ expect(results.unhealthy.status).not.toBe(0);
+ expect(results.unhealthy.stdout).toContain('STEP:restart:error:');
+ expect(results.unhealthy.stdout).not.toContain('STEP:restart:warning:');
+ });
+
+ it('does not touch PM2 when the update aborts before the delete', () => {
+ expect(results.preDelete.status).not.toBe(0);
+ expect(pm2Calls(sandboxes.preDelete)).toEqual([]);
+ });
+});
+
+/**
+ * update.ps1 is the Windows half of the same bracket and cannot be executed
+ * here, so guard the invariant that makes its recovery reachable: every fatal
+ * exit between the pm2 delete and the successful start must route through
+ * Stop-UpdateScript. A future step added to that window with a bare `exit`
+ * would silently reintroduce the headless failure on Windows only.
+ */
+describe('update.ps1 headless-install guard', () => {
+ const ps1 = readFileSync(join(REPO_ROOT, 'update.ps1'), 'utf8').split('\n');
+ const lineOf = (needle) => ps1.findIndex(line => line.includes(needle));
+
+ it('routes every fatal exit in the delete→start window through the recovery', () => {
+ const deleteAt = lineOf('$script:Pm2AppsDown = $true');
+ // The latch is cleared in Restore-Pm2Apps too; the LAST clear is the real start.
+ const startedAt = ps1.findLastIndex(line => line.includes('$script:Pm2AppsDown = $false'));
+ expect(deleteAt).toBeGreaterThan(-1);
+ expect(startedAt).toBeGreaterThan(deleteAt);
+
+ const rawExits = ps1
+ .slice(deleteAt, startedAt)
+ .map((line, i) => ({ line: line.trim(), number: deleteAt + i + 1 }))
+ .filter(({ line }) => /(^|[{;]\s*)exit\b/.test(line));
+ expect(rawExits, `bare exit(s) skip Restore-Pm2Apps: ${JSON.stringify(rawExits)}`).toEqual([]);
+ });
+
+ it('installs the recovery before the delete that makes it necessary', () => {
+ expect(lineOf('function Restore-Pm2Apps')).toBeLessThan(lineOf('$script:Pm2AppsDown = $true'));
+ expect(lineOf('trap {')).toBeLessThan(lineOf('$script:Pm2AppsDown = $true'));
+ });
+});
diff --git a/update.ps1 b/update.ps1
index 8168aa4a6b..10ff7ef29a 100644
--- a/update.ps1
+++ b/update.ps1
@@ -146,7 +146,7 @@ function Safe-Install {
Pop-Location
Write-SafeHost "❌ npm install failed for $Label after retry" -ForegroundColor Red
- exit 1
+ Stop-UpdateScript 1
}
# Pull latest — always switch to main (detached HEAD or feature branch both
@@ -245,12 +245,71 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Step "submodules" "done" "Submodules updated"
Write-SafeHost ""
+# Headless-install guard (mirrors update.sh). From the `pm2-stop` step below
+# until the closing `pm2 start` succeeds, PortOS's PM2 entries are DELETED — the
+# install has no server. Every step in between (npm install, setup-db,
+# migrations, the client build) can fail, and each of those failures exits this
+# script with the apps still deleted and nothing left running to notice: the
+# "update deleted portos-server and it never came back" failure. So restore the
+# apps on the way out instead of leaving the machine headless.
+#
+# Starting the pulled tree after a failed install can crash-loop, but a
+# crash-looping app the user can see beats a silently headless machine — and the
+# recovery only ever runs on a path that was already leaving PortOS down.
+$script:Pm2AppsDown = $false
+
+function Restore-Pm2Apps {
+ if (-not $script:Pm2AppsDown) { return }
+ $script:Pm2AppsDown = $false
+ try {
+ Write-SafeHost "⚠️ Update is exiting with PortOS's apps deleted — restarting them so the install isn't left headless." -ForegroundColor Yellow
+ Step "restart" "running" "Update failed — restarting PortOS so it isn't left down..."
+ # `pm2 start` exiting 0 is not proof the server came back (same reason the
+ # verify step below exists) — and this path starts a HALF-INSTALLED tree, so
+ # a start that exits 0 and then crash-loops is the likely case here, not the
+ # edge case. Never claim a recovery the health probe doesn't confirm.
+ Invoke-Logged node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs
+ if ($LASTEXITCODE -eq 0) { Invoke-Logged node scripts/verify-server-health.js }
+ if ($LASTEXITCODE -eq 0) {
+ Invoke-Logged node ./node_modules/pm2/bin/pm2 save
+ Step "restart" "warning" "Update failed, but PortOS was restarted"
+ Write-SafeHost "✅ PortOS is answering /api/system/health again after the failed update." -ForegroundColor Green
+ } else {
+ Step "restart" "error" "Update failed and PortOS is DOWN"
+ Write-SafeHost "❌ PortOS is not answering /api/system/health." -ForegroundColor Red
+ Write-SafeHost " Recover with: node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs" -ForegroundColor Red
+ }
+ } catch {
+ # A throwing recovery must not replace the real update failure, and must
+ # not re-enter the trap below.
+ Write-SafeHost "❌ PortOS restart attempt failed: $($_.Exception.Message)" -ForegroundColor Red
+ }
+}
+
+# Every fatal exit between the delete and the start goes through here, so the
+# recovery cannot be forgotten at one of the ten call sites.
+function Stop-UpdateScript {
+ param([int]$Code = 1)
+ Restore-Pm2Apps
+ # Recovery must never turn a failed update into a reported success.
+ if ($Code -eq 0) { $Code = 1 }
+ exit $Code
+}
+
+# Backstop for a terminating error nobody converted into a Stop-UpdateScript
+# call; `break` rethrows so the script still exits non-zero.
+trap {
+ Restore-Pm2Apps
+ break
+}
+
# Remove ONLY PortOS's apps from the shared PM2 daemon — never `pm2 kill`, which
# tears down the daemon and stops EVERY other project's apps on this machine.
# The daemon itself is left alone here; whether it also needs an in-place reload
# is decided in the restart step below, against the freshly installed pm2.
Step "pm2-stop" "running" "Stopping PortOS apps..."
Invoke-Logged node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent
+$script:Pm2AppsDown = $true
$global:LASTEXITCODE = 0
Step "pm2-stop" "done" "Apps stopped"
Write-SafeHost ""
@@ -271,14 +330,14 @@ Safe-Install -Dir "autofixer" -Label "autofixer"
# (vite 8 dropped the esbuild binary dependency that used to be the reason).
Write-SafeHost "🔧 Rebuilding trusted native dependencies..." -ForegroundColor Yellow
Invoke-Logged node scripts/trusted-rebuilds.js server
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Write-SafeHost ""
# Verify critical dependencies exist
if (-not (Test-Path "client/node_modules/vite/bin/vite.js")) {
Write-SafeHost "❌ Critical dependency missing: client/node_modules/vite" -ForegroundColor Red
Write-SafeHost " Try running: npm run install:all"
- exit 1
+ Stop-UpdateScript 1
}
Step "npm-install" "done" "Dependencies installed"
@@ -287,11 +346,11 @@ Step "npm-install" "done" "Dependencies installed"
# `npm run setup` and are idempotent.
Step "setup" "running" "Running setup..."
Invoke-Logged node scripts/setup-data.js
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Invoke-Logged node scripts/setup-db.js
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Invoke-Logged node scripts/setup-browser.js
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Invoke-Logged node scripts/setup-ghostty.js
Step "setup" "done" "Setup complete"
Write-SafeHost ""
@@ -301,7 +360,7 @@ Write-SafeHost ""
# failed update; setup-guide owns the shared human-readable next step.
Step "network-setup" "running" "Checking Tailscale, MagicDNS, and HTTPS..."
Invoke-Logged node scripts/setup-cert.js
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
$networkSummary = & {
$ErrorActionPreference = 'Continue'
& node scripts/setup-guide.js --summary 2>> $UpdateLog
@@ -318,7 +377,7 @@ Step "migrations" "running" "Running data migrations..."
$migrationsScript = Join-Path $RootDir "scripts\run-migrations.js"
if (Test-Path $migrationsScript) {
Invoke-Logged node $migrationsScript
- if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
}
Step "migrations" "done" "Migrations complete"
@@ -345,7 +404,7 @@ Write-SafeHost ""
# Build UI assets for production serving
Step "build" "running" "Building client..."
Invoke-Logged npm run build
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Step "build" "done" "Client built"
Write-SafeHost ""
@@ -353,7 +412,7 @@ Write-SafeHost ""
$Tag = (Get-Content package.json -Raw | ConvertFrom-Json).version
if (-not $Tag) {
Write-SafeHost "❌ Failed to determine package version from package.json" -ForegroundColor Red
- exit 1
+ Stop-UpdateScript 1
}
$completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
$markerObj = @{ version = $Tag; completedAt = $completedAt }
@@ -388,8 +447,9 @@ if ($LASTEXITCODE -ne 0) {
if (Test-Path "$RootDir\data\update-complete.json") {
Remove-Item -Force "$RootDir\data\update-complete.json"
}
- exit $LASTEXITCODE
+ Stop-UpdateScript $LASTEXITCODE
}
+$script:Pm2AppsDown = $false
Invoke-Logged node ./node_modules/pm2/bin/pm2 save
$global:LASTEXITCODE = 0
Step "restart" "done" "PortOS started"
diff --git a/update.sh b/update.sh
index 9b14b08043..b2a7cc77ea 100755
--- a/update.sh
+++ b/update.sh
@@ -173,12 +173,58 @@ run git submodule update --init --recursive
step "submodules" "done" "Submodules updated"
log ""
+# Headless-install guard. From the `pm2-stop` step below until the closing
+# `pm2 start` succeeds, PortOS's PM2 entries are DELETED — the install has no
+# server. Every step in between (npm install, setup-db, migrations, the client
+# build) can fail, and `set -e` would then exit with the apps still deleted and
+# nothing left running to notice: the "update deleted portos-server and it never
+# came back" failure. #5976 made this script SURVIVE pm2's tree-kill; it did not
+# cover the script exiting on its own. So trap the exit and put the apps back.
+#
+# Starting the pulled tree after a failed install can crash-loop, but a
+# crash-looping app the user can see beats a silently headless machine — and the
+# recovery only ever runs on a path that was already leaving PortOS down.
+PM2_APPS_DOWN=0
+
+restore_pm2_apps_on_exit() {
+ local status=$?
+ trap - EXIT
+ if [ "$PM2_APPS_DOWN" = "1" ]; then
+ PM2_APPS_DOWN=0
+ log "⚠️ Update is exiting (status $status) with PortOS's apps deleted — restarting them so the install isn't left headless."
+ step "restart" "running" "Update failed — restarting PortOS so it isn't left down..."
+ # `pm2 start` exiting 0 is not proof the server came back (same reason the
+ # verify step below exists) — and this path starts a HALF-INSTALLED tree, so
+ # a start that exits 0 and then crash-loops is the likely case here, not the
+ # edge case. Never claim a recovery the health probe doesn't confirm.
+ if run node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && run node scripts/verify-server-health.js; then
+ run node ./node_modules/pm2/bin/pm2 save || true
+ step "restart" "warning" "Update failed, but PortOS was restarted"
+ log "✅ PortOS is answering /api/system/health again after the failed update."
+ else
+ step "restart" "error" "Update failed and PortOS is DOWN"
+ log "❌ PortOS is not answering /api/system/health."
+ log " Recover with: node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs"
+ fi
+ # Recovery must never turn a failed update into a reported success.
+ if [ "$status" -eq 0 ]; then status=1; fi
+ fi
+ exit "$status"
+}
+trap restore_pm2_apps_on_exit EXIT
+# Turn a fatal signal into an ordinary exit so the EXIT trap above still runs
+# (bash does not run an EXIT trap for an untrapped fatal signal).
+trap 'exit 143' TERM
+trap 'exit 130' INT
+trap 'exit 129' HUP
+
# Remove ONLY PortOS's apps from the shared PM2 daemon — never `pm2 kill`, which
# tears down the daemon and stops EVERY other project's apps on this machine.
# The daemon itself is left alone here; whether it also needs an in-place reload
# is decided in the restart step below, against the freshly installed pm2.
step "pm2-stop" "running" "Stopping PortOS apps..."
run node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || true
+PM2_APPS_DOWN=1
step "pm2-stop" "done" "Apps stopped"
log ""
@@ -354,6 +400,7 @@ if ! run node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs; then
rm -f "$ROOT_DIR/data/update-complete.json"
exit 1
fi
+PM2_APPS_DOWN=0
run node ./node_modules/pm2/bin/pm2 save || true
step "restart" "done" "PortOS started"
log ""