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

only run `pm2 update` during self-update when the daemon isn't already ours

[._.]/ Adam Eivyc49e689afe27
diff --git a/scripts/pm2-daemon-refresh.js b/scripts/pm2-daemon-refresh.js
new file mode 100644
index 0000000000..c1f7e864fe
--- /dev/null
+++ b/scripts/pm2-daemon-refresh.js
@@ -0,0 +1,121 @@
+/**
+ * "Does the running PM2 daemon still need a `pm2 update`?"
+ *
+ * `pm2 update` reloads the daemon in place — it kills the God process and
+ * resurrects everything from the dump. That refreshes the daemon's cached
+ * ProcessContainerFork.js path (a stale path from a daemon originally launched
+ * by another project — e.g. a Yarn PnP zip cache — makes every subsequent
+ * fork() crash with MODULE_NOT_FOUND), but it also RESTARTS every co-located
+ * app on the machine. PortOS shares one PM2 daemon with whatever else the user
+ * runs, so paying that cost on every self-update interrupts unrelated projects
+ * for a refresh they almost never need.
+ *
+ * They need it only when the live daemon is not the one this checkout's
+ * node_modules would launch: a different install path, or a different pm2
+ * version. This probe answers that question so update.sh / update.ps1 can run
+ * `pm2 update` in exactly that case and leave the daemon alone otherwise.
+ *
+ * Usage as a CLI (what update.sh and update.ps1 call):
+ * node scripts/pm2-daemon-refresh.js
+ *
+ * Exit 0 → refresh needed, run `pm2 update`.
+ * Exit 1 → daemon already matches this checkout, skip it.
+ *
+ * Fails OPEN: anything unexpected (no report, an RPC error, an unrecognized
+ * argv shape) exits 0 and restores the unconditional behavior. A needless
+ * daemon reload is an annoyance; skipping a needed one leaves PortOS unable to
+ * fork a single app.
+ */
+
+import { readFileSync, realpathSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+
+const ROOT_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+// APFS and NTFS are case-insensitive, and the daemon's argv is whatever spelling
+// launched it — realpath + case-fold so two spellings of one file compare equal.
+const normalizePath = (path) => {
+ let resolved = path;
+ try {
+ resolved = realpathSync(path);
+ } catch {
+ // Path no longer exists (node_modules wiped since the daemon launched) —
+ // compare the literal spelling rather than giving up.
+ }
+ return process.platform === 'win32' || process.platform === 'darwin'
+ ? resolved.toLowerCase()
+ : resolved;
+};
+
+/**
+ * The `lib/Daemon.js` entry out of the daemon's own process.argv.
+ * @param {string[]|string} argv - `report.argv` (array; string-joined on older daemons)
+ * @returns {string|null} the Daemon.js path, or null when argv has no recognizable entry
+ */
+export function daemonEntryFromArgv(argv) {
+ const parts = Array.isArray(argv) ? argv : typeof argv === 'string' ? argv.split(',') : [];
+ return parts.find((part) => /Daemon\.js$/.test(String(part).trim())) ?? null;
+}
+
+/**
+ * Whether the live daemon has to be reloaded to match this checkout.
+ * @param {object} options
+ * @param {object|null} options.report - the daemon's `getReport` payload
+ * @param {string} options.expectedEntry - path to this checkout's pm2 lib/Daemon.js
+ * @param {string} options.expectedVersion - this checkout's installed pm2 version
+ * @returns {{ needed: boolean, reason: string }}
+ */
+export function daemonNeedsRefresh({ report, expectedEntry, expectedVersion }) {
+ if (!report) return { needed: true, reason: 'daemon did not report its identity' };
+
+ const entry = daemonEntryFromArgv(report.argv);
+ if (!entry) return { needed: true, reason: 'daemon argv has no Daemon.js entry' };
+ if (normalizePath(entry) !== normalizePath(expectedEntry)) {
+ return { needed: true, reason: 'daemon runs from a different pm2 install' };
+ }
+
+ // A version mismatch means node_modules was upgraded under a daemon still
+ // executing the old code — the CLI would talk to a daemon it no longer matches.
+ if (report.pm2_version !== expectedVersion) {
+ return {
+ needed: true,
+ reason: `daemon is pm2 ${report.pm2_version}, this checkout has ${expectedVersion}`,
+ };
+ }
+
+ return { needed: false, reason: 'daemon already runs this checkout of pm2' };
+}
+
+async function fetchReport(pm2) {
+ await new Promise((resolve, reject) => {
+ pm2.connect((err) => (err ? reject(err) : resolve()));
+ });
+ try {
+ return await new Promise((resolve, reject) => {
+ pm2.Client.executeRemote('getReport', {}, (err, report) => (err ? reject(err) : resolve(report)));
+ });
+ } finally {
+ pm2.disconnect();
+ }
+}
+
+async function runCli() {
+ let verdict = { needed: true, reason: 'could not inspect the running daemon' };
+ try {
+ const pm2Dir = join(ROOT_DIR, 'node_modules', 'pm2');
+ const { default: pm2 } = await import('pm2');
+ verdict = daemonNeedsRefresh({
+ report: await fetchReport(pm2),
+ expectedEntry: join(pm2Dir, 'lib', 'Daemon.js'),
+ expectedVersion: JSON.parse(readFileSync(join(pm2Dir, 'package.json'), 'utf8')).version,
+ });
+ } catch (err) {
+ verdict = { needed: true, reason: `daemon probe failed: ${err.message}` };
+ }
+ console.log(`${verdict.needed ? '🔄' : '✅'} PM2 daemon refresh ${verdict.needed ? 'needed' : 'skipped'}: ${verdict.reason}`);
+ return verdict.needed ? 0 : 1;
+}
+
+if (isDirectlyInvoked(import.meta.url)) process.exit(await runCli());
diff --git a/scripts/pm2-daemon-refresh.test.js b/scripts/pm2-daemon-refresh.test.js
new file mode 100644
index 0000000000..89290e9a08
--- /dev/null
+++ b/scripts/pm2-daemon-refresh.test.js
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { daemonEntryFromArgv, daemonNeedsRefresh } from './pm2-daemon-refresh.js';
+
+// A path that really exists in this checkout, so realpath resolution in the
+// comparison exercises the same branch it takes during an update.
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const OURS = join(ROOT, 'node_modules', 'pm2', 'lib', 'Daemon.js');
+const VERSION = '7.0.4';
+
+const report = (overrides = {}) => ({
+ pm2_version: VERSION,
+ argv: ['/usr/local/bin/node', OURS],
+ ...overrides,
+});
+
+const check = (overrides) =>
+ daemonNeedsRefresh({
+ report: report(overrides),
+ expectedEntry: OURS,
+ expectedVersion: VERSION,
+ });
+
+describe('daemonEntryFromArgv', () => {
+ it('finds the Daemon.js entry in a real argv array', () => {
+ expect(daemonEntryFromArgv(['/usr/bin/node', OURS])).toBe(OURS);
+ });
+
+ it('accepts the comma-joined string an older daemon may report', () => {
+ expect(daemonEntryFromArgv(`/usr/bin/node,${OURS}`)).toBe(OURS);
+ });
+
+ it('returns null when argv carries no Daemon.js entry', () => {
+ expect(daemonEntryFromArgv(['/usr/bin/node', '/somewhere/else.js'])).toBeNull();
+ expect(daemonEntryFromArgv(undefined)).toBeNull();
+ });
+});
+
+describe('daemonNeedsRefresh', () => {
+ it('skips the reload when the daemon already runs this checkout of pm2', () => {
+ // The whole point: co-located apps on the shared daemon are not restarted.
+ expect(check()).toEqual({ needed: false, reason: expect.any(String) });
+ });
+
+ it('reloads when the daemon runs from another project\'s pm2 install', () => {
+ // The MODULE_NOT_FOUND case — a stale ProcessContainerFork.js path.
+ expect(check({ argv: ['/usr/bin/node', '/other/project/node_modules/pm2/lib/Daemon.js'] }).needed).toBe(true);
+ });
+
+ it('reloads when the pulled update bumped pm2 under a running daemon', () => {
+ expect(check({ pm2_version: '6.0.0' }).needed).toBe(true);
+ });
+
+ it('reloads when the daemon reports nothing usable', () => {
+ // Fails open: an unreadable daemon must not skip a reload it may need.
+ expect(daemonNeedsRefresh({ report: null, expectedEntry: OURS, expectedVersion: VERSION }).needed).toBe(true);
+ expect(check({ argv: [] }).needed).toBe(true);
+ });
+
+ it('treats a differently-spelled path to the same file as a match', () => {
+ const spelled = join(ROOT, 'node_modules', 'pm2', 'lib', '..', 'lib', 'Daemon.js');
+ expect(check({ argv: ['/usr/bin/node', spelled] }).needed).toBe(false);
+ });
+});
diff --git a/update.ps1 b/update.ps1
index 61119c11ad..861626a4fb 100644
--- a/update.ps1
+++ b/update.ps1
@@ -247,16 +247,11 @@ Write-SafeHost ""
# 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.
-# `pm2 update` then reloads the daemon in place from this checkout's node_modules,
-# refreshing its cached ProcessContainerFork.js path (a stale path from a daemon
-# originally launched by another project — e.g. a Yarn PnP zip cache — makes
-# future fork() calls crash with MODULE_NOT_FOUND) while leaving other projects'
-# apps running instead of killing them.
+# 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
$global:LASTEXITCODE = 0
-Invoke-Logged node ./node_modules/pm2/bin/pm2 update
-$global:LASTEXITCODE = 0
Step "pm2-stop" "done" "Apps stopped"
Write-SafeHost ""
@@ -357,6 +352,18 @@ Move-Item -Force "$RootDir\data\update-complete.json.tmp" "$RootDir\data\update-
# state doesn't make `start` a no-op, then `save` so the apps come back on
# reboot. Remove the completion marker if start fails so it isn't misread on boot.
Step "restart" "running" "Starting PortOS..."
+# `pm2 update` reloads the daemon in place, refreshing its cached
+# ProcessContainerFork.js path (a stale path from a daemon originally launched by
+# another project — e.g. a Yarn PnP zip cache — makes future fork() calls crash
+# with MODULE_NOT_FOUND). It also RESTARTS every co-located app on the shared
+# daemon, so run it only when the daemon isn't already the one this checkout's
+# node_modules would launch. The probe runs here, after npm install, so a pm2
+# version bump in the pulled update is part of the comparison.
+Invoke-Logged node scripts/pm2-daemon-refresh.js
+if ($LASTEXITCODE -eq 0) {
+ Invoke-Logged node ./node_modules/pm2/bin/pm2 update
+}
+$global:LASTEXITCODE = 0
Invoke-Logged node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent
$global:LASTEXITCODE = 0
Invoke-Logged node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs
diff --git a/update.sh b/update.sh
index c0c0df4c12..575a0642d5 100755
--- a/update.sh
+++ b/update.sh
@@ -174,14 +174,10 @@ log ""
# 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.
-# `pm2 update` then reloads the daemon in place from our local node_modules,
-# refreshing its cached ProcessContainerFork.js path (a stale path from a daemon
-# originally launched by another project — e.g. a Yarn PnP zip cache — makes all
-# subsequent fork() calls crash with MODULE_NOT_FOUND) while resurrecting other
-# projects' apps instead of killing them.
+# 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
-run node ./node_modules/pm2/bin/pm2 update || true
step "pm2-stop" "done" "Apps stopped"
log ""
@@ -333,6 +329,16 @@ TAG="$TAG" ROOT_DIR="$ROOT_DIR" node -e '
# state doesn't make `start` a no-op, then `save` so the apps come back on
# reboot. Remove the completion marker if start fails so it isn't misread on boot.
step "restart" "running" "Starting PortOS..."
+# `pm2 update` reloads the daemon in place, refreshing its cached
+# ProcessContainerFork.js path (a stale path from a daemon originally launched by
+# another project — e.g. a Yarn PnP zip cache — makes all subsequent fork() calls
+# crash with MODULE_NOT_FOUND). It also RESTARTS every co-located app on the
+# shared daemon, so run it only when the daemon isn't already the one this
+# checkout's node_modules would launch. The probe runs here, after npm install,
+# so a pm2 version bump in the pulled update is part of the comparison.
+if run node scripts/pm2-daemon-refresh.js; then
+ run node ./node_modules/pm2/bin/pm2 update || true
+fi
run node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || true
if ! run node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs; then
rm -f "$ROOT_DIR/data/update-complete.json"