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

address review: strip inherited node_args, fix the cap floor that inverted the policy, damp portos-ui restarts

[._.]/ Adam Eivy4e77fadf18c3
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 39cd28263d..004c4b8aa2 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -17,17 +17,15 @@ const BASE_ENV = {
// so a one-off shell override still works.
const fs = require('fs');
const envFile = path.join(__dirname, '.env');
+const readEnvValue = (content, key) => content.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? null;
let pgMode = 'docker';
let envServerMaxMemory = null;
let envUiMaxMemory = null;
try {
const envContent = fs.readFileSync(envFile, 'utf8');
- const modeMatch = envContent.match(/^PGMODE=(\w+)/m);
- if (modeMatch) pgMode = modeMatch[1];
- const memMatch = envContent.match(/^PORTOS_SERVER_MAX_MEMORY=(\S+)/m);
- if (memMatch) envServerMaxMemory = memMatch[1];
- const uiMemMatch = envContent.match(/^PORTOS_UI_MAX_MEMORY=(\S+)/m);
- if (uiMemMatch) envUiMaxMemory = uiMemMatch[1];
+ pgMode = readEnvValue(envContent, 'PGMODE') || pgMode;
+ envServerMaxMemory = readEnvValue(envContent, 'PORTOS_SERVER_MAX_MEMORY');
+ envUiMaxMemory = readEnvValue(envContent, 'PORTOS_UI_MAX_MEMORY');
} catch { /* no .env file — default to docker */ }
// pm2 restarts portos-server when its RSS crosses this — originally a memory-leak
@@ -59,7 +57,7 @@ const MEMORY_UNIT_MB = { K: 1 / 1024, M: 1, G: 1024 };
/**
* Parse a pm2 memory spec ('512M', '4G', '1024') to megabytes.
* pm2 itself defaults a bare number to bytes, but every spec here carries a unit
- * and an unrecognized one returns null so `heapCapArgs` degrades to "no cap"
+ * and an unrecognized one returns null so `memoryLimits` degrades to "no cap"
* rather than silently inventing a wrong one.
*/
function memorySpecToMB(spec) {
@@ -69,29 +67,41 @@ function memorySpecToMB(spec) {
}
/**
- * V8's old-space cap for a pm2 app, as `node_args`.
+ * Both memory bounds for a pm2 app: the RSS ceiling pm2 restarts at, and V8's
+ * old-space cap underneath it.
*
- * WHY: without an explicit cap, V8 sizes the heap limit from physical memory and
- * lands at ~4 GB on any workstation. That is at or above every ceiling below, so
- * the process reaches `max_memory_restart` and gets KILLED before V8 ever feels
- * enough pressure to run the full compacting GC that would have reclaimed the
- * garbage. Capping the heap under the pm2 ceiling inverts that race: V8 collects,
- * RSS settles, and the restart stays a genuine last resort instead of the normal
- * way memory is reclaimed — which matters because a restart drops in-flight SSE
- * streams and long jobs.
+ * WHY the cap: without an explicit one, V8 sizes the heap limit from physical
+ * memory and lands at ~4 GB on any workstation. That is at or above every ceiling
+ * below, so the process reaches `max_memory_restart` and gets KILLED before V8
+ * ever feels enough pressure to run the full compacting GC that would have
+ * reclaimed the garbage. Capping the heap under the pm2 ceiling inverts that
+ * race: V8 collects, RSS settles, and the restart stays a genuine last resort
+ * instead of the normal way memory is reclaimed — which matters because a restart
+ * drops in-flight SSE streams and long jobs.
*
- * 75% leaves room for the non-heap RSS (native buffers, sharp, the module code
- * itself) under the same ceiling.
+ * `ratio` is the gap left for the RSS that `--max-old-space-size` does NOT count:
+ * Buffers over 8 KB and ArrayBuffer backing stores are external, not old space.
+ * The default 0.75 suits a process whose bytes are mostly JS objects. Give a
+ * lower ratio to anything that moves large native buffers — portos-server runs
+ * sharp/libvips (a single 4096² RGBA `.raw().toBuffer()` is 64 MB) and decodes
+ * audio into Float32Arrays, so a heap sitting legally at its cap could still push
+ * RSS past the ceiling and get killed, i.e. the very race this exists to prevent.
*
* `node_args` rather than `NODE_OPTIONS` on purpose: NODE_OPTIONS is inherited by
* every child process, so it would also shrink the heap of the agent CLIs, build
* steps, and media tooling portos-server spawns. `node_args` applies to the
- * interpreter pm2 launches and stops there.
+ * interpreter pm2 launches and stops there. (pm2 also re-exports it into the
+ * app's own env, so `INHERITED_PM2_CONFIG_KEYS` in server/services/pm2.js strips
+ * it before PortOS shells out to `pm2 start` for a managed app.)
*/
-function heapCapArgs(restartSpec) {
+function memoryLimits(restartSpec, ratio = 0.75) {
const ceilingMB = memorySpecToMB(restartSpec);
- if (!ceilingMB) return [];
- return [`--max-old-space-size=${Math.max(256, Math.floor(ceilingMB * 0.75))}`];
+ return {
+ max_memory_restart: restartSpec,
+ // No floor: a floor could raise the cap to or above a small user-set ceiling
+ // and invert the whole policy. ratio < 1 keeps the cap strictly below it.
+ node_args: ceilingMB ? [`--max-old-space-size=${Math.floor(ceilingMB * ratio)}`] : []
+ };
}
const PORTS = {
@@ -169,8 +179,10 @@ module.exports = {
// and add `'**/data/**'` (plus `'**/node_modules'`, `'**/logs/**'`,
// `'**/.cache/**'`, `'**/portos-stepwise-*/**'`) to `ignore_watch`.
watch: false,
- max_memory_restart: SERVER_MAX_MEMORY,
- node_args: heapCapArgs(SERVER_MAX_MEMORY),
+ // 0.60, not the 0.75 default: sharp/libvips raw buffers and decoded audio
+ // are external memory the heap cap does not count, so portos-server needs a
+ // wider external margin under the same ceiling than a plain JS service.
+ ...memoryLimits(SERVER_MAX_MEMORY, 0.60),
// PM2's default kill_timeout (1600ms) is shorter than the server's own
// GRACEFUL_SHUTDOWN_TIMEOUT_MS (10s) force-exit in server/index.js, so if
// shutdown ever stalls, PM2 would SIGKILL the process before its graceful
@@ -210,8 +222,7 @@ module.exports = {
max_restarts: 5,
min_uptime: '30s',
restart_delay: 10000,
- max_memory_restart: COS_MAX_MEMORY,
- node_args: heapCapArgs(COS_MAX_MEMORY),
+ ...memoryLimits(COS_MAX_MEMORY),
// Important: This process manages long-running agent processes
// Keep kill_timeout high to allow graceful shutdown of agents
kill_timeout: 30000
@@ -220,6 +231,10 @@ module.exports = {
name: 'portos-ui',
script: path.join(__dirname, 'client', 'node_modules', 'vite', 'bin', 'vite.js'),
cwd: path.join(__dirname, 'client'),
+ // Explicit, unlike the inferred-from-.js default the other apps could rely
+ // on: this is the one script PortOS does not own, so pin the interpreter
+ // that node_args attach to rather than let a Vite release change it.
+ interpreter: 'node',
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
args: `--host 0.0.0.0 --port ${PORTS.UI}`,
@@ -229,13 +244,22 @@ module.exports = {
},
watch: false,
// Vite's dev server keeps a module graph, a transform cache, and per-client
- // HMR bookkeeping that all grow with session length, and it never releases
- // them on its own. With the default (physical-memory-derived) heap limit it
- // was measured at 2.7 GB after 18h. The heap cap makes V8 actually collect;
- // the ceiling restarts a dev server that still runs away. A restart here is
- // cheap — the browser reconnects and Vite re-warms its transform cache.
- max_memory_restart: UI_MAX_MEMORY,
- node_args: heapCapArgs(UI_MAX_MEMORY)
+ // HMR bookkeeping that all grow with session length and that it never
+ // releases on its own; with the default (physical-memory-derived) heap limit
+ // it was measured at 2.7 GB after 18h. The heap cap reaches the JS half of
+ // that — Vite 8 bundles through rolldown, whose own allocations are native
+ // and counted only by the RSS ceiling, so both bounds are load-bearing here.
+ //
+ // A restart is cheap (the browser reconnects, Vite re-warms its transform
+ // cache) but not free, and this is the one app that otherwise inherits pm2's
+ // `restart_delay: 0`. The damping below turns a mis-sized ceiling into slow
+ // churn instead of a tight crash loop; raise PORTOS_UI_MAX_MEMORY if a large
+ // client tree makes it fire during normal editing.
+ autorestart: true,
+ max_restarts: 10,
+ min_uptime: '60s',
+ restart_delay: 15000,
+ ...memoryLimits(UI_MAX_MEMORY)
},
{
name: 'portos-autofixer',
@@ -254,8 +278,7 @@ module.exports = {
max_restarts: 10,
min_uptime: '10s',
restart_delay: 5000,
- max_memory_restart: HELPER_MAX_MEMORY,
- node_args: heapCapArgs(HELPER_MAX_MEMORY)
+ ...memoryLimits(HELPER_MAX_MEMORY)
},
{
name: 'portos-autofixer-ui',
@@ -273,8 +296,7 @@ module.exports = {
max_restarts: 10,
min_uptime: '10s',
restart_delay: 5000,
- max_memory_restart: HELPER_MAX_MEMORY,
- node_args: heapCapArgs(HELPER_MAX_MEMORY)
+ ...memoryLimits(HELPER_MAX_MEMORY)
},
{
name: 'portos-browser',
@@ -296,8 +318,7 @@ module.exports = {
max_restarts: 10,
min_uptime: '10s',
restart_delay: 5000,
- max_memory_restart: HELPER_MAX_MEMORY,
- node_args: heapCapArgs(HELPER_MAX_MEMORY)
+ ...memoryLimits(HELPER_MAX_MEMORY)
}
]
};
diff --git a/server/lib/ecosystemMemory.test.js b/scripts/ecosystem-memory-bounds.test.js
similarity index 56%
rename from server/lib/ecosystemMemory.test.js
rename to scripts/ecosystem-memory-bounds.test.js
index 9c4b0927e7..dbe48a5908 100644
--- a/server/lib/ecosystemMemory.test.js
+++ b/scripts/ecosystem-memory-bounds.test.js
@@ -17,7 +17,7 @@ import path from 'path';
* uptime — the regression these assertions exist to prevent.
*/
const require = createRequire(import.meta.url);
-const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const { apps } = require(path.join(repoRoot, 'ecosystem.config.cjs'));
const UNIT_MB = { K: 1 / 1024, M: 1, G: 1024 };
@@ -31,21 +31,38 @@ const heapCapMB = (app) => {
return flag ? Number(flag.split('=')[1]) : null;
};
+const APP_CASES = apps.map((app) => [app.name, app]);
+
+// pm2 also manages python/go/docker/static apps, and `--max-old-space-size` is
+// meaningless for those — scope the heap-cap assertion to the Node-interpreted
+// entries so a future non-Node app doesn't force the guard to be deleted.
+const NODE_APP_CASES = APP_CASES.filter(([, app]) =>
+ app.interpreter === 'node' || (!app.interpreter && /\.[cm]?js$/i.test(app.script)));
+
describe('ecosystem.config.cjs memory bounds', () => {
- it.each(apps.map((app) => [app.name, app]))('%s declares a restart ceiling', (_name, app) => {
+ it('recognizes every app as Node-interpreted (update the filter if that changes)', () => {
+ expect(NODE_APP_CASES).toHaveLength(APP_CASES.length);
+ });
+
+ it.each(APP_CASES)('%s declares a restart ceiling', (_name, app) => {
expect(toMB(app.max_memory_restart)).toBeGreaterThan(0);
});
- it.each(apps.map((app) => [app.name, app]))('%s caps V8 below that ceiling', (_name, app) => {
+ it.each(NODE_APP_CASES)('%s caps V8 below a declared restart ceiling', (_name, app) => {
+ const ceiling = toMB(app.max_memory_restart);
const cap = heapCapMB(app);
expect(cap).toBeGreaterThan(0);
// Strictly below, so V8 collects first and pm2 restarts only as a last resort.
- expect(cap).toBeLessThan(toMB(app.max_memory_restart));
+ // This is also what a `Math.max(...)` floor on the cap would break: at a small
+ // user-set ceiling the floor could raise the cap to or past it.
+ expect(cap).toBeLessThan(ceiling);
});
- // A heap cap must never reach the child processes portos-server spawns (agent
- // CLIs, builds, media tooling) — NODE_OPTIONS is inherited, `node_args` is not.
- it.each(apps.map((app) => [app.name, app]))('%s sets the cap via node_args, not NODE_OPTIONS', (_name, app) => {
+ // A heap cap must never reach the child processes these apps spawn (agent CLIs,
+ // builds, media tooling) — NODE_OPTIONS is inherited by children, node_args is
+ // not. server/services/pm2.js additionally strips the `node_args` key pm2
+ // re-exports into the app's own environment.
+ it.each(NODE_APP_CASES)('%s sets the cap via node_args, not NODE_OPTIONS', (_name, app) => {
expect(app.env?.NODE_OPTIONS ?? '').not.toContain('max-old-space-size');
});
});
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index 3d0721fe4c..f56043d3b1 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -125,6 +125,12 @@ describe('llamaServerManager', () => {
vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')
.mockImplementation(async () => ({ reachable: pm2State?.status === 'online', models: [] }));
+ // `createDaemonWatcher` reads the saved boot list on every status read, and
+ // the dump is a real file on the developer's machine — pin it so these tests
+ // are about this code, not their PM2 state. (Its twin in
+ // mtplxServerManager.test.js pins it for the same reason.)
+ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue([]);
+
vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
execPm2Calls.push(args);
const action = args[0];
diff --git a/server/services/pm2.js b/server/services/pm2.js
index ca8e373a82..94d4db1ae8 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -53,8 +53,13 @@ function isJsScript(script) {
* fires regardless of `--no-autorestart`) killed the 25GB model process seconds
* after every successful load, forever. `exec_mode` and `watch` leak the same
* way — verified by starting a process with each key set in the environment.
+ *
+ * `node_args` joins them for the same reason: portos-server carries its own V8
+ * heap cap (ecosystem.config.cjs), and leaking that into a `pm2 start` would cap
+ * every app PortOS launches at portos-server's ceiling — including an app whose
+ * whole job is to hold more than that.
*/
-const INHERITED_PM2_CONFIG_KEYS = ['max_memory_restart', 'exec_mode', 'watch'];
+const INHERITED_PM2_CONFIG_KEYS = ['max_memory_restart', 'exec_mode', 'watch', 'node_args'];
/** Drop the PM2 config keys PM2 injected into our own environment. */
function withoutInheritedPm2Config(env) {
@@ -100,6 +105,18 @@ export function spawnPm2(pm2Args, opts = {}) {
/**
* Execute a PM2 CLI command and return stdout/stderr as a promise.
* Drop-in replacement for execAsync('pm2 ...') that bypasses pm2.cmd on Windows.
+ *
+ * TESTING — `vi.spyOn(pm2Module, 'execPm2')` is NOT enough on its own. It
+ * intercepts callers in OTHER modules (mtplxServerManager, llamaServerManager),
+ * but every export in THIS file that calls `execPm2`/`spawnPm2` reads the local
+ * binding and runs the real implementation regardless of the spy — silently, with
+ * the test still passing. `pm2.savedProcesses.test.js` relied on that and really
+ * ran `pm2 save`, and PM2 forked a God Daemon per test that outlived the suite:
+ * 641 orphans holding 38 GB accumulated on one dev machine before anyone noticed.
+ * A test that calls into this module must mock the spawn seam instead —
+ * `vi.mock('../lib/childProcess.js', … spawn: mockSpawn)`, as pm2.launch.test.js
+ * and pm2.savedProcesses.test.js do — and assert the mock was reached.
+ *
* @param {string[]} pm2Args PM2 CLI arguments (e.g. ['jlist'])
* @param {object} opts Spawn options (env, cwd, etc.)
* @returns {Promise<{stdout: string, stderr: string}>}
diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.js
index cfa3f9aa76..3247f92ff7 100644
--- a/server/services/pm2.launch.test.js
+++ b/server/services/pm2.launch.test.js
@@ -83,6 +83,9 @@ describe('PM2 command launch interpreters', () => {
vi.stubEnv('max_memory_restart', '4294967296');
vi.stubEnv('exec_mode', 'cluster_mode');
vi.stubEnv('watch', 'true');
+ // portos-server carries its own V8 heap cap; inherited, it would cap every
+ // app PortOS launches — including one whose job is to hold more than that.
+ vi.stubEnv('node_args', '--max-old-space-size=3072');
await execPm2(['start', '/usr/local/bin/llama-server', '--name', 'portos-llama-server']);
@@ -90,6 +93,7 @@ describe('PM2 command launch interpreters', () => {
expect(spawnOpts.env).not.toHaveProperty('max_memory_restart');
expect(spawnOpts.env).not.toHaveProperty('exec_mode');
expect(spawnOpts.env).not.toHaveProperty('watch');
+ expect(spawnOpts.env).not.toHaveProperty('node_args');
expect(spawnOpts.env.PATH).toBe(process.env.PATH);
});
diff --git a/server/services/pm2.savedProcesses.test.js b/server/services/pm2.savedProcesses.test.js
index 930c443a02..319ca39ff8 100644
--- a/server/services/pm2.savedProcesses.test.js
+++ b/server/services/pm2.savedProcesses.test.js
@@ -105,10 +105,7 @@ describe('saveProcessList exclusions', () => {
const seedDump = (names) =>
writeFile(join(home, 'dump.pm2'), JSON.stringify(names.map((name) => ({ name, script: `/bin/${name}` }))));
- // Regression guard for the daemon leak described at the top of this file. If a
- // future refactor moves `pm2 save` off the mocked `spawn` seam, this assertion
- // fails loudly here instead of quietly forking a real PM2 God Daemon per test
- // that survives the run forever.
+ // Regression guard for the daemon leak described at the top of this file.
it('runs `pm2 save` through the stubbed spawn seam, never a real subprocess', async () => {
await seedDump(['portos-server']);