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
fix: stop AI fixers from killing the shared pm2 daemon
Adam Eivy090b8c52689c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1fef94c7ae..cb2fdf623d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## Fixed++- **AI fixers can no longer take down the whole server with `pm2 kill`.** PortOS runs every managed app under one shared pm2 daemon, so `pm2 kill` / `pm2 delete all` stops *everything* — including PortOS itself. A "Fix with AI" / autofixer agent (which runs its CLI fully unrestricted) could be talked into running one while trying to "restart the app." Three layers now block this: (1) the shell-command allowlist (`validateCommand`) rejects `pm2 kill`/`startup`/`unstartup` and any `pm2 <verb> all` for the manual command runner and autonomous jobs; (2) spawned AI agents (CoS tasks, the autofixer app) get a guarded `pm2` shim prepended to their PATH that intercepts those same destructive subcommands before they reach the real pm2 — a hard guard that holds even under `--dangerously-skip-permissions`; (3) every agent prompt now states the shared-daemon rule and to only `pm2 restart <its-own-process>`. Scoped commands (`pm2 restart my-app`, `pm2 logs my-app`, `pm2 list`) still work.+## Changed- The **Social Agents** page now lives under the **Chief of Staff** sidebar section instead of **Brain**, in both the sidebar and the ⌘K / voice nav manifest.diff --git a/autofixer/server.js b/autofixer/server.jsindex 7c7a3fdcb7..bbc777b804 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -8,10 +8,17 @@ import { createRequire } from 'module';// Lets the autofixer honor the user's configured CLI provider/model instead// of hardcoding `claude -p`.import { pickCliProvider, runCliProviderPrompt } from '../server/lib/cliProviderRun.js';+import { agentGuardEnv } from '../server/lib/agentGuard/index.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Prepend the guarded pm2 shim to this process's PATH. The fix agent spawned by+// runCliProviderPrompt inherits process.env, so a confused agent told to "restart+// PM2" can't `pm2 kill` the shared daemon (which would down every app + PortOS).+// Our own execPm2 calls use an absolute PM2_BIN, so they bypass the shim.+Object.assign(process.env, agentGuardEnv());+// Resolve PM2 binary to avoid pm2.cmd on Windows (creates visible CMD windows)const require = createRequire(import.meta.url);const PM2_BIN = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');@@ -196,10 +203,14 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {1. Analyze the error logs below to understand what caused the crash2. Read relevant source files to understand the issue3. Fix the bug by editing the necessary files-4. After fixing, run: pm2 restart ${processName}+4. After fixing, restart ONLY this process: pm2 restart ${processName}5. Verify the process starts successfully by checking pm2 list6. If it still fails, analyze the new error and try again (max 2 attempts)+**🛑 PM2 SAFETY — this is a SHARED server running many apps:**+- ONLY ever run \`pm2 restart ${processName}\` (or \`pm2 logs ${processName}\`). NEVER target a different process.+- NEVER run \`pm2 kill\`, \`pm2 stop\`, \`pm2 delete\`, \`pm2 startup\`/\`unstartup\`, or any \`... all\` form. They take down EVERY app on this machine, including PortOS itself, and are blocked — they will fail.+**App Information:**- App Name: ${app.name}- Process Name: ${processName}@@ -217,7 +228,7 @@ ${outputLogs || '(no output logs available)'}\`\`\`**Your Task:**-Fix the issue and restart the process. Be systematic and thorough. Use the Bash tool to restart PM2 after making your fixes.`;+Fix the issue and restart the process. Be systematic and thorough. Use the Bash tool to run \`pm2 restart ${processName}\` after making your fixes — never a broader pm2 command.`;await ensureHistoryDir();diff --git a/server/lib/README.md b/server/lib/README.mdindex b9e0ad202a..bc8a007c54 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -122,10 +122,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `agentGuard/` | `agentGuardEnv(baseEnv?)` + `AGENT_GUARD_BIN` — env patch that prepends a guarded `pm2` shim (`bin/pm2`) to a spawned AI agent's PATH so a confused `--dangerously-skip-permissions` agent can't `pm2 kill` / `pm2 delete all` the shared daemon (which would down every app, incl. PortOS). Blocked-subcommand list mirrors `validatePm2Command` in `commandSecurity.js`. POSIX-only (no-op on Windows). || `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. |-| `commandSecurity.js` | Allowlist of safe shell commands. |+| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |diff --git a/server/lib/agentGuard/bin/pm2 b/server/lib/agentGuard/bin/pm2new file mode 100755index 0000000000..0ccfcb36a9--- /dev/null+++ b/server/lib/agentGuard/bin/pm2@@ -0,0 +1,60 @@+#!/usr/bin/env bash+#+# PortOS agent guard — pm2 shim+# ------------------------------+# Spawned AI agents (CoS "Fix with AI" tasks, the autofixer app, etc.) run their+# CLI with `--dangerously-skip-permissions`, i.e. fully unrestricted Bash. PortOS+# prepends THIS directory to those agents' PATH (see server/lib/agentGuard), so a+# bare `pm2 ...` resolves here first. We block the handful of subcommands that+# would take down the SHARED PM2 daemon — and therefore every other app on the+# machine, including PortOS itself — then exec the real pm2 for everything else.+#+# This list is mirrored in server/lib/commandSecurity.js (validatePm2Command).+# Keep the two in sync.+#+# Note: this is defense-in-depth against a *confused* agent, not a sandbox. An+# agent that calls pm2 by absolute path bypasses the shim — acceptable for+# PortOS's single-user, private-network trust model.++sub="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"++block() {+ printf '🛑 PortOS agent guard: `pm2 %s` is blocked — it would disrupt the shared PM2 daemon or other apps on this server (including PortOS itself). Restart only your own app with `pm2 restart <your-process-name>`.\n' "$*" >&2+ exit 1+}++case "$sub" in+ kill|startup|unstartup) block "$@" ;;+esac++case "$sub" in+ stop|delete|del|restart|reload|gracefulreload|scale)+ for arg in "${@:2}"; do+ lower="$(printf '%s' "$arg" | tr '[:upper:]' '[:lower:]')"+ [ "$lower" = "all" ] && block "$@"+ done+ ;;+esac++# Resolve the real pm2. PortOS sets PORTOS_REAL_PM2 to the Node-resolved binary;+# fall back to the first pm2 on PATH that is NOT this shim's own directory.+self_dir="$(cd "$(dirname "$0")" && pwd)"+real="$PORTOS_REAL_PM2"+if [ -z "$real" ] || [ ! -x "$real" ]; then+ real=""+ OLD_IFS="$IFS"; IFS=':'+ for d in $PATH; do+ [ -z "$d" ] && continue+ resolved="$(cd "$d" 2>/dev/null && pwd)" || continue+ [ "$resolved" = "$self_dir" ] && continue+ if [ -x "$d/pm2" ]; then real="$d/pm2"; break; fi+ done+ IFS="$OLD_IFS"+fi++if [ -z "$real" ]; then+ printf '🛑 PortOS agent guard: real pm2 binary not found on PATH.\n' >&2+ exit 127+fi++exec "$real" "$@"diff --git a/server/lib/agentGuard/index.js b/server/lib/agentGuard/index.jsnew file mode 100644index 0000000000..8b4b5ad5cd--- /dev/null+++ b/server/lib/agentGuard/index.js@@ -0,0 +1,50 @@+// Agent guard — keeps spawned AI agents from killing the shared PM2 daemon.+//+// CoS "Fix with AI" tasks and the autofixer app run their CLI with+// `--dangerously-skip-permissions` (fully unrestricted Bash). A confused agent+// asked to "restart the app" once ran `pm2 kill`, which took down EVERY app on+// the machine — including PortOS itself. `agentGuardEnv()` returns an env patch+// that prepends a guarded `pm2` shim (./bin/pm2) to the agent's PATH so a bare+// `pm2 kill` / `pm2 delete all` is intercepted before it reaches the real pm2.+// The shim's blocked-subcommand list mirrors `validatePm2Command` in+// commandSecurity.js (which guards the non-agentic command paths).+//+// POSIX-only by design: the shim is a bash script, so on Windows (pm2.cmd, no+// bash) the prepend is a harmless no-op and pm2 resolves normally.++import { delimiter, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createRequire } from 'node:module';++const HERE = dirname(fileURLToPath(import.meta.url));++// Directory containing the guarded `pm2` shim.+export const AGENT_GUARD_BIN = join(HERE, 'bin');++// Node-resolved path to the REAL pm2 binary, handed to the shim via+// PORTOS_REAL_PM2 so it doesn't have to rediscover it on PATH. Resolved once.+function resolveRealPm2() {+ const require = createRequire(import.meta.url);+ // require.resolve throws when pm2 isn't installed — the shim falls back to a+ // PATH scan in that case, so an unresolved binary is non-fatal.+ try {+ return join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');+ } catch {+ return undefined;+ }+}++const REAL_PM2 = resolveRealPm2();++/**+ * Env patch to merge into a spawned agent's environment. Prepends the guarded+ * pm2 shim to PATH and points it at the real pm2.+ * @param {NodeJS.ProcessEnv} [baseEnv=process.env] base env to read PATH from.+ * @returns {{ PATH: string, PORTOS_REAL_PM2?: string }}+ */+export function agentGuardEnv(baseEnv = process.env) {+ const currentPath = baseEnv.PATH || baseEnv.Path || '';+ const patch = { PATH: `${AGENT_GUARD_BIN}${delimiter}${currentPath}` };+ if (REAL_PM2) patch.PORTOS_REAL_PM2 = REAL_PM2;+ return patch;+}diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.jsindex 8bd37979d3..d971965a1f 100644--- a/server/lib/commandSecurity.js+++ b/server/lib/commandSecurity.js@@ -46,6 +46,37 @@ export function parseCommandArgs(str) {return args;}+// PM2 runs ONE shared daemon for every app on the machine. These subcommands+// take the whole daemon (and therefore every other app, including PortOS itself)+// down or rewrite system boot config — never legitimate for a single app's+// scoped management. Blocked regardless of who issues them. This list is mirrored+// in the agent PATH-shim (server/lib/agentGuard/bin/pm2) — keep them in sync.+export const PM2_BLOCKED_SUBCOMMANDS = new Set(['kill', 'startup', 'unstartup']);++// Daemon-wide verbs that are fine against a single named process but catastrophic+// with the `all` target (`pm2 stop all`, `pm2 delete all`, `pm2 restart all` —+// the unscoped form the user's CLAUDE.md explicitly forbids). Blocked only when+// the target is `all`.+export const PM2_ALL_TARGET_VERBS = new Set([+ 'stop', 'delete', 'del', 'restart', 'reload', 'gracefulreload', 'scale',+]);++/**+ * Reject pm2 invocations that would disrupt the shared PM2 daemon or other apps.+ * `args` is everything after the `pm2` base command.+ * Returns { valid, error? }.+ */+export function validatePm2Command(args) {+ const sub = (args[0] || '').toLowerCase();+ if (PM2_BLOCKED_SUBCOMMANDS.has(sub)) {+ return { valid: false, error: `'pm2 ${sub}' is blocked — it would take down the shared PM2 daemon or every app on this machine (including PortOS). Use a scoped command like 'pm2 restart <process-name>'.` };+ }+ if (PM2_ALL_TARGET_VERBS.has(sub) && args.slice(1).some(a => a.toLowerCase() === 'all')) {+ return { valid: false, error: `'pm2 ${sub} all' is blocked — it affects every app on this shared server. Target a specific process by name instead.` };+ }+ return { valid: true };+}+/*** Validate a command against the allowlist.* Returns { valid, error?, baseCommand?, args? }@@ -64,7 +95,12 @@ export function validateCommand(command) {if (!ALLOWED_COMMANDS.has(baseCommand)) {return { valid: false, error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${ALLOWED_COMMANDS_SORTED.join(', ')}` };}- return { valid: true, baseCommand, args: parts.slice(1) };+ const args = parts.slice(1);+ if (baseCommand === 'pm2') {+ const pm2Check = validatePm2Command(args);+ if (!pm2Check.valid) return pm2Check;+ }+ return { valid: true, baseCommand, args };}// Patterns matching sensitive env var values in command outputdiff --git a/server/lib/commandSecurity.test.js b/server/lib/commandSecurity.test.jsindex 6b0db8b4a9..70d03c1ed4 100644--- a/server/lib/commandSecurity.test.js+++ b/server/lib/commandSecurity.test.js@@ -4,6 +4,7 @@ import {ALLOWED_COMMANDS_SORTED,DANGEROUS_SHELL_CHARS,validateCommand,+ validatePm2Command,redactOutput,parseCommandArgs} from './commandSecurity.js'@@ -228,4 +229,45 @@ describe('commandSecurity', () => {expect(parseCommandArgs('echo ""')).toEqual(['echo', ''])})})++ describe('pm2 daemon-protection (validatePm2Command via validateCommand)', () => {+ // The shared pm2 daemon runs every app on the machine. These must never reach+ // the shell — `pm2 kill` once took the whole server (incl. PortOS) down.+ it.each([+ 'pm2 kill',+ 'pm2 startup',+ 'pm2 unstartup',+ 'pm2 stop all',+ 'pm2 delete all',+ 'pm2 del all',+ 'pm2 restart all',+ 'pm2 reload all',+ 'pm2 scale all 2',+ 'pm2 KILL', // case-insensitive subcommand+ 'pm2 stop ALL', // case-insensitive target+ ])('rejects %s', (cmd) => {+ const result = validateCommand(cmd)+ expect(result.valid).toBe(false)+ expect(result.error).toMatch(/blocked/)+ })++ it.each([+ 'pm2 list',+ 'pm2 jlist',+ 'pm2 logs my-app',+ 'pm2 restart my-app',+ 'pm2 stop my-app',+ 'pm2 delete my-app',+ 'pm2 reload my-app',+ 'pm2 describe my-app',+ ])('allows scoped command %s', (cmd) => {+ expect(validateCommand(cmd).valid).toBe(true)+ })++ it('validatePm2Command is callable directly with arg arrays', () => {+ expect(validatePm2Command(['kill']).valid).toBe(false)+ expect(validatePm2Command(['restart', 'my-app']).valid).toBe(true)+ expect(validatePm2Command(['delete', 'all']).valid).toBe(false)+ })+ })})diff --git a/server/lib/index.js b/server/lib/index.jsindex 7329d08e78..d18f69c061 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -113,6 +113,7 @@ export * from './zipStream.js';export * from './zipWriter.js';// === Process execution ===+export * from './agentGuard/index.js';export * from './bashResolver.js';export * from './bufferedSpawn.js';export * from './commandSecurity.js';diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 8ba2f57fee..ae21c85a94 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -26,6 +26,7 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';+import { agentGuardEnv } from '../lib/agentGuard/index.js';const AGENTS_DIR = PATHS.cosAgents;@@ -376,7 +377,10 @@ export async function spawnDirectly({shell: false,stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true,- env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; return e; })()+ // The pm2 shim must be prepended onto the FINAL PATH (after any+ // provider.envVars override) so a `--dangerously-skip-permissions` agent+ // can't `pm2 kill` the shared daemon.+ env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()});registerSpawnedAgent(claudeProcess.pid, {diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 44bcd0930d..c48cdc15ca 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -25,6 +25,14 @@ const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');+// Appended to every agent briefing. PortOS shares ONE pm2 daemon across many+// apps; an agent restarting "the server" once ran `pm2 kill` and took the whole+// machine (incl. PortOS) down. A PATH shim (server/lib/agentGuard) hard-blocks+// the destructive subcommands, but the prompt rule keeps a well-behaved agent+// from even attempting them.+export const PM2_SAFETY_RULE = `## ⚠️ PM2 Safety (shared server)+PortOS runs MANY apps under one shared pm2 daemon. To restart an app, use a SCOPED command — \`pm2 restart <that-app's-process-name>\`. NEVER run \`pm2 kill\`, \`pm2 stop\`, \`pm2 delete\`, \`pm2 startup\`/\`unstartup\`, or any \`pm2 <verb> all\` form: they take down EVERY app on this machine, including PortOS itself, and are blocked (they will fail).`;+/*** Skill template keyword matchers.* Each entry maps a skill template filename to its trigger keywords.@@ -613,7 +621,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch}).catch(() => null);if (promptData?.prompt) {- return promptData.prompt;+ return `${promptData.prompt}\n\n${PM2_SAFETY_RULE}`;}const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });@@ -676,6 +684,8 @@ ${worktreeInfo ? `- **Your PR should contain only your task's commits.** If you## Working Directory${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.+${PM2_SAFETY_RULE}+Begin working on the task now.`;}diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 22bd8a9ebe..ec0831c935 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -40,6 +40,7 @@ import {inferTuiCommand,applyCommandDefaults,} from '../lib/tuiHandshake.js';+import { agentGuardEnv } from '../lib/agentGuard/index.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).@@ -129,7 +130,10 @@ export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onDatlabel: `${provider.name} ${agentId}`,command: tuiConfig.commandLine,initialCommand: tuiConfig.commandLine,- env: provider.envVars || {},+ // agentGuardEnv() prepends the pm2 shim to the agent session's PATH (and+ // points it at the real pm2). Spread LAST so it wins over any provider PATH.+ // Only AI agent sessions get this — the user's own Shell page does not.+ env: { ...(provider.envVars || {}), ...agentGuardEnv() },onData,onExit,});diff --git a/server/services/runner.js b/server/services/runner.jsindex 9466e84bbb..cd58082cb4 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -8,6 +8,7 @@ import { join } from 'path';import { ensureDir, tryReadFile } from '../lib/fileUtils.js';import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildCliArgs } from '../lib/cliProviderArgs.js';+import { agentGuardEnv } from '../lib/agentGuard/index.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import {setAIToolkitInstance,@@ -173,7 +174,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onchildProcess = spawn(provider.command, args, {cwd: workspacePath,- env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),+ // Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted+ // agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.+ env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })(),windowsHide: true});