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): resolve pm2 for the recovery and close the Windows exit gap
[._.]/ Adam Eivya4e5524d5b93
diff --git a/scripts/update-headless-recovery.test.js b/scripts/update-headless-recovery.test.jsindex ba033d6dc0..eb371d7adc 100644--- a/scripts/update-headless-recovery.test.js+++ b/scripts/update-headless-recovery.test.js@@ -23,14 +23,21 @@ const STUB_SCRIPTS = [* 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+ * @param {{origin?: boolean, failAfterDelete?: boolean, npmShim?: string,+ * forceClean?: boolean, pm2OnPath?: 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.+ * fails before anything is deleted. failAfterDelete fails the first step AFTER+ * the pm2 delete that does not also wipe node_modules. npmShim picks whether+ * `npm`/`npx` succeed ('ok'), fail ('fail' — which makes safe_install wipe+ * node_modules first) or stall ('slow', so a signal can arrive mid-window).+ * forceClean makes safe_install wipe root node_modules regardless of the diff,+ * pm2OnPath supplies a fallback pm2 for when that wipe removes the local one,+ * and healthy:false makes the health probe report the server never came back.*/-async function makeSandbox({ origin = true, failInstall = true, healthy = true } = {}) {+async function makeSandbox({+ origin = true, failAfterDelete = true, npmShim = 'ok',+ forceClean = false, pm2OnPath = false, healthy = true+} = {}) {const { scratch, repo } = await makeGitSandbox({ origin, prefix: 'portos-update-guard-' });const bin = join(scratch, 'bin');const calls = join(scratch, 'pm2-calls.log');@@ -51,7 +58,7 @@ async function makeSandbox({ origin = true, failInstall = true, healthy = true }`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`);+ writeFileSync(join(repo, 'scripts', 'trusted-rebuilds.js'), `process.exit(${failAfterDelete ? 1 : 0});\n`);for (const stub of STUB_SCRIPTS) {writeFileSync(join(repo, 'scripts', stub), 'process.exit(0);\n');}@@ -70,26 +77,46 @@ async function makeSandbox({ origin = true, failInstall = true, healthy = true }// 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.+ const npmBody = { ok: 'exit 0', fail: 'exit 1', slow: 'sleep 2\nexit 0' }[npmShim];for (const shim of ['npm', 'npx']) {- writeFileSync(join(bin, shim), '#!/bin/sh\nexit 0\n');+ writeFileSync(join(bin, shim), `#!/bin/sh\n${npmBody}\n`);chmodSync(join(bin, shim), 0o755);}+ // A pm2 the recovery can still reach after safe_install wipes the local one.+ if (pm2OnPath) {+ writeFileSync(join(bin, 'pm2'), `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(calls)}\n`);+ chmodSync(join(bin, 'pm2'), 0o755);+ }- return { scratch, repo, bin, calls };+ return { scratch, repo, bin, calls, forceClean };}// The three runs share no state, so they go out concurrently rather than// serializing three full update scripts.-function runUpdate(sandbox) {+function runUpdate(sandbox, { onStart } = {}) {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}` }- });+ const env = { ...process.env, PATH: `${sandbox.bin}:${process.env.PATH}` };+ if (sandbox.forceClean) env.PORTOS_FORCE_CLEAN_WORKSPACES = '.';+ const child = spawn('bash', [join(sandbox.repo, 'update.sh')], { cwd: sandbox.repo, env });let stdout = '';child.stdout.on('data', (d) => { stdout += d; });child.stderr.on('data', () => {});child.on('close', (status) => resolve({ status, stdout }));+ onStart?.(child);+ });+}++// Resolves once the sandbox's pm2 log contains a matching call, so a test can+// act at a precise point in the window instead of guessing at a delay.+function waitForPm2Call(sandbox, prefix, timeoutMs = 30000) {+ const deadline = Date.now() + timeoutMs;+ return new Promise((resolve, reject) => {+ const poll = () => {+ if (pm2Calls(sandbox).some(c => c.startsWith(prefix))) return resolve();+ if (Date.now() > deadline) return reject(new Error(`timed out waiting for pm2 "${prefix}"`));+ setTimeout(poll, 25);+ };+ poll();});}@@ -102,10 +129,13 @@ describe.skipIf(process.platform === 'win32' || SKIP_HEAVY_INTEGRATION)('update.beforeAll(async () => {const cases = {- failed: { failInstall: true },- clean: { failInstall: false },+ failed: {},+ clean: { failAfterDelete: false },preDelete: { origin: false },- unhealthy: { failInstall: true, healthy: false }+ unhealthy: { healthy: false },+ // The failure the guard's own comment names: both npm installs fail, and+ // safe_install wiped root node_modules — pm2 included — on the way.+ pm2Wiped: { npmShim: 'fail', forceClean: true, pm2OnPath: true }};await Promise.all(Object.entries(cases).map(async ([name, options]) => {sandboxes[name] = await makeSandbox(options);@@ -145,6 +175,40 @@ describe.skipIf(process.platform === 'win32' || SKIP_HEAVY_INTEGRATION)('update.expect(results.unhealthy.stdout).not.toContain('STEP:restart:warning:');});+ it('restarts through a pm2 the failed install did not delete', () => {+ // safe_install wipes root node_modules (pm2 is a ROOT dependency) before it+ // retries, so a recovery hardcoded to ./node_modules/pm2/bin/pm2 would be a+ // no-op on the most likely failure of all.+ const calls = pm2Calls(sandboxes.pm2Wiped);+ 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);+ expect(results.pm2Wiped.status).not.toBe(0);+ });++ it('restarts the apps when the update is killed mid-window', async () => {+ // Without the TERM/INT/HUP traps bash runs NO exit trap for a fatal signal,+ // so the apps would stay deleted.+ const box = await makeSandbox({ npmShim: 'slow' });+ try {+ const result = await runUpdate(box, {+ onStart: (child) => {+ waitForPm2Call(box, 'delete ecosystem.config.cjs')+ .then(() => child.kill('SIGTERM'))+ .catch(() => child.kill('SIGKILL'));+ }+ });+ const calls = pm2Calls(box);+ const deleteAt = calls.findIndex(c => c.startsWith('delete ecosystem.config.cjs'));+ const startAt = calls.findIndex(c => c.startsWith('start ecosystem.config.cjs'));+ expect(startAt, `pm2 calls were: ${JSON.stringify(calls)}`).toBeGreaterThan(deleteAt);+ expect(result.status).toBe(143);+ } finally {+ await destroyGitSandbox(box.scratch);+ }+ }, 120000);+it('does not touch PM2 when the update aborts before the delete', () => {expect(results.preDelete.status).not.toBe(0);expect(pm2Calls(sandboxes.preDelete)).toEqual([]);@@ -153,30 +217,39 @@ describe.skipIf(process.platform === 'win32' || SKIP_HEAVY_INTEGRATION)('update./*** 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.+ * here, so guard the invariant that makes its recovery reachable: PowerShell's+ * `exit` inside a function terminates the whole script WITHOUT raising a+ * terminating error, bypassing both Stop-UpdateScript and the script-scope trap.+ * So every fatal exit in the file must route through Stop-UpdateScript. Scanning+ * the whole file rather than the delete→start line window is the point: the+ * exit that actually caused this bug lives in Safe-Install, which is DEFINED+ * above the delete and CALLED below it.*/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([]);+ // The only two script-terminating exits that may bypass the recovery: the one+ // Stop-UpdateScript itself performs (after running it), and the final status.+ const SANCTIONED_EXITS = ['exit $Code', 'exit $verifyFailed'];++ it('routes every fatal exit through the recovery', () => {+ const exits = ps1+ .map((line, i) => ({ line: line.trim(), number: i + 1 }))+ .filter(({ line }) => /(^|[{;]\s*)exit\b/.test(line) || line.includes('[Environment]::Exit('));++ const offenders = exits.filter(({ line }) => !SANCTIONED_EXITS.includes(line));+ expect(offenders, `exit(s) bypassing Restore-Pm2Apps: ${JSON.stringify(offenders)}`).toEqual([]);+ // ...and both sanctioned exits must still be there, so the guard can't be+ // "satisfied" by deleting the exit inside Stop-UpdateScript.+ expect([...new Set(exits.map(e => e.line))].sort()).toEqual([...SANCTIONED_EXITS].sort());});- it('installs the recovery before the delete that makes it necessary', () => {+ it('defines the recovery before every call site that depends on it', () => {+ const definedAt = lineOf('function Stop-UpdateScript');+ expect(definedAt).toBeGreaterThan(-1);+ const firstCall = ps1.findIndex(line => line.includes('Stop-UpdateScript ') && !line.includes('function '));+ expect(firstCall).toBeGreaterThan(definedAt);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.ps1index 10ff7ef29a..0d82d00c5b 100644--- a/update.ps1+++ b/update.ps1@@ -76,6 +76,94 @@ function Invoke-Logged {& $cmd @cmdRest >> $UpdateLog 2>&1}+# 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.+#+# This block sits here — above every fatal exit in the script, not beside the+# delete it guards — because PowerShell's `exit` inside a function terminates the+# whole script WITHOUT raising a terminating error, bypassing both the trap and+# any later-defined helper. Safe-Install is defined above the delete and called+# below it, so a guard defined between them could never catch its exit.+#+# 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++# Which pm2 the recovery can actually reach. It CANNOT assume this checkout's own+# copy: Safe-Install wipes root node_modules whenever the pulled update touched+# root package.json — which every release does, since the version bump lives+# there — and pm2 is a ROOT dependency. So on the most likely failure of all+# (both npm install attempts fail) the checkout's pm2 is already gone by the time+# the recovery runs. Any pm2 CLI can drive the already-running daemon, so falling+# back to one on PATH, or to npx, is fine for a recovery.+function Resolve-Pm2Command {+ if (Test-Path "$RootDir\node_modules\pm2\bin\pm2") {+ return @('node', './node_modules/pm2/bin/pm2')+ }+ if (Get-Command pm2 -ErrorAction SilentlyContinue) {+ return @('pm2')+ }+ $pinned = try { (Get-Content "$RootDir\package.json" -Raw | ConvertFrom-Json).dependencies.pm2 } catch { $null }+ if ($pinned) { return @('npx', '--yes', "pm2@$pinned") }+ return @('npx', '--yes', 'pm2')+}++function Restore-Pm2Apps {+ if (-not $script:Pm2AppsDown) { return }+ $script:Pm2AppsDown = $false+ try {+ $pm2 = Resolve-Pm2Command+ 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.+ $startArgs = $pm2 + @('start', 'ecosystem.config.cjs')+ Invoke-Logged @startArgs+ if ($LASTEXITCODE -eq 0) { Invoke-Logged node scripts/verify-server-health.js }+ if ($LASTEXITCODE -eq 0) {+ $saveArgs = $pm2 + @('save')+ Invoke-Logged @saveArgs+ 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+ # Name the pm2 that actually exists — the checkout's copy may be the+ # thing a failed install just deleted, so printing it would be a dead end.+ Write-SafeHost " Recover with: $($pm2 -join ' ') 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 in this script goes through here, so the recovery cannot be+# forgotten at one of the call sites. Before the delete it is a no-op.+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+}+Write-SafeHost "===================================" -ForegroundColor CyanWrite-SafeHost " PortOS Update" -ForegroundColor CyanWrite-SafeHost "===================================" -ForegroundColor Cyan@@ -202,7 +290,7 @@ if ($currentBranch -ne "main") {Write-SafeHost "⚠️ On branch '$currentBranch' — switching to main for update" -ForegroundColor Yellow}Invoke-Logged git checkout main- if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+ if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }}# Record main's pre-pull HEAD — captured AFTER any checkout so it's the commit# the installed node_modules was built from (main, which the rest of this script@@ -211,7 +299,7 @@ if ($currentBranch -ne "main") {# the update brings is detected even when launched from another branch.$prePullSha = git rev-parse HEAD 2>$nullInvoke-Logged git pull --rebase --autostash-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }Step "git-pull" "done" "Latest changes pulled"# Determine which workspaces' package.json this update touched, so Safe-Install@@ -239,70 +327,12 @@ Write-SafeHost ""# contract, not whichever submodule commit happens to be newest upstream.Step "submodules" "running" "Synchronizing and updating submodules..."Invoke-Logged git submodule sync --recursive-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }Invoke-Logged git submodule update --init --recursive-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $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 reloaddiff --git a/update.sh b/update.shindex b2a7cc77ea..b93a287a1a 100755--- a/update.sh+++ b/update.sh@@ -186,25 +186,55 @@ log ""# recovery only ever runs on a path that was already leaving PortOS down.PM2_APPS_DOWN=0+# Which pm2 the recovery can actually reach. It CANNOT assume this checkout's+# own copy: `safe_install .` wipes root node_modules whenever the pulled update+# touched root package.json — which every release does, since the version bump+# lives there — and pm2 is a ROOT dependency. So on the most likely failure of+# all (both npm install attempts fail: offline, registry 5xx, ENOSPC) the+# checkout's pm2 is already gone by the time the trap runs, and a hardcoded+# ./node_modules/pm2/bin/pm2 would make the recovery a no-op exactly when it is+# needed most. Prefer the local copy, fall back to a pm2 on PATH, then to npx at+# the version package.json pins. Any pm2 CLI can drive the already-running+# daemon, so a version difference is fine for a recovery.+PM2_CMD=()+resolve_pm2_cmd() {+ if [ -f "$ROOT_DIR/node_modules/pm2/bin/pm2" ]; then+ PM2_CMD=(node "$ROOT_DIR/node_modules/pm2/bin/pm2")+ elif command -v pm2 >/dev/null 2>&1; then+ PM2_CMD=(pm2)+ else+ local pinned+ pinned=$(node -e 'const d=require("./package.json").dependencies||{}; process.stdout.write(typeof d.pm2 === "string" ? d.pm2 : "")' 2>/dev/null || echo "")+ if [ -n "$pinned" ]; then+ PM2_CMD=(npx --yes "pm2@$pinned")+ else+ PM2_CMD=(npx --yes pm2)+ fi+ fi+}+restore_pm2_apps_on_exit() {local status=$?trap - EXITif [ "$PM2_APPS_DOWN" = "1" ]; thenPM2_APPS_DOWN=0+ resolve_pm2_cmdlog "⚠️ 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+ if run "${PM2_CMD[@]}" start ecosystem.config.cjs && run node scripts/verify-server-health.js; then+ run "${PM2_CMD[@]}" save || truestep "restart" "warning" "Update failed, but PortOS was restarted"log "✅ PortOS is answering /api/system/health again after the failed update."elsestep "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"+ # Name the pm2 that actually exists — the checkout's copy may be the thing+ # a failed install just deleted, so printing it would be a dead-end hint.+ log " Recover with: ${PM2_CMD[*]} start ecosystem.config.cjs"fi# Recovery must never turn a failed update into a reported success.if [ "$status" -eq 0 ]; then status=1; fi