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
refactor: route PM2 jlist reads through one strict parser (#8164)
[._.]/ Adam Eivy06ce6410fe60
diff --git a/autofixer/server.js b/autofixer/server.jsindex ff64fdb67f..6b32bb3957 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -20,7 +20,7 @@ import {revertDiffFromLive,runVerifyCommand,} from './sandbox.js';-import { execPm2, DATA_DIR, AUTOFIXER_DIR, INDEX_FILE, loadApps } from './shared.js';+import { execPm2, listProcessesStrict, DATA_DIR, AUTOFIXER_DIR, INDEX_FILE, loadApps } from './shared.js';// Prepend the guarded pm2 shim to this process's PATH as defense-in-depth. The// fix agent runs in an isolated worktree with a sanitized env and (for claude)@@ -157,21 +157,6 @@ async function saveSession(sessionId, prompt, output, metadata, patch) {await saveIndex(index);}-// Get PM2 process list-async function getProcessList() {- const { stdout } = await execPm2(['jlist']);- const stripped = stdout.replace(/\x1b\[[0-9;]*m/g, '');- const jsonStart = stripped.indexOf('[{');- const jsonEnd = stripped.lastIndexOf('}]');-- if (jsonStart < 0 || jsonEnd < 0) {- console.error(`❌ [Autofixer] Invalid pm2 jlist output`);- return [];- }-- return JSON.parse(stripped.substring(jsonStart, jsonEnd + 2));-}-// Get error logs for a processasync function getProcessLogs(processName) {const { stdout: errLogs } = await execPm2(['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => ({ stdout: '' }));@@ -403,7 +388,17 @@ async function checkAndFixProcesses() {console.log(`📋 [Autofixer] Monitoring ${monitoredProcesses.length} process(es): ${monitoredProcesses.join(', ')}`);- const pm2List = await getProcessList();+ // `listProcessesStrict()` returns `null` when the read itself FAILED (vs `[]`+ // for a successful read with no processes) — the absent-vs-empty contract+ // from issue #968, now shared with `server/services/pm2.js` (#8164). A+ // failed read must not be reported as "no PM2 processes found": that would+ // silently skip repair on the exact cycle a crashed process most needs it.+ const pm2List = await listProcessesStrict();++ if (pm2List === null) {+ console.error(`❌ [Autofixer] PM2 process read failed — skipping this check cycle`);+ return;+ }if (pm2List.length === 0) {console.log(`⚠️ [Autofixer] No PM2 processes found`);diff --git a/autofixer/shared.js b/autofixer/shared.jsindex d38aed4b3e..52309ed303 100644--- a/autofixer/shared.js+++ b/autofixer/shared.js@@ -3,13 +3,15 @@// dependency-light (node builtins only): PortOS's own `server/services/pm2.js`// has an equivalent `execPm2`, but importing it here would drag the whole// server dependency graph into a package whose package.json declares only-// express.+// express. `server/lib/pm2Jlist.js` is the one exception: a pure, zero-import+// leaf, so importing it costs nothing this package needs to stay light about.import { spawn } from 'child_process';import { existsSync } from 'fs';import { readFile } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { createRequire } from 'module';+import { parsePm2JlistStdout } from '../server/lib/pm2Jlist.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -42,6 +44,23 @@ export function execPm2(pm2Args) {});}+/**+ * Strict PM2 process list: the one non-test reader both `server.js` and+ * `ui.js` share, so a failed read never masquerades as zero processes.+ *+ * `null` = the read FAILED (spawn/exit failure, or stdout with no real array+ * literal — see `parsePm2JlistStdout`); an array (incl. `[]`) = a successful+ * read. Callers must not collapse `null` into `[]`: the repair daemon skips+ * its cycle instead of reporting "no PM2 processes found", and the dashboard+ * API answers 503 instead of an empty list (issue #8164).+ *+ * @returns {Promise<Array|null>}+ */+export async function listProcessesStrict() {+ const { stdout } = await execPm2(['jlist']).catch(() => ({ stdout: '' }));+ return parsePm2JlistStdout(stdout);+}+// Paths. Resolved from THIS module's location (both consumers are siblings in// `autofixer/`), so every process agrees on one `data/` directory.export const DATA_DIR = join(__dirname, '../data');diff --git a/autofixer/shared.test.js b/autofixer/shared.test.jsindex 31e16eaa3d..babf741b24 100644--- a/autofixer/shared.test.js+++ b/autofixer/shared.test.js@@ -1,5 +1,6 @@import { describe, it, expect, beforeEach, vi } from 'vitest';import { existsSync } from 'fs';+import { EventEmitter } from 'events';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { createRequire } from 'module';@@ -12,6 +13,15 @@ vi.mock('fs/promises', async (importOriginal) => ({readFile: (...args) => readFileMock(...args),}));+// listProcessesStrict() tests fake the PM2 CLI's spawned child process so they+// don't depend on a real `pm2` daemon; every other test in this file leaves+// spawn unmocked (real execPm2 calls, or short-circuits before spawning).+const spawnMock = vi.hoisted(() => vi.fn());+vi.mock('child_process', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, spawn: (...args) => spawnMock(...args) };+});+// execPm2's missing-binary guard is tested by faking existsSync rather than// actually deleting PM2_BIN, which would break every other test in this file.const existsSyncMock = vi.hoisted(() => vi.fn());@@ -106,3 +116,49 @@ describeShared('autofixer/shared — loadApps', () => {]);});});++// `listProcessesStrict()` (issue #8164) is the one strict reader `server.js`+// (the repair daemon) and `ui.js` (the dashboard API) both call — a failed+// PM2 read must resolve `null`, never `[]`, or a crashed monitored process+// silently stops getting auto-repaired and the dashboard reports a clean+// empty process list instead of "unavailable".+function fakeChild({ stdout = '', code = 0 } = {}) {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ queueMicrotask(() => {+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));+ child.emit('close', code);+ });+ return child;+}++describeShared('autofixer/shared — listProcessesStrict', () => {+ beforeEach(() => {+ spawnMock.mockReset();+ });++ it('resolves a populated process array on a successful read', async () => {+ spawnMock.mockReturnValue(fakeChild({+ stdout: JSON.stringify([{ name: 'svc-a', pm2_env: { status: 'online' } }])+ }));+ await expect(shared.listProcessesStrict()).resolves.toEqual([+ { name: 'svc-a', pm2_env: { status: 'online' } }+ ]);+ });++ it('resolves [] for a genuine empty read (not "unavailable")', async () => {+ spawnMock.mockReturnValue(fakeChild({ stdout: '[]' }));+ await expect(shared.listProcessesStrict()).resolves.toEqual([]);+ });++ it('resolves null (not []) when the PM2 CLI exits non-zero', async () => {+ spawnMock.mockReturnValue(fakeChild({ stdout: '', code: 1 }));+ await expect(shared.listProcessesStrict()).resolves.toBeNull();+ });++ it('resolves null (not []) for exit-0 stdout with no real array literal', async () => {+ spawnMock.mockReturnValue(fakeChild({ stdout: 'pm2 daemon not running', code: 0 }));+ await expect(shared.listProcessesStrict()).resolves.toBeNull();+ });+});diff --git a/autofixer/ui.js b/autofixer/ui.jsindex 2ec8bd8ac3..542f9cba30 100644--- a/autofixer/ui.js+++ b/autofixer/ui.js@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url';import { createTailscaleServers, watchCertReload } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';import { createSidecarAuthGate } from '../lib/sidecarAuthGate.js';-import { PM2_BIN, execPm2, DATA_DIR, INDEX_FILE, loadApps } from './shared.js';+import { PM2_BIN, execPm2, listProcessesStrict, DATA_DIR, INDEX_FILE, loadApps } from './shared.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -60,17 +60,20 @@ app.get('/api/history', async (req, res) => {});// API: Get PM2 status+//+// `listProcessesStrict()` returns `null` when the read itself FAILED (vs `[]`+// for a successful read with no processes) — the absent-vs-empty contract+// from issue #968, shared with `server/services/pm2.js` (#8164). A failed+// read answers 503 rather than an empty array, so the dashboard doesn't+// render "no processes" when PM2 was simply unreachable; the client handles+// this status without breaking on `.forEach`.app.get('/api/status', async (req, res) => {- const { stdout } = await execPm2(['jlist']).catch(() => ({ stdout: '[]' }));- const stripped = stdout.replace(/\x1b\[[0-9;]*m/g, '');- const jsonStart = stripped.indexOf('[');- const jsonEnd = stripped.lastIndexOf(']');+ const processes = await listProcessesStrict();- if (jsonStart < 0 || jsonEnd < 0) {- return res.json([]);+ if (processes === null) {+ return res.status(503).json({ error: 'PM2 process read failed', code: 'PM2_UNAVAILABLE' });}- const processes = JSON.parse(stripped.substring(jsonStart, jsonEnd + 1));res.json(processes.map(p => ({name: p.name,status: p.pm2_env?.status,diff --git a/autofixer/ui.template.html b/autofixer/ui.template.htmlindex 2a2347ee15..f0215e31f1 100644--- a/autofixer/ui.template.html+++ b/autofixer/ui.template.html@@ -678,13 +678,20 @@showLogin('Signed out.');});- // Fetch PM2 status+ // Fetch PM2 status. A failed PM2 read answers 503 with an error object,+ // not an array (issue #8164) — treat that as "unavailable", never clear+ // every process to unknown/offline by iterating a non-array with forEach.async function fetchStatus() {const res = await apiFetch('/api/status');if (!res) return;- const statuses = await res.json();+ const body = await res.json();+ if (!res.ok || !Array.isArray(body)) {+ processStatuses = null;+ updateProcessList();+ return;+ }processStatuses = new Map();- statuses.forEach(s => { processStatuses.set(String(s.name ?? ''), s.status); });+ body.forEach(s => { processStatuses.set(String(s.name ?? ''), s.status); });updateProcessList();}@@ -720,7 +727,9 @@nameEl.className = 'process-name';const statusEl = document.createElement('span');- const statusClass = processStatusClasses.get(processStatuses.get(name)) || 'status-unknown';+ // `processStatuses === null` means the last PM2 read failed (503) —+ // render every process unknown rather than throwing on a missing Map.+ const statusClass = processStatusClasses.get(processStatuses?.get(name)) || 'status-unknown';statusEl.classList.add('process-status', statusClass);nameEl.append(statusEl, document.createTextNode(name));diff --git a/server/lib/README.md b/server/lib/README.mdindex ab06421525..f010ae9665 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -331,6 +331,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. || `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. || `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |+| `pm2Jlist.js` | Sole owner of the strict `pm2 jlist` stdout parser: `parsePm2JlistStdout(stdout)` returns the parsed process array (incl. `[]` for a genuine empty read) or `null` when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so `autofixer/shared.js` can use it without the server dependency graph. `services/pm2.js` re-exports it as `parseJlistStdout` for compatibility; `services/pm2.js#listProcessesStrict` and `autofixer/shared.js` are the only non-test callers permitted to execute raw `pm2 jlist`. || `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. || `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). || `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex fc9e019ae2..b47734f21c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -294,6 +294,7 @@ export * from './forgeIssueCli.js';export * from './forgeIssueState.js';export * from './portosEnv.js';export * from './portosRootPlaceholder.js';+export * from './pm2Jlist.js';export * from './homePath.js';export * from './jsonIo.js';export * from './settingsStore.js';diff --git a/server/lib/pm2Jlist.js b/server/lib/pm2Jlist.jsnew file mode 100644index 0000000000..bad10866eb--- /dev/null+++ b/server/lib/pm2Jlist.js@@ -0,0 +1,53 @@+/**+ * Sole owner of the strict `pm2 jlist` stdout parser (issue #8164, consolidating+ * #968, #2991, #5732).+ *+ * `pm2 jlist` always emits a JSON array (`[]` when there are no processes), so+ * an exit-0 read with empty or garbage stdout — no array literal at all — is a+ * FAILED read, not a successful "no processes." Returning `[]` there would+ * reintroduce the absent-vs-empty footgun (AGENTS.md "Sentinel + validate"):+ * a transient PM2 read failure would masquerade as a confident empty process+ * list. Detect a real array literal (tolerating ANSI/log noise before it, e.g.+ * `\x1b[2K`) before trusting the stdout, and return `null` otherwise.+ *+ * Kept dependency-free (no imports) so a package-local consumer that+ * deliberately avoids the server dependency graph — `autofixer/shared.js` — can+ * import this one leaf without dragging anything else in.+ */++/**+ * Locate and slice the JSON array literal out of raw pm2 jlist stdout.+ * Mirrors the detection `parsePm2JlistStdout` already performed to decide a+ * literal is present: '[{' (an array of objects) wins over a bare '[]' when+ * both appear, and a `[31m`-style ANSI code never matches the empty-array regex.+ *+ * @param {string} stdout+ * @returns {string} The JSON array text, or '[]' if no literal was found.+ */+function extractJsonArrayText(stdout) {+ const objectStart = stdout.indexOf('[{');+ if (objectStart >= 0) return stdout.slice(objectStart);+ const emptyMatch = stdout.match(/\[\](?![0-9])/);+ if (emptyMatch) return stdout.slice(stdout.indexOf(emptyMatch[0]));+ return '[]';+}++/**+ * Parse the stdout of a `pm2 jlist` invocation into a raw process array, or+ * `null` when the read effectively failed.+ *+ * @param {string} stdout Raw `pm2 jlist` stdout (may carry ANSI noise).+ * @returns {Array|null} The parsed process array (incl. `[]`), or `null` on failure.+ */+export function parsePm2JlistStdout(stdout) {+ const hasArrayLiteral = typeof stdout === 'string' && (stdout.includes('[{') || /\[\](?![0-9])/.test(stdout));+ if (!hasArrayLiteral) return null;++ let parsed;+ try {+ parsed = JSON.parse(extractJsonArrayText(stdout));+ } catch {+ return null;+ }+ return Array.isArray(parsed) ? parsed : null;+}diff --git a/server/pm2JlistOwnership.guard.test.js b/server/pm2JlistOwnership.guard.test.jsnew file mode 100644index 0000000000..144f9b347f--- /dev/null+++ b/server/pm2JlistOwnership.guard.test.js@@ -0,0 +1,89 @@+/**+ * Tree-wide guard: only the two designated readers may execute raw+ * `pm2 jlist` (issue #8164, consolidating #968, #2991, #5732).+ *+ * ## The bug class+ *+ * `pm2 jlist` always emits a JSON array (`[]` for no processes), so an exit-0+ * read with empty/garbage stdout is a FAILED read, not "no processes" — and a+ * caller that re-implements its own extraction/parsing tends to get that+ * absent-vs-empty distinction wrong, collapsing a transient PM2 outage into a+ * confident "nothing running." Before this issue, six call sites each ran and+ * parsed `pm2 jlist` independently (`cosHealthMonitor.js`, `streamingDetect.js`,+ * `routes/detect.js`, `browserService.js`, `autofixer/server.js`,+ * `autofixer/ui.js`), and three prior issues (#968, #2991, #5732) each fixed+ * the contract in one owner without closing the door on a new copy appearing+ * elsewhere.+ *+ * ## The rule+ *+ * Exactly two non-test modules may spawn PM2 with a literal `['jlist']` (or+ * `["jlist"]`) argument array: `server/services/pm2.js` (`fetchJlist` →+ * `listProcessesStrict`/`listProcesses`, the mapped-shape reader every other+ * server-side caller should use) and `autofixer/shared.js`+ * (`listProcessesStrict`, package-local because the autofixer deliberately+ * avoids the server dependency graph — see the comment at the top of that+ * file). Both compose the shared, dependency-free parser at+ * `server/lib/pm2Jlist.js#parsePm2JlistStdout`. A new caller must import one of+ * those readers, not re-run `pm2 jlist` itself.+ *+ * This is a narrow, call-shape-specific scan (`(['jlist'` / `(["jlist"`), not a+ * substring match on the word "jlist" — that word appears legitimately in+ * comments, cache-key constants (`clearJlistCache`, `JLIST_TTL_MS`), and an+ * autonomous-job shell-command description elsewhere in the tree.+ */+import { describe, expect, it } from 'vitest';+import { execFileSync } from 'child_process';+import { readFileSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';++const SERVER_ROOT = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = dirname(SERVER_ROOT);+const PROCESS_ROOTS = ['server/', 'autofixer/'];++// The only two files permitted to spawn PM2 with a literal `['jlist']`/`["jlist"]`+// argument array.+const ALLOWED_OWNERS = new Set([+ 'server/services/pm2.js',+ 'autofixer/shared.js',+]);++const RAW_JLIST_CALL = /\(\s*\[\s*['"]jlist['"]/;++const trackedSources = () => execFileSync('git', ['ls-files', '*.js', '*.mjs', '*.cjs'], {+ cwd: REPO_ROOT,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+}).split('\n').filter((f) => f && PROCESS_ROOTS.some((root) => f.startsWith(root)) && !f.includes('.test.'));++describe('pm2 jlist ownership guard (#8164)', () => {+ it('scans both long-running Node process trees', () => {+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise+ // let the assertion below pass by scanning nothing at all.+ const sources = trackedSources();+ expect(sources.length).toBeGreaterThan(200);+ expect(PROCESS_ROOTS.every((root) => sources.some((file) => file.startsWith(root)))).toBe(true);+ });++ it('recognizes the two allowed owners actually spawn a literal jlist call', () => {+ // Proves the regex still matches real call sites — without this the scan+ // below could go vacuously green if the call shape ever changed.+ for (const owner of ALLOWED_OWNERS) {+ const src = readFileSync(join(REPO_ROOT, owner), 'utf8');+ expect(RAW_JLIST_CALL.test(src)).toBe(true);+ }+ });++ it('finds no raw `pm2 jlist` execution outside the two designated readers', () => {+ const offenders = [];+ for (const file of trackedSources()) {+ if (ALLOWED_OWNERS.has(file)) continue;+ const src = readFileSync(join(REPO_ROOT, file), 'utf8');+ if (RAW_JLIST_CALL.test(src)) {+ offenders.push(file);+ }+ }+ expect(offenders).toEqual([]);+ });+});diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 9f130cc95d..2b5cfd8376 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -4,7 +4,7 @@ import { readFile, stat } from 'fs/promises';import { join, resolve } from 'path';import { exec } from '../lib/childProcess.js';import { promisify } from 'util';-import { execPm2 } from '../services/pm2.js';+import { listProcessesStrict } from '../services/pm2.js';import { detectAppWithAi } from '../services/aiDetect.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';@@ -239,8 +239,16 @@ router.post('/pm2', asyncHandler(async (req, res) => {throw new ServerError('Process name is required', { status: 400, code: 'MISSING_NAME' });}- const { stdout } = await execPm2(['jlist']).catch(() => ({ stdout: '[]' }));- const processes = safeJSONParse(stdout, []);+ // `listProcessesStrict()` returns `null` when the PM2 read itself FAILED (vs+ // `[]` for a successful read with no processes) — the absent-vs-empty+ // contract from issue #968, now the one non-test owner of raw `pm2 jlist`+ // execution/parsing alongside `autofixer/shared.js` (#8164). `exists: false`+ // is reserved for a successful empty/no-match read; a failed read is a 503,+ // never a confident "process not found."+ const processes = await listProcessesStrict();+ if (processes === null) {+ throw new ServerError('PM2 process read failed', { status: 503, code: 'PM2_UNAVAILABLE' });+ }const found = processes.find(p => p.name === name);res.json({@@ -248,7 +256,7 @@ router.post('/pm2', asyncHandler(async (req, res) => {exists: !!found,process: found ? {name: found.name,- status: found.pm2_env?.status,+ status: found.status,pid: found.pid,pm_id: found.pm_id} : nulldiff --git a/server/routes/detect.test.js b/server/routes/detect.test.jsindex f0b22fce75..c6548c476d 100644--- a/server/routes/detect.test.js+++ b/server/routes/detect.test.js@@ -10,7 +10,14 @@ vi.mock('../services/aiDetect.js', () => ({detectAppWithAi: vi.fn()}));+// `listProcessesStrict` returns `null` on a FAILED PM2 read (distinct from a+// successful `[]` empty read) — the absent-vs-empty contract from issue #968.+vi.mock('../services/pm2.js', () => ({+ listProcessesStrict: vi.fn()+}));+import { detectAppWithAi } from '../services/aiDetect.js';+import { listProcessesStrict } from '../services/pm2.js';describe('Detect Routes', () => {let app;@@ -47,6 +54,59 @@ describe('Detect Routes', () => {});});+describe('POST /api/detect/pm2', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/detect', detectRoutes);+ app.use(errorMiddleware);+ vi.clearAllMocks();+ });++ it('reports exists:false only for a successful read with no matching process', async () => {+ listProcessesStrict.mockResolvedValue([{ name: 'other-app', status: 'online', pid: 123, pm_id: 0 }]);++ const response = await request(app)+ .post('/api/detect/pm2')+ .send({ name: 'example-app' });++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ name: 'example-app', exists: false, process: null });+ });++ it('reports the matched process status/pid from the mapped shape', async () => {+ listProcessesStrict.mockResolvedValue([{ name: 'example-app', status: 'online', pid: 123, pm_id: 0 }]);++ const response = await request(app)+ .post('/api/detect/pm2')+ .send({ name: 'example-app' });++ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ name: 'example-app',+ exists: true,+ process: { name: 'example-app', status: 'online', pid: 123, pm_id: 0 }+ });+ });++ // Issue #8164: a FAILED PM2 read must not be reported as exists:false —+ // that would tell a caller the process is confidently absent when its+ // status is actually unavailable.+ it('returns a 503 instead of exists:false when the PM2 read fails', async () => {+ listProcessesStrict.mockResolvedValue(null);++ const response = await request(app)+ .post('/api/detect/pm2')+ .send({ name: 'example-app' });++ expect(response.status).toBe(503);+ expect(response.body).toMatchObject({ code: 'PM2_UNAVAILABLE' });+ expect(response.body).not.toHaveProperty('exists');+ });+});+// A directory that exists on the host but sits OUTSIDE DEFAULT_WORKSPACE_ROOTS,// so the only thing that can admit it is PORTOS_WORKSPACE_ROOTS. Deliberately not// a mkdtemp() directory: `tmpdir()` is itself a default root on Linux (/tmp) anddiff --git a/server/services/browserService.js b/server/services/browserService.jsindex 9f4caee6b3..f28222b4eb 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -11,7 +11,7 @@ import { ensureDir, safeJSONParse, PATHS, tryReadFile, atomicWrite, sleep } fromimport { normalizeBrowserConfig } from '../lib/browserConfig.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { readResponseJson } from '../lib/readResponseJson.js';-import { execPm2 } from './pm2.js';+import { execPm2, listProcessesStrict } from './pm2.js';const PM2_SETTLE_MS = 1500;const HEALTH_TIMEOUT_MS = 3000;@@ -153,8 +153,19 @@ export async function restartBrowser() {// ---------- PM2 status (process-level) ----------export async function getProcessStatus() {- const { stdout } = await execPm2(['jlist']);- const processes = safeJSONParse(stdout, [], { allowArray: true });+ // `listProcessesStrict()` returns `null` when the PM2 read itself FAILED (vs+ // `[]` for a successful read with no processes) — the absent-vs-empty+ // contract from issue #968, now the one non-test owner of raw `pm2 jlist`+ // execution/parsing alongside `autofixer/shared.js` (#8164).+ const processes = await listProcessesStrict();++ if (processes === null) {+ // A failed read must never report `exists: false` — that claims the+ // browser process is confidently absent when its status is actually+ // unavailable (a transient PM2 blip should not read as "not installed").+ return { exists: null, status: 'unavailable', pm2_id: null };+ }+const browserProc = processes.find(p => p.name === 'portos-browser');if (!browserProc) {@@ -163,14 +174,14 @@ export async function getProcessStatus() {return {exists: true,- status: browserProc.pm2_env?.status || 'unknown',+ status: browserProc.status || 'unknown',pm2_id: browserProc.pm_id,pid: browserProc.pid,- memory: browserProc.monit?.memory || 0,- cpu: browserProc.monit?.cpu || 0,- uptime: browserProc.pm2_env?.pm_uptime || null,- restarts: browserProc.pm2_env?.restart_time || 0,- unstableRestarts: browserProc.pm2_env?.unstable_restarts || 0+ memory: browserProc.memory || 0,+ cpu: browserProc.cpu || 0,+ uptime: browserProc.uptime || null,+ restarts: browserProc.restarts || 0,+ unstableRestarts: browserProc.unstableRestarts || 0};}diff --git a/server/services/browserService.test.js b/server/services/browserService.test.jsindex 4cb1e8ac70..faadf6d9ec 100644--- a/server/services/browserService.test.js+++ b/server/services/browserService.test.js@@ -101,6 +101,64 @@ describe('browserService config persistence', () => {});});+// Issue #8164: the strict, mapped-shape reader (`listProcessesStrict`)+// replaces a private `execPm2(['jlist'])` parse here — `null` (a FAILED read)+// must not collapse into the same `exists: false` a genuinely absent process+// reports.+describe('getProcessStatus (PM2 read — absent-vs-empty contract)', () => {+ beforeEach(() => {+ vi.resetModules();+ });++ afterEach(() => {+ vi.doUnmock('./pm2.js');+ });++ async function importServiceWithPm2(listProcessesStrictImpl) {+ vi.doMock('./pm2.js', () => ({+ execPm2: vi.fn(),+ listProcessesStrict: vi.fn(listProcessesStrictImpl)+ }));+ return import('./browserService.js');+ }++ it('reports the matched process from the mapped shape', async () => {+ const service = await importServiceWithPm2(async () => [+ { name: 'portos-browser', status: 'online', pm_id: 1, pid: 456, memory: 1024, cpu: 2, uptime: 9999, restarts: 0, unstableRestarts: 0 }+ ]);++ const status = await service.getProcessStatus();++ expect(status).toEqual({+ exists: true,+ status: 'online',+ pm2_id: 1,+ pid: 456,+ memory: 1024,+ cpu: 2,+ uptime: 9999,+ restarts: 0,+ unstableRestarts: 0+ });+ });++ it('reports not_found for a successful read with no matching process', async () => {+ const service = await importServiceWithPm2(async () => []);++ const status = await service.getProcessStatus();++ expect(status).toEqual({ exists: false, status: 'not_found', pm2_id: null });+ });++ it('reports unavailable, never exists:false, when the PM2 read fails', async () => {+ const service = await importServiceWithPm2(async () => null);++ const status = await service.getProcessStatus();++ expect(status).toEqual({ exists: null, status: 'unavailable', pm2_id: null });+ });+});+describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {// Pure helper: no data-root proxy needed, import the real module directly.let pickMainFrameHops;diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex 8eb5c7b6e9..ccbd9681f6 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -6,8 +6,7 @@* snapshot to CoS state, and emits health events for downstream consumers.*/-import { execPm2 } from './pm2.js';-import { safeJSONParse } from '../lib/fileUtils.js';+import { execPm2, listProcessesStrict } from './pm2.js';import { getMemoryStats } from '../lib/memoryStats.js';import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';@@ -29,83 +28,87 @@ export async function runHealthCheck() {ports: null};- // Check PM2 processes- const pm2Result = await execPm2(['jlist']).catch(() => ({ stdout: '[]' }));- // pm2 jlist may output ANSI codes and warnings before JSON, extract the JSON array- // Look for '[{' (array with objects) or '[]' (empty array) to avoid matching ANSI codes like [31m- const pm2Output = pm2Result.stdout || '[]';- let jsonStart = pm2Output.indexOf('[{');- if (jsonStart < 0) {- // Check for empty array - find '[]' that's not part of ANSI codes- const emptyMatch = pm2Output.match(/\[\](?![0-9])/);- jsonStart = emptyMatch ? pm2Output.indexOf(emptyMatch[0]) : -1;- }- const pm2Json = jsonStart >= 0 ? pm2Output.slice(jsonStart) : '[]';- const pm2Processes = safeJSONParse(pm2Json, [], { logError: true, context: 'pm2 process list' });-- // A process whose stopping is a normal outcome (a desktop app the user closed)- // must not be auto-restarted — that would reopen the window they just closed,- // the same relaunch loop `autorestart: false` prevents, arriving by another- // path. See issue #2991.- const annotated = await annotateExpectedExit(pm2Processes);- const supervised = annotated.filter(p => !p.expectedExit);-- const erroredProcesses = supervised.filter(p => p.pm2_env?.status === 'errored');- // Reported on its own rather than folded into `errored` (which would degrade- // health for a normal user action) or dropped from the totals. Counted from- // the expected-exit processes only, so it never overlaps `errored`/`stopped`- // below — those now count supervised processes exclusively.- const desktopExited = annotated.filter(- p => p.expectedExit && ['errored', 'stopped'].includes(p.pm2_env?.status)- ).length;- // `online` counts EVERY process, exempt or not: the exemption is about exit- // semantics, not liveness, so a running desktop app must still report as online- // (otherwise it lands in `total` and in no bucket, and the metric reads the same- // whether the game is running or quit).- metrics.pm2 = {- total: pm2Processes.length,- online: annotated.filter(p => p.pm2_env?.status === 'online').length,- errored: erroredProcesses.length,- stopped: supervised.filter(p => p.pm2_env?.status === 'stopped').length,- desktopExited- };+ // Check PM2 processes. `listProcessesStrict()` returns `null` when the read+ // itself FAILED (vs `[]` for a successful read with no processes) — the+ // absent-vs-empty contract from issue #968, now the one non-test owner of raw+ // `pm2 jlist` execution/parsing alongside `autofixer/shared.js` (#8164). A+ // failed read must not be recorded as zero processes: that would suppress+ // repair (no errored processes found) and misreport health as clean.+ const pm2Processes = await listProcessesStrict();- // Check for runaway processes (too many)- if (pm2Processes.length > state.config.maxTotalProcesses) {+ if (pm2Processes === null) {+ metrics.pm2 = null;issues.push({- type: 'warning',+ type: 'error',category: 'processes',- message: `High process count: ${pm2Processes.length} PM2 processes (limit: ${state.config.maxTotalProcesses})`+ message: 'PM2 process read failed — process health is unavailable, not necessarily clean'});- }-- // Check for errored processes and auto-restart them- if (erroredProcesses.length > 0) {- const names = erroredProcesses.map(p => p.name);- emitLog('warn', `🔄 ${names.length} errored PM2 process(es) detected: ${names.join(', ')} — attempting restart`);-- const restartResults = await Promise.all(names.map(async (name) => {- // execPm2, not execFileAsync('pm2', …, { shell: true }) — `shell: true`- // resolves `pm2` to pm2.cmd and rebuilds the cmd.exe → pm2.cmd → node- // chain that v1.6.7 removed, flashing a console window on every restart.- const result = await execPm2(['restart', name]).catch(e => ({ stdout: '', stderr: e.message }));- const failed = result.stderr && !result.stdout;- if (failed) {- emitLog('error', `❌ Failed to restart ${name}: ${result.stderr}`);- } else {- emitLog('success', `✅ Auto-restarted errored process: ${name}`);- }- return { name, success: !failed };- }));-- const failedRestarts = restartResults.filter(r => !r.success);- if (failedRestarts.length > 0) {+ } else {+ // A process whose stopping is a normal outcome (a desktop app the user+ // closed) must not be auto-restarted — that would reopen the window they+ // just closed, the same relaunch loop `autorestart: false` prevents,+ // arriving by another path. See issue #2991.+ const annotated = await annotateExpectedExit(pm2Processes);+ const supervised = annotated.filter(p => !p.expectedExit);++ const erroredProcesses = supervised.filter(p => p.status === 'errored');+ // Reported on its own rather than folded into `errored` (which would+ // degrade health for a normal user action) or dropped from the totals.+ // Counted from the expected-exit processes only, so it never overlaps+ // `errored`/`stopped` below — those now count supervised processes+ // exclusively.+ const desktopExited = annotated.filter(+ p => p.expectedExit && ['errored', 'stopped'].includes(p.status)+ ).length;+ // `online` counts EVERY process, exempt or not: the exemption is about+ // exit semantics, not liveness, so a running desktop app must still report+ // as online (otherwise it lands in `total` and in no bucket, and the+ // metric reads the same whether the game is running or quit).+ metrics.pm2 = {+ total: pm2Processes.length,+ online: annotated.filter(p => p.status === 'online').length,+ errored: erroredProcesses.length,+ stopped: supervised.filter(p => p.status === 'stopped').length,+ desktopExited+ };++ // Check for runaway processes (too many)+ if (pm2Processes.length > state.config.maxTotalProcesses) {issues.push({- type: 'error',+ type: 'warning',category: 'processes',- message: `${failedRestarts.length} errored PM2 process(es) failed to auto-restart: ${failedRestarts.map(r => r.name).join(', ')}`+ message: `High process count: ${pm2Processes.length} PM2 processes (limit: ${state.config.maxTotalProcesses})`});}++ // Check for errored processes and auto-restart them+ if (erroredProcesses.length > 0) {+ const names = erroredProcesses.map(p => p.name);+ emitLog('warn', `🔄 ${names.length} errored PM2 process(es) detected: ${names.join(', ')} — attempting restart`);++ const restartResults = await Promise.all(names.map(async (name) => {+ // execPm2, not execFileAsync('pm2', …, { shell: true }) — `shell: true`+ // resolves `pm2` to pm2.cmd and rebuilds the cmd.exe → pm2.cmd → node+ // chain that v1.6.7 removed, flashing a console window on every restart.+ const result = await execPm2(['restart', name]).catch(e => ({ stdout: '', stderr: e.message }));+ const failed = result.stderr && !result.stdout;+ if (failed) {+ emitLog('error', `❌ Failed to restart ${name}: ${result.stderr}`);+ } else {+ emitLog('success', `✅ Auto-restarted errored process: ${name}`);+ }+ return { name, success: !failed };+ }));++ const failedRestarts = restartResults.filter(r => !r.success);+ if (failedRestarts.length > 0) {+ issues.push({+ type: 'error',+ category: 'processes',+ message: `${failedRestarts.length} errored PM2 process(es) failed to auto-restart: ${failedRestarts.map(r => r.name).join(', ')}`+ });+ }+ }}// Keep memory telemetry without treating expected occupancy as a failure.diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex 69fd4f78f6..f0c321ae6d 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -4,7 +4,9 @@ const mock = vi.hoisted(() => ({daemonRunning: true,state: null,savedState: null,- pm2Stdout: '[]',+ // `null` = PM2 read failed (issue #8164 absent-vs-empty contract); an array+ // (incl. []) = a successful read.+ pm2Processes: [],restartImpl: null,events: [],// PM2 process names belonging to desktop (GUI) apps — exempt from auto-restart.@@ -29,14 +31,15 @@ vi.mock('./cosState.js', () => ({isDaemonRunning: () => mock.daemonRunning}));-// The jlist poll and the auto-restart both run through execPm2 now, so the mock-// dispatches on the verb. Restarts deliberately do NOT go through-// execFile('pm2', …, { shell: true }) — that resolves to pm2.cmd on Windows and-// flashes a console window (docs/WINDOWS_CONSOLE.md).+// The process READ now goes through the strict, mapped-shape reader+// (`listProcessesStrict` — issue #8164) instead of raw `execPm2(['jlist'])` ++// private parsing; `execPm2` remains only for the auto-restart call. Restarts+// deliberately do NOT go through execFile('pm2', …, { shell: true }) — that+// resolves to pm2.cmd on Windows and flashes a console window+// (docs/WINDOWS_CONSOLE.md).vi.mock('./pm2.js', () => ({- execPm2: vi.fn(async (args) => (- args[0] === 'jlist' ? { stdout: mock.pm2Stdout } : mock.restartImpl(args)- ))+ execPm2: vi.fn(async (args) => mock.restartImpl(args)),+ listProcessesStrict: vi.fn(async () => mock.pm2Processes)}));vi.mock('../lib/memoryStats.js', () => ({@@ -67,7 +70,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {mock.daemonRunning = true;mock.state = baseState();mock.savedState = null;- mock.pm2Stdout = '[]';+ mock.pm2Processes = [];mock.events = [];mock.desktopProcessNames = new Set();mock.desktopLookupError = null;@@ -82,28 +85,46 @@ describe('cosHealthMonitor.runHealthCheck', () => {expect(mock.savedState).toBeNull();});- it('extracts the JSON array from pm2 output prefixed with ANSI noise', async () => {- mock.pm2Stdout = '[31mwarning[0m[{"name":"a","pm2_env":{"status":"online"},"monit":{"memory":1000}}]';+ // Issue #8164: a FAILED PM2 read (listProcessesStrict → null) must be+ // recorded as unavailable, never as zero processes — collapsing it to []+ // would suppress restart of a genuinely errored process and report a+ // health check as clean when PM2 was simply unreachable.+ it('records PM2 metrics as unavailable (not empty) when the read fails', async () => {+ mock.pm2Processes = null;+ const { metrics, issues } = await runHealthCheck();+ expect(metrics.pm2).toBeNull();+ expect(issues.some(i => i.type === 'error' && i.category === 'processes' && /read failed/.test(i.message))).toBe(true);+ });++ it('attempts no auto-restart when the PM2 read fails', async () => {+ mock.pm2Processes = null;+ const restarted = [];+ mock.restartImpl = recordRestarts(restarted);+ await runHealthCheck();+ expect(restarted).toEqual([]);+ });++ it('counts a genuine empty read as zero processes, not unavailable', async () => {+ mock.pm2Processes = [];const { metrics } = await runHealthCheck();- expect(metrics.pm2).toEqual({ total: 1, online: 1, errored: 0, stopped: 0, desktopExited: 0 });+ expect(metrics.pm2).toEqual({ total: 0, online: 0, errored: 0, stopped: 0, desktopExited: 0 });});it('flags a high process count over the configured limit', async () => {- const procs = Array.from({ length: 12 }, (_, i) => ({ name: `p${i}`, pm2_env: { status: 'online' }, monit: { memory: 0 } }));- mock.pm2Stdout = JSON.stringify(procs);+ mock.pm2Processes = Array.from({ length: 12 }, (_, i) => ({ name: `p${i}`, status: 'online' }));const { issues } = await runHealthCheck();expect(issues.some(i => i.category === 'processes' && /High process count/.test(i.message))).toBe(true);});it('auto-restarts errored processes without reporting a resolved problem', async () => {- mock.pm2Stdout = JSON.stringify([{ name: 'boom', pm2_env: { status: 'errored' }, monit: { memory: 0 } }]);+ mock.pm2Processes = [{ name: 'boom', status: 'errored' }];const { issues } = await runHealthCheck();expect(issues).toEqual([]);expect(issues.some(i => i.type === 'error')).toBe(false);});it('records an error issue and emits health:critical when a restart fails', async () => {- mock.pm2Stdout = JSON.stringify([{ name: 'boom', pm2_env: { status: 'errored' }, monit: { memory: 0 } }]);+ mock.pm2Processes = [{ name: 'boom', status: 'errored' }];mock.restartImpl = async () => { throw new Error('restart failed'); };const { issues } = await runHealthCheck();expect(issues.some(i => i.type === 'error' && /failed to auto-restart/.test(i.message))).toBe(true);@@ -114,13 +135,11 @@ describe('cosHealthMonitor.runHealthCheck', () => {// `errored`, and restarting would reopen the window the user just closed —// the relaunch loop `autorestart: false` prevents, by another path (#2991).describe('desktop (GUI) process exemption', () => {- const erroredGame = () => JSON.stringify([- { name: 'game', pm2_env: { status: 'errored' }, monit: { memory: 0 } }- ]);+ const erroredGame = () => [{ name: 'game', status: 'errored' }];it('never auto-restarts an errored desktop process', async () => {mock.desktopProcessNames = new Set(['game']);- mock.pm2Stdout = erroredGame();+ mock.pm2Processes = erroredGame();const restarted = [];mock.restartImpl = recordRestarts(restarted);@@ -132,7 +151,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {it('reports a quit game separately instead of as an error', async () => {mock.desktopProcessNames = new Set(['game']);- mock.pm2Stdout = erroredGame();+ mock.pm2Processes = erroredGame();const { metrics } = await runHealthCheck();@@ -142,9 +161,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {it('counts a cleanly stopped desktop process as exited too', async () => {mock.desktopProcessNames = new Set(['game']);- mock.pm2Stdout = JSON.stringify([- { name: 'game', pm2_env: { status: 'stopped' }, monit: { memory: 0 } }- ]);+ mock.pm2Processes = [{ name: 'game', status: 'stopped' }];const { metrics } = await runHealthCheck();@@ -157,10 +174,10 @@ describe('cosHealthMonitor.runHealthCheck', () => {// on it too would leave a live game in `total` and in no bucket at all —// and make the metric read identically whether it is running or quit.mock.desktopProcessNames = new Set(['game']);- mock.pm2Stdout = JSON.stringify([- { name: 'game', pm2_env: { status: 'online' }, monit: { memory: 0 } },- { name: 'web', pm2_env: { status: 'online' }, monit: { memory: 0 } }- ]);+ mock.pm2Processes = [+ { name: 'game', status: 'online' },+ { name: 'web', status: 'online' }+ ];const { metrics } = await runHealthCheck();@@ -169,10 +186,10 @@ describe('cosHealthMonitor.runHealthCheck', () => {it('still auto-restarts non-desktop processes alongside an exempt one', async () => {mock.desktopProcessNames = new Set(['game']);- mock.pm2Stdout = JSON.stringify([- { name: 'game', pm2_env: { status: 'errored' }, monit: { memory: 0 } },- { name: 'web', pm2_env: { status: 'errored' }, monit: { memory: 0 } }- ]);+ mock.pm2Processes = [+ { name: 'game', status: 'errored' },+ { name: 'web', status: 'errored' }+ ];const restarted = [];mock.restartImpl = recordRestarts(restarted, (args) => args[1]);@@ -185,9 +202,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {it('exempts nothing when the registry read fails (pre-existing behavior stands)', async () => {mock.desktopLookupError = new Error('registry unreadable');- mock.pm2Stdout = JSON.stringify([- { name: 'web', pm2_env: { status: 'errored' }, monit: { memory: 0 } }- ]);+ mock.pm2Processes = [{ name: 'web', status: 'errored' }];const restarted = [];mock.restartImpl = recordRestarts(restarted, (args) => args[1]);@@ -199,17 +214,17 @@ describe('cosHealthMonitor.runHealthCheck', () => {});it('keeps memory telemetry without flagging large processes', async () => {- mock.pm2Stdout = JSON.stringify([- { name: 'example-worker', pm2_env: { status: 'online' }, monit: { memory: 24 * 1024 ** 3 } },- { name: 'portos-llama-server', pm2_env: { status: 'online' }, monit: { memory: 24 * 1024 ** 3 } }- ]);+ mock.pm2Processes = [+ { name: 'example-worker', status: 'online' },+ { name: 'portos-llama-server', status: 'online' }+ ];const { metrics, issues } = await runHealthCheck();expect(metrics.memory).toEqual({ usedMb: 100 });expect(issues).toEqual([]);});it('persists the latest snapshot to state and emits health:check', async () => {- mock.pm2Stdout = '[]';+ mock.pm2Processes = [];const { metrics } = await runHealthCheck();expect(mock.savedState.stats.lastHealthCheck).toBe(metrics.timestamp);expect(mock.events.some(e => e.name === 'health:check')).toBe(true);diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 33e423ec78..dbe84cdbc3 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -5,9 +5,10 @@ import { writeFile, unlink } from 'fs/promises';import { join, dirname } from 'path';import { createRequire } from 'module';import { homedir } from 'os';-import { atomicWrite, extractJSONArray, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { parseCommandArgs } from '../lib/commandSecurity.js';import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';+import { parsePm2JlistStdout } from '../lib/pm2Jlist.js';const IS_WIN = process.platform === 'win32';@@ -357,23 +358,15 @@ function shapeProcStatus(proc) {* Parse the stdout of a `pm2 jlist` (custom PM2_HOME CLI path) into a raw* process array, or `null` when the read effectively failed.*- * PM2 jlist always emits a JSON array (`[]` when there are no processes), so an- * exit-0 with empty or garbage stdout (no array literal at all) is a FAILED read- * — not a successful "no processes." Returning `[]` there would reintroduce the- * absent-vs-empty footgun (issue #968) for custom PM2_HOME reads. `extractJSONArray`- * itself falls back to `'[]'` on garbage, so we must detect a real array literal- * before trusting it (mirroring extractJSONArray's own detection) and return null- * otherwise — matching the default-home path, which resolves null for a non-array.+ * Compatibility re-export: the strict parser now lives in the pure+ * `server/lib/pm2Jlist.js` (issue #8164) so package-local consumers like the+ * autofixer can import it without the rest of this service. Kept exported here+ * under its original name for existing first-party callers/tests.** @param {string} stdout Raw `pm2 jlist` stdout (may carry ANSI noise).* @returns {Array|null} The parsed process array (incl. `[]`), or `null` on failure.*/-export function parseJlistStdout(stdout) {- const hasArrayLiteral = typeof stdout === 'string' && (stdout.includes('[{') || /\[\](?![0-9])/.test(stdout));- if (!hasArrayLiteral) return null;- const list = safeJSONParse(extractJSONArray(stdout), null);- return Array.isArray(list) ? list : null;-}+export const parseJlistStdout = parsePm2JlistStdout;/*** Fetch PM2 process list with TTL caching.diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex 36397ec827..a5134ad428 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -2,7 +2,7 @@ import { readFile, readdir, stat } from 'fs/promises';import { existsSync } from 'fs';import { join, basename, dirname } from 'path';import { homedir } from 'os';-import { execPm2 } from './pm2.js';+import { listProcessesStrict } from './pm2.js';import { safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { detectAppIcon } from './appIconDetect.js';@@ -1410,53 +1410,56 @@ export async function streamDetection(socket, dirPath) {emit('pm2', 'skipped', { message: `Not applicable for ${result.type} apps` });} else {emit('pm2', 'running', { message: 'Checking PM2 processes...' });- // Use custom PM2_HOME if detected from ecosystem config- const pm2Env = result.pm2Home ? { ...process.env, PM2_HOME: result.pm2Home } : undefined;- const { stdout } = await execPm2(['jlist'], pm2Env ? { env: pm2Env } : {}).catch(() => ({ stdout: '[]' }));- // pm2 jlist may output ANSI codes and warnings before JSON- let jsonStart = stdout.indexOf('[{');- if (jsonStart < 0) {- const emptyMatch = stdout.match(/\[\](?![0-9])/);- jsonStart = emptyMatch ? stdout.indexOf(emptyMatch[0]) : -1;- }- const pm2Json = jsonStart >= 0 ? stdout.slice(jsonStart) : '[]';- const pm2Processes = safeJSONParse(pm2Json, []);-- // Look for processes that might be this app- const possibleNames = [- result.name,- result.name.toLowerCase(),- result.name.toLowerCase().replace(/[^a-z0-9]/g, '-'),- `${result.name}-ui`,- `${result.name}-api`- ];-- const matchingProcesses = pm2Processes.filter(p =>- possibleNames.some(name => p.name.includes(name) || name.includes(p.name))- );-- if (matchingProcesses.length > 0) {- result.pm2Status = matchingProcesses.map(p => ({- name: p.name,- status: p.pm2_env?.status,- pid: p.pid- }));- // Use actual found PM2 process names- result.pm2ProcessNames = matchingProcesses.map(p => p.name);- emit('pm2', 'done', {- message: `Found ${matchingProcesses.length} running process(es)`,- pm2Status: result.pm2Status,- pm2ProcessNames: result.pm2ProcessNames- });+ // `listProcessesStrict()` returns `null` when the read itself FAILED (vs+ // `[]` for a successful read with no processes) — the absent-vs-empty+ // contract from issue #968, now the one non-test owner of raw `pm2 jlist`+ // execution/parsing alongside `autofixer/shared.js` (#8164). Use custom+ // PM2_HOME if detected from ecosystem config.+ const pm2Processes = await listProcessesStrict(result.pm2Home || null);++ if (pm2Processes === null) {+ // A failed read must not be reported as "no matching processes" — that+ // would silently drop the pm2ProcessNames the ecosystem config already+ // found. Leave result.pm2Status/pm2ProcessNames as already derived and+ // surface the read failure on its own stage.+ emit('pm2', 'error', { message: 'PM2 process read failed — status is unavailable' });} else {- emit('pm2', 'done', { message: 'No matching PM2 processes found' });- // Generate PM2 process names only if none found from ecosystem.config- if (result.pm2ProcessNames.length === 0) {- const baseName = result.name.toLowerCase().replace(/[^a-z0-9]/g, '-');- if (result.type === 'vite+express') {- result.pm2ProcessNames = [`${baseName}-ui`, `${baseName}-api`];- } else {- result.pm2ProcessNames = [baseName];+ // Look for processes that might be this app+ const possibleNames = [+ result.name,+ result.name.toLowerCase(),+ result.name.toLowerCase().replace(/[^a-z0-9]/g, '-'),+ `${result.name}-ui`,+ `${result.name}-api`+ ];++ const matchingProcesses = pm2Processes.filter(p =>+ possibleNames.some(name => p.name.includes(name) || name.includes(p.name))+ );++ if (matchingProcesses.length > 0) {+ result.pm2Status = matchingProcesses.map(p => ({+ name: p.name,+ status: p.status,+ pid: p.pid+ }));+ // Use actual found PM2 process names+ result.pm2ProcessNames = matchingProcesses.map(p => p.name);+ emit('pm2', 'done', {+ message: `Found ${matchingProcesses.length} running process(es)`,+ pm2Status: result.pm2Status,+ pm2ProcessNames: result.pm2ProcessNames+ });+ } else {+ emit('pm2', 'done', { message: 'No matching PM2 processes found' });+ // Generate PM2 process names only if none found from ecosystem.config+ if (result.pm2ProcessNames.length === 0) {+ const baseName = result.name.toLowerCase().replace(/[^a-z0-9]/g, '-');+ if (result.type === 'vite+express') {+ result.pm2ProcessNames = [`${baseName}-ui`, `${baseName}-api`];+ } else {+ result.pm2ProcessNames = [baseName];+ }}}}diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.jsindex f1da9beb4e..12ed5bf0c8 100644--- a/server/services/streamingDetect.test.js+++ b/server/services/streamingDetect.test.js@@ -6,7 +6,11 @@ import { detectGodotNativeLaunch, parseEcosystemConfig, resolveViteConfigPortFor// streamDetection shells out to PM2 and scans for an app icon; neither is under// test here and both are slow/environment-dependent.-vi.mock('./pm2.js', () => ({ execPm2: vi.fn(async () => ({ stdout: '[]' })) }));+// `null` = a failed PM2 read (issue #8164 absent-vs-empty contract, matching+// `listProcessesStrict`'s real return type); an array (incl. []) = a+// successful read. Default to a successful empty read.+const pm2Mock = vi.hoisted(() => ({ processes: [] }));+vi.mock('./pm2.js', () => ({ listProcessesStrict: vi.fn(async () => pm2Mock.processes) }));vi.mock('./appIconDetect.js', () => ({ detectAppIcon: vi.fn(async () => null) }));describe('detectGodotNativeLaunch', () => {@@ -1112,6 +1116,24 @@ describe('streamDetection app-type classification', () => {});expect(result.type).toBe('vite+express');});++ // Issue #8164: a FAILED PM2 read (listProcessesStrict → null, distinct from+ // a successful empty `[]` read) must not silently drop the process names the+ // ecosystem config already derived, or fabricate a fake "no processes+ // matched" status.+ it('preserves ecosystem-derived process names and skips status when PM2 is unreachable', async () => {+ pm2Mock.processes = null;+ try {+ const { result } = await detect({+ 'package.json': JSON.stringify({ name: 'example', dependencies: { express: '^4' } }),+ 'ecosystem.config.cjs': "module.exports = { apps: [{ name: 'example-api', script: 'server.js' }] };\n"+ });+ expect(result.pm2ProcessNames).toEqual(['example-api']);+ expect(result.pm2Status).toBeNull();+ } finally {+ pm2Mock.processes = [];+ }+ });});describe('classifyNonNodeType', () => {