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

feat: auto-detect pm2Home from ecosystem config during ingestion

Adam Eivy2360bf75c5fa
diff --git a/.changelog/v0.13.x.md b/.changelog/v0.13.x.md
index a1b0fa7ae7..79e60d87b1 100644
--- a/.changelog/v0.13.x.md
+++ b/.changelog/v0.13.x.md
@@ -231,3 +231,14 @@ This release expands the genome dashboard with comprehensive cancer predispositi
### Autofixer — PATH Inheritance for nvm Environments
- **Fixed `pm2 jlist` failing with "env: node: No such file or directory"** — the autofixer process spawns child shells via `exec()` that didn't inherit the nvm PATH; added `PATH: process.env.PATH` to the autofixer's PM2 env config so child processes can find node/pm2
+
+### PM2 Scripts — Removed Project-Local PM2_HOME Isolation
+- **Simplified PM2 npm scripts** — removed `PM2_HOME=.pm2` and local binary path from all pm2:* scripts; now uses global pm2 installation directly
+- **Native pm2 commands work** — `pm2 logs`, `pm2 status`, `pm2 monit` etc. now work without wrappers since PortOS shares the global `~/.pm2` daemon
+- **Cleaned up stale local .pm2 directory** — the project-local PM2 daemon was causing "invalid pid" errors when state got out of sync with the global daemon
+
+### Custom PM2_HOME Auto-Detection
+- **Automatic pm2Home extraction during app detection/ingestion** — the streaming detector now parses ecosystem.config.js for `const PM2_HOME = ...` declarations and extracts the custom path
+- **Template literal support** — handles common patterns like `` `${require("os").homedir()}/.pm2-grace` `` by resolving the homedir at detection time
+- **Refresh config updates pm2Home** — the `/api/apps/:id/refresh-config` endpoint now auto-populates pm2Home when re-parsing the ecosystem config, so existing apps can pick up custom PM2_HOME settings without re-ingestion
+- **Detection uses correct PM2_HOME for status checks** — when detecting a new app with a custom PM2_HOME, the PM2 status check runs against the correct daemon instance instead of the default
diff --git a/server/routes/apps.js b/server/routes/apps.js
index bc06fdfb94..5f2fe89d65 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -57,7 +57,8 @@ router.get('/', asyncHandler(async (req, res) => {
// Auto-populate processes from ecosystem config if not already set
let processes = app.processes;
if ((!processes || processes.length === 0) && existsSync(app.repoPath)) {
- processes = await parseEcosystemFromPath(app.repoPath).catch(() => []);
+ const parsed = await parseEcosystemFromPath(app.repoPath).catch(() => ({ processes: [] }));
+ processes = parsed.processes;
}
return {
@@ -413,11 +414,16 @@ router.post('/:id/refresh-config', asyncHandler(async (req, res, next) => {
}
// Parse ecosystem config from the app's repo path
- const processes = await parseEcosystemFromPath(app.repoPath);
+ const { processes, pm2Home } = await parseEcosystemFromPath(app.repoPath);
// Update app with new process data
const updates = {};
+ // Update pm2Home if detected and different from current
+ if (pm2Home && pm2Home !== app.pm2Home) {
+ updates.pm2Home = pm2Home;
+ }
+
if (processes.length > 0) {
updates.processes = processes;
updates.pm2ProcessNames = processes.map(p => p.name);
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index c7c1c816a1..dc686e315e 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -10,9 +10,32 @@ const execAsync = promisify(exec);
/**
* Parse ecosystem.config.js/cjs to extract all processes with their ports
* Uses regex parsing since we can't safely execute arbitrary JS
+ * @returns {{ processes: Array, pm2Home: string|null }}
*/
export function parseEcosystemConfig(content) {
const processes = [];
+ let pm2Home = null;
+
+ // Extract PM2_HOME constant if defined (e.g., const PM2_HOME = `${require("os").homedir()}/.pm2-grace`)
+ const pm2HomeMatch = content.match(/(?:const|let|var)\s+PM2_HOME\s*=\s*[`'"](.*?)[`'"]/);
+ if (pm2HomeMatch) {
+ // Handle template literal with homedir()
+ let homePath = pm2HomeMatch[1];
+ homePath = homePath.replace(/\$\{require\(['"]os['"]\)\.homedir\(\)\}/, process.env.HOME || '~');
+ pm2Home = homePath;
+ } else {
+ // Check for PM2_HOME in env blocks
+ const envPm2HomeMatch = content.match(/PM2_HOME\s*:\s*PM2_HOME/);
+ if (envPm2HomeMatch) {
+ // PM2_HOME is used but defined as a variable - try to extract the original definition
+ const varMatch = content.match(/PM2_HOME\s*=\s*`([^`]+)`/);
+ if (varMatch) {
+ let homePath = varMatch[1];
+ homePath = homePath.replace(/\$\{require\(['"]os['"]\)\.homedir\(\)\}/, process.env.HOME || '~');
+ pm2Home = homePath;
+ }
+ }
+ }
// Extract top-level port constants (e.g., const CDP_PORT = 5549)
const portConstants = {};
@@ -248,7 +271,7 @@ export function parseEcosystemConfig(content) {
lastIndex = endPos;
}
- return processes;
+ return { processes, pm2Home };
}
/**
@@ -262,13 +285,14 @@ function extractVitePort(content) {
/**
* Parse ecosystem config from a directory path (non-streaming, for refresh)
* Also checks vite.config files in subdirectories for processes that use Vite
+ * @returns {{ processes: Array, pm2Home: string|null }}
*/
export async function parseEcosystemFromPath(dirPath) {
for (const ecosystemFile of ['ecosystem.config.js', 'ecosystem.config.cjs']) {
const ecosystemPath = join(dirPath, ecosystemFile);
if (existsSync(ecosystemPath)) {
const content = await readFile(ecosystemPath, 'utf-8');
- const processes = parseEcosystemConfig(content);
+ const { processes, pm2Home } = parseEcosystemConfig(content);
// For processes that use vite and don't have a port, check their cwd for vite.config
for (const proc of processes) {
@@ -291,10 +315,10 @@ export async function parseEcosystemFromPath(dirPath) {
delete proc.usesVite;
}
- return processes;
+ return { processes, pm2Home };
}
}
- return [];
+ return { processes: [], pm2Home: null };
}
/**
@@ -314,6 +338,7 @@ export async function streamDetection(socket, dirPath) {
pm2ProcessNames: [],
pm2Status: null,
processes: [],
+ pm2Home: null,
type: 'unknown'
};
@@ -414,7 +439,10 @@ export async function streamDetection(socket, dirPath) {
const content = await readFile(ecosystemPath, 'utf-8').catch(() => '');
if (content) {
// Parse all processes with their ports using the dedicated parser
- const parsedProcesses = parseEcosystemConfig(content);
+ const { processes: parsedProcesses, pm2Home } = parseEcosystemConfig(content);
+ if (pm2Home) {
+ result.pm2Home = pm2Home;
+ }
if (parsedProcesses.length > 0) {
// For processes that use vite and don't have a port, check their cwd for vite.config
for (const proc of parsedProcesses) {
@@ -469,8 +497,18 @@ export async function streamDetection(socket, dirPath) {
// Step 5: Check PM2 status
emit('pm2', 'running', { message: 'Checking PM2 processes...' });
- const { stdout } = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));
- const pm2Processes = safeJSONParse(stdout, []);
+ // Use custom PM2_HOME if detected from ecosystem config
+ const pm2Env = result.pm2Home ? { ...process.env, PM2_HOME: result.pm2Home } : process.env;
+ const pm2Cmd = 'pm2 jlist';
+ const { stdout } = await execAsync(pm2Cmd, { 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 = [