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(windows): stop console windows flashing and stealing focus (#4319)
[._.]/ Adam Eivy91e6799e51e7
diff --git a/.changelog/next/fixed-agent-768879f6.md b/.changelog/next/fixed-agent-768879f6.mdnew file mode 100644index 0000000000..da98566d8e--- /dev/null+++ b/.changelog/next/fixed-agent-768879f6.md@@ -0,0 +1 @@+- **Windows console windows no longer flash and steal focus.** A process with no console of its own — every PortOS app, since they are all PM2 forks — makes Windows allocate a brand-new console for any console child it spawns (`git`, `gh`, `psql`, `ffmpeg`, `where`, `taskkill`). Under the Windows 11 default terminal setting that allocation is handed to Windows Terminal over COM, which starts `OpenConsole.exe -Embedding` plus a terminal window that grabs foreground focus and dies with the child; at PortOS's background spawn rate that is a steady stream of unusable windows stealing keystrokes. Server runtime code now imports `server/lib/childProcess.js` instead of `child_process` — a drop-in wrapper that defaults `windowsHide: true` (`CREATE_NO_WINDOW`) on every `spawn`/`spawnSync`/`fork`/`exec`/`execSync`/`execFile`/`execFileSync`, keeping `promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`, and honoring an explicit `windowsHide: false`. 84 files migrated. `childProcess.guards.test.js` now fails the build on a direct `child_process` import, on an aiToolkit spawn without inline `windowsHide`, and on `pm2` invoked through a shell — the same bug was swept away by hand in v1.5.x and v1.6.7 and regressed both times. Also routed the two `shell: true` pm2 calls back through `execPm2` (`cosHealthMonitor.js` auto-restart, `browserService.js` start/stop/restart/jlist/logs), dropping the `cmd.exe -> pm2.cmd -> node` hops and the PATH ambiguity of resolving a bare `pm2` through a shell, and fixed the missing `windowsHide` on the aiToolkit CLI probes and on `browser/server.js`. New `npm run fix:windows-console` points the machine's default terminal at the classic console host, which stops the handoff for every app on the box, not just PortOS. Background: `docs/WINDOWS_CONSOLE.md`.diff --git a/browser/server.js b/browser/server.jsindex 5090e6e39c..da1ff87e6e 100644--- a/browser/server.js+++ b/browser/server.js@@ -226,7 +226,11 @@ async function launchBrowser() {// Headless mode skips this (no UI to click) and non-darwin platforms don't// have the TCC-responsibility problem at all.if (platform() === 'darwin' && !headlessMode) {- chromeProcess = spawn('/usr/bin/open', ['-na', macAppBundle, '--args', ...args], { stdio: 'ignore' });+ // windowsHide is a no-op on POSIX and this branch is darwin-only, but every+ // spawn in this package carries it: portos-browser is a PM2 fork, so the+ // guard holds the whole tree to one rule rather than reasoning about which+ // branch runs where. See docs/WINDOWS_CONSOLE.md.+ chromeProcess = spawn('/usr/bin/open', ['-na', macAppBundle, '--args', ...args], { stdio: 'ignore', windowsHide: true });chromeProcess.on('exit', () => {// `open` returns ~immediately once Chrome is handed off to launchd; that// exit is not Chrome's death. Chrome-exit detection happens via thediff --git a/docs/README.md b/docs/README.mdindex 0048c914cb..ea4aa8763b 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,6 +21,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [SELF_UPDATE.md](./SELF_UPDATE.md) | Fork-aware self-update flow — release polling, `FORK_SYNC_REQUIRED`, fork sync || [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict || [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) | Common runtime issues, known issues |+| [WINDOWS_CONSOLE.md](./WINDOWS_CONSOLE.md) | Why console windows flash and steal focus on Windows, and the two fixes || [GOALS_OPERATIONAL.md](./GOALS_OPERATIONAL.md) | Runtime operating principles the CoS agent reads (parsed by `goalProgress.js`) || [METRICS.md](./METRICS.md) | The `METRICS.md` convention — how a managed app exposes its own success metrics so agents (incl. Layered Intelligence) can evaluate it against its goals || [SECURITY_AUDIT.md](./SECURITY_AUDIT.md) | Historical hardening audit (2026-02, all items resolved) |diff --git a/docs/WINDOWS_CONSOLE.md b/docs/WINDOWS_CONSOLE.mdnew file mode 100644index 0000000000..100e75df57--- /dev/null+++ b/docs/WINDOWS_CONSOLE.md@@ -0,0 +1,167 @@+# Windows: console windows flashing and stealing focus++On Windows you may see a stream of console windows opening and closing across+the desktop — often more than a dozen at once — that grab foreground focus and+render as unusable, half-drawn terminals. In Task Manager they appear as+`OpenConsole.exe` processes started with `-Embedding`.++This document explains the mechanism, how to confirm what is causing it on your+machine, and the two fixes.++## The short version++`OpenConsole.exe -Embedding` is not a program anything launches on purpose. It+is Windows' **default-terminal handoff**, and it fires whenever all three of+these are true:++1. A process **without a console of its own** spawns a child, **and**+2. the child is a **console application** (`git`, `gh`, `psql`, `ffmpeg`,+ `where`, `taskkill`, `cmd`, a Node CLI…), **and**+3. the spawn does **not** pass `CREATE_NO_WINDOW`.++Windows must then allocate a brand-new console. Instead of drawing it with the+classic `conhost.exe`, it hands the console off over COM to whatever is+configured as the **Default terminal application**. On Windows 11 that is+Windows Terminal — including under the default `{00000000-…}` "Let Windows+decide" value. The handoff starts `OpenConsole.exe -Embedding` as the COM local+server and a Windows Terminal window to host it, the window takes foreground+focus, and both die when the short-lived child exits.++One `git status` is a flicker. A background process doing this a few times a+second is a desktop that will not hold focus.++Condition 1 is permanent for PortOS: every PortOS app is a PM2 fork, and PM2+forks have no console. So on Windows, **any** PortOS spawn that omits+`windowsHide: true` produces a focus-stealing window.++## Confirming it on your machine++Console hosts are far too short-lived to catch by polling `Get-Process`. Use a+WMI creation-event trace, which misses nothing:++```powershell+$q = "SELECT * FROM __InstanceCreationEvent WITHIN 0.05 WHERE TargetInstance ISA 'Win32_Process'"+Register-CimIndicationEvent -Query $q -SourceIdentifier Trace | Out-Null+$deadline = (Get-Date).AddSeconds(60)+while ((Get-Date) -lt $deadline) {+ foreach ($e in (Get-Event -SourceIdentifier Trace -ErrorAction SilentlyContinue)) {+ $t = $e.SourceEventArgs.NewEvent.TargetInstance+ "{0} pid={1} ppid={2} {3} :: {4}" -f $e.TimeGenerated.ToString('HH:mm:ss.fff'),+ $t.ProcessId, $t.ParentProcessId, $t.Name, $t.CommandLine+ Remove-Event -EventIdentifier $e.EventIdentifier+ }+ Start-Sleep -Milliseconds 250+}+Unregister-Event -SourceIdentifier Trace+```++Two things to read out of the trace:++- **Every `OpenConsole.exe -Embedding` line has `ppid` pointing at the DCOM+ launcher (`svchost.exe`), not at the app that caused it.** That is the COM+ activation, and it is why the parent chain never names the real culprit.+- **Attribute by walking the *console child's* ancestry instead** — group the+ `git.exe` / `cmd.exe` / `where.exe` creations by their root ancestor. That is+ what identifies the actual spawner.++PortOS is frequently *not* the only contributor. Any tool that polls git in the+background does the same thing; editor and AI-assistant desktop apps are common+sources, and one of them can easily out-spawn PortOS several times over. Attribute+before you assume.++## Fix 1 (system-wide, fixes every app): stop the terminal handoff++Setting the default terminal to the classic console host removes step 3's+consequence for **everything on the machine**, not just PortOS. Windows still+allocates a console, but draws it with `conhost.exe`, which does not COM-activate+Windows Terminal and does not steal focus.++```bash+npm run fix:windows-console # set default terminal to Windows Console Host+npm run fix:windows-console -- --show # print the current setting only+npm run fix:windows-console -- --revert # restore "Let Windows decide"+```++The equivalent manual route is **Settings → System → For developers → Terminal+→ Windows Console Host**, or in Windows Terminal, **Settings → Startup →+Default terminal application**.++This only writes `HKCU\Console\%%Startup` for the current user, changes no+system state, and takes effect for newly launched console apps. It does not stop+you from using Windows Terminal — it only stops apps from being *forced* into it+when they allocate a console programmatically.++## Fix 2 (PortOS-side): every spawn defaults to hidden++PortOS server code must not import `child_process` directly. It imports+[`server/lib/childProcess.js`](../server/lib/childProcess.js), a drop-in+replacement that defaults `windowsHide: true` (i.e. `CREATE_NO_WINDOW`) on every+`spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` /+`execFileSync`. `exec` and `execFile` keep their `util.promisify.custom` hooks,+so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit+`windowsHide: false` is honored.++`server/lib/childProcess.guards.test.js` fails the build if a server runtime file+imports `child_process` directly. This bug was fixed twice before by sweeping+`windowsHide: true` across call sites (v1.5.x, v1.6.7) and regressed both times,+because nothing prevented the next new file from omitting it. Owning the import+is the version of the rule that new code cannot silently skip.++Carve-outs, all enforced rather than exempted. Trees that cannot import the+wrapper are held to a **per-call-site** rule instead — every `spawn`/`exec`+family call must carry `windowsHide` itself:++- **`server/lib/aiToolkit/`** is vendored and contractually self-contained (no+ imports out to other PortOS modules), so it applies `windowsHide` inline.+- **`autofixer/` and `browser/`** are separate packages with their own+ `package.json`, so they cannot reach `server/lib/` either — but both are+ PM2-forked apps (`ecosystem.config.cjs`), which puts them in exactly the+ console-less blast radius above.++The per-call-site check is deliberate: a file-level "mentions `windowsHide`+somewhere" test is the weak form of the rule, and would let a second spawn added+to an already-compliant file through unchecked.+- **`shell: true` with a bare `pm2`** is banned separately, but *not* because+ `windowsHide` fails there. Measured on Windows 11: eight `shell: true` spawns+ from a console-less parent produce eight `OpenConsole.exe -Embedding`+ handoffs without `windowsHide`, and zero with it — `shell: true` makes+ `cmd.exe` the direct child, so `CREATE_NO_WINDOW` applies to it and the+ `pm2.cmd`/`node` grandchildren inherit its hidden console. The v1.6.7 sites+ flashed because they passed no `windowsHide` at all. The rule stands on its+ other merits: `execPm2` / `spawnPm2` (`server/services/pm2.js`) exec+ `node pm2/bin/pm2` directly, dropping two process hops and the PATH ambiguity+ of resolving a bare `pm2` through a shell.++ This distinction matters. If you believe `windowsHide` is unreliable, you+ start layering redundant per-call special cases on top of the wrapper — which+ is the failure mode the wrapper exists to end.++### What is *not* affected++**node-pty / ConPTY sessions.** A PTY does allocate its own console host, but+always with `--headless`, which never triggers the terminal handoff and never+draws a window. Web shells and TUI agent sessions were never part of this+symptom, and there is nothing to change there.++That holds because the pinned node-pty is ConPTY-only — its Windows agent has+no winpty fallback path. It is a property of this dependency, not of PTYs in+general, so re-check it on a node-pty major bump. All PTY spawns go through the+one module (`server/services/shell.js`, `server/cos-runner/index.js`,+`server/lib/tuiPromptRunner.js`, `server/lib/tuiUsageScrape.js`), so the blast+radius of that assumption is real.++**`detached: true` spawns.** Windows ignores `CREATE_NO_WINDOW` when+`DETACHED_PROCESS` is set. Those children are safe because they get *no* console+at all — not because `windowsHide` is doing the work. Don't remove `detached`+from a spawn and assume the flag was what protected it.++## Does PortOS need to be launched differently from PowerShell?++**No.** How you start PortOS makes no difference — `npm start`, `pm2 start`, a+shortcut, or a PowerShell profile all end at the same place, because the spawns+that flash come from PM2-forked children, and PM2 forks are console-less no+matter what launched the daemon. Running the launch command from an elevated+prompt, from Windows Terminal, or with `-WindowStyle Hidden` changes nothing.++The two fixes above are the whole story: Fix 1 changes what Windows does with a+newly allocated console, and Fix 2 stops PortOS from allocating one at all.diff --git a/package.json b/package.jsonindex f4af93ba61..5f4f65e69c 100644--- a/package.json+++ b/package.json@@ -33,6 +33,7 @@"test:db": "npm run test:db --prefix server","setup:llm": "node scripts/setup-llm.js","setup:browser": "node scripts/setup-browser.js",+ "fix:windows-console": "node scripts/fix-windows-console.js","setup:cert": "node scripts/setup-cert.js","setup:ghostty": "node scripts/setup-ghostty.js","setup:hooks": "bash scripts/setup-git-hooks.sh",diff --git a/scripts/fix-windows-console.js b/scripts/fix-windows-console.jsnew file mode 100644index 0000000000..3c1375d2ab--- /dev/null+++ b/scripts/fix-windows-console.js@@ -0,0 +1,114 @@+#!/usr/bin/env node+/**+ * Point Windows' "Default terminal application" at the classic console host so+ * programmatically-allocated consoles stop being handed off to Windows Terminal.+ *+ * Background: a console-less process (every PM2 fork, so all of PortOS) that+ * spawns a console child makes Windows allocate a new console. Under the+ * default terminal setting that allocation is COM-handed to Windows Terminal,+ * which starts `OpenConsole.exe -Embedding` plus a terminal window that takes+ * foreground focus and dies with the child. Pointing the delegation at+ * conhost.exe keeps the console headless-ish and non-stealing.+ *+ * This is the machine-wide half of the fix and helps every app on the box, not+ * just PortOS — see docs/WINDOWS_CONSOLE.md. The PortOS half (defaulting+ * `windowsHide: true` on every spawn) lives in server/lib/childProcess.js.+ *+ * Writes only HKCU\Console\%%Startup for the current user. Reversible with+ * --revert, inspectable with --show.+ */++import { execFileSync } from '../server/lib/childProcess.js';++// Console-host delegation CLSIDs. These identify which COM server Windows hands+// a newly allocated console to.+const CONHOST = '{B23D10C0-E52E-411E-9D5B-C09FDF709C7D}'; // Windows Console Host+const LET_WINDOWS_DECIDE = '{00000000-0000-0000-0000-000000000000}'; // → Windows Terminal on Win11++const KEY = 'HKCU\\Console\\%%Startup';+const VALUES = ['DelegationConsole', 'DelegationTerminal'];++const args = process.argv.slice(2);+const has = (flag) => args.includes(flag);++if (process.platform !== 'win32') {+ console.log('ℹ️ Not Windows — nothing to do (the console handoff is Windows-only)');+ process.exit(0);+}++/**+ * Read both delegation values in one `reg query`. Values are absent entirely on+ * a machine that has never changed the setting, which reads the same as "Let+ * Windows decide" and is reported as such.+ * @returns {Record<string, string|null>}+ */+function readValues() {+ // try/catch is required: `reg query` exits non-zero when the key does not+ // exist, which is a normal state, not an error. This runs outside Express, so+ // an uncaught throw would take the process down rather than reach middleware.+ let out = '';+ try {+ out = execFileSync('reg', ['query', KEY], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ } catch {+ out = '';+ }+ return Object.fromEntries(+ VALUES.map((name) => {+ const match = out.match(new RegExp(`${name}\\s+REG_SZ\\s+(\\{[0-9A-Fa-f-]+\\})`, 'i'));+ return [name, match ? match[1].toUpperCase() : null];+ })+ );+}++/**+ * @param {string} name+ * @param {string} guid+ */+function writeValue(name, guid) {+ execFileSync('reg', ['add', KEY, '/v', name, '/t', 'REG_SZ', '/d', guid, '/f'], {+ stdio: ['ignore', 'ignore', 'pipe'],+ });+}++/**+ * Human-readable name for a delegation CLSID.+ * @param {string|null} guid+ * @returns {string}+ */+function describe(guid) {+ if (guid === null) return 'not set (Windows default → Windows Terminal)';+ if (guid === CONHOST) return 'Windows Console Host (conhost.exe)';+ if (guid === LET_WINDOWS_DECIDE) return 'Let Windows decide (→ Windows Terminal on Windows 11)';+ return `${guid} (a third-party terminal)`;+}++function report(label) {+ const values = readValues();+ console.log(`📋 ${label}:`);+ for (const name of VALUES) console.log(` ${name} = ${describe(values[name])}`);+}++if (has('--show')) {+ report('Default terminal application');+ process.exit(0);+}++const revert = has('--revert');+const target = revert ? LET_WINDOWS_DECIDE : CONHOST;++report('Before');+for (const name of VALUES) writeValue(name, target);+report('After');++if (revert) {+ console.log('↩️ Reverted to "Let Windows decide" — console windows may flash and steal focus again');+} else {+ console.log('✅ Default terminal set to Windows Console Host');+ console.log(' New console apps stop handing off to Windows Terminal. Already-running');+ console.log(' processes keep their current console; restart PortOS (or PM2) to apply.');+ console.log(' You can still open Windows Terminal yourself — this only changes what');+ console.log(' happens when a program allocates a console on its own.');+}diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex e8c61244e1..9d87a5ed58 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -9,7 +9,7 @@*/import express from 'express';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import * as pty from 'node-pty';import { join, basename } from 'path';import { writeFile, readFile } from 'fs/promises';diff --git a/server/cos-runner/processStats.js b/server/cos-runner/processStats.jsindex 3c8c5d954f..b95cf1240c 100644--- a/server/cos-runner/processStats.js+++ b/server/cos-runner/processStats.js@@ -7,7 +7,7 @@* isolated `portos-cos` PM2 process stays standalone.*/-import { exec } from 'child_process';+import { exec } from '../lib/childProcess.js';import { promisify } from 'util';const execAsync = promisify(exec);diff --git a/server/cos-runner/processStats.test.js b/server/cos-runner/processStats.test.jsindex 92f66eabeb..c75aa5e517 100644--- a/server/cos-runner/processStats.test.js+++ b/server/cos-runner/processStats.test.js@@ -44,7 +44,7 @@ describe('cos-runner processStats', () => {const loadWithMockedExec = async (stdout) => {const calls = [];vi.resetModules();- vi.doMock('child_process', () => ({+ vi.doMock('../lib/childProcess.js', () => ({exec: (cmd, _opts, cb) => { calls.push(cmd); cb(null, { stdout, stderr: '' }); },}));vi.stubGlobal('process', { ...process, platform: 'win32' });@@ -91,7 +91,7 @@ describe('cos-runner processStats', () => {const loadWithMockedExec = async (stdout) => {const calls = [];vi.resetModules();- vi.doMock('child_process', () => ({+ vi.doMock('../lib/childProcess.js', () => ({exec: (cmd, _opts, cb) => { calls.push(cmd); cb(null, { stdout, stderr: '' }); },}));vi.stubGlobal('process', { ...process, platform: 'win32' });diff --git a/server/lib/README.md b/server/lib/README.mdindex 2597789dde..4cc384858a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -189,6 +189,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. `toBashPath(p)` — the companion path rule: bash reads backslashes as escapes, so a Windows path must reach it with forward slashes. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |+| `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. || `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. |diff --git a/server/lib/agentGuard/index.test.js b/server/lib/agentGuard/index.test.jsindex 5b0839e35d..a8871c5695 100644--- a/server/lib/agentGuard/index.test.js+++ b/server/lib/agentGuard/index.test.js@@ -1,7 +1,7 @@import { describe, it, expect, beforeAll, afterAll } from 'vitest';import { delimiter, dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';-import { spawnSync } from 'node:child_process';+import { spawnSync } from '../childProcess.js';import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, chmodSync, statSync, symlinkSync } from 'node:fs';import { tmpdir } from 'node:os';import { agentGuardEnv, AGENT_GUARD_BIN } from './index.js';diff --git a/server/lib/aiToolkit/providers.cliPathResolve.test.js b/server/lib/aiToolkit/providers.cliPathResolve.test.jsindex f738a51c40..d58d251116 100644--- a/server/lib/aiToolkit/providers.cliPathResolve.test.js+++ b/server/lib/aiToolkit/providers.cliPathResolve.test.js@@ -123,8 +123,11 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>// Node's documented safe pattern (no shell:true, no DEP0190 hazard).expect(versionCall?.[0]).toBe('cmd.exe');expect(versionCall?.[1]).toEqual(['/c', join(fakePathDir, 'opencode.cmd'), '--version']);- expect(versionCall?.length).toBe(3);- expect(typeof versionCall?.[2]).toBe('function');+ // (file, args, options, callback) — the options slot carries windowsHide so+ // this probe can't pop a console window out of a PM2 fork on Windows.+ expect(versionCall?.length).toBe(4);+ expect(versionCall?.[2]).toMatchObject({ windowsHide: true });+ expect(typeof versionCall?.[3]).toBe('function');});it('falls back to the where-resolved path when no extension-bearing match exists on PATH', async () => {diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 3606ed7b4a..975bdd4908 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -107,7 +107,15 @@ function escapeCmdMetacharsIfUnquoted(value) {return str.replace(CMD_METACHAR_RE, '^$&');}-const execFileAsync = promisify(execFile);+// windowsHide is applied here rather than by importing server/lib/childProcess.js:+// the aiToolkit is contractually self-contained (see aiToolkit/CLAUDE.md), so it+// carries its own copy of the default. Without it, every CLI probe below spawns+// a console from PortOS's console-less PM2 fork, which Windows hands off to+// Windows Terminal as a focus-stealing window. See docs/WINDOWS_CONSOLE.md.+// Spread last so an explicit windowsHide: false still wins, matching the+// contract server/lib/childProcess.js states.+const execFileAsync = (file, args, options) =>+ promisify(execFile)(file, args, { windowsHide: true, ...options });// Tool-use (function-calling) capable model families. Inlined here because the// aiToolkit is self-contained (no imports out to server/lib). MIRROR ofdiff --git a/server/lib/bashResolver.js b/server/lib/bashResolver.jsindex e5677af16b..541bd29fe9 100644--- a/server/lib/bashResolver.js+++ b/server/lib/bashResolver.js@@ -29,7 +29,7 @@import { existsSync } from 'fs';import { join, dirname } from 'path';-import { execFileSync } from 'child_process';+import { execFileSync } from './childProcess.js';const IS_WIN32 = process.platform === 'win32';diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex 987e8d38dc..6e9e969575 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -1,4 +1,4 @@-import { spawn, ChildProcess } from 'child_process';+import { spawn, ChildProcess } from './childProcess.js';import { existsSync } from 'fs';import { delimiter, isAbsolute, join } from 'path';import { withSpawnCwdEnv } from './spawnCwd.js';diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 73b54e4014..9f4981fe75 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';-import { ChildProcess } from 'child_process';+import { ChildProcess } from './childProcess.js';import { mkdtemp, rm, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';@@ -11,7 +11,7 @@ import { tmpdir } from 'os';// needs the real `ChildProcess` export; a from-scratch replacement object// (no `ChildProcess` key) would make that check throw on an actual win32 run.const spawnMock = vi.fn();-vi.mock('child_process', async (importOriginal) => {+vi.mock('./childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: (...a) => spawnMock(...a) };});diff --git a/server/lib/childProcess.guards.test.js b/server/lib/childProcess.guards.test.jsnew file mode 100644index 0000000000..49e3e5765f--- /dev/null+++ b/server/lib/childProcess.guards.test.js@@ -0,0 +1,219 @@+import { describe, it, expect } from 'vitest';+import { join } from 'node:path';+import { collectServerSources, readServerSource, SERVER_DIR } from './testHelper.js';++// Windows hands a newly allocated console off to Windows Terminal when a+// console-less parent (every PM2 fork, which is all of PortOS) spawns a console+// child without CREATE_NO_WINDOW — a window that appears, steals foreground+// focus, and dies with the child. `windowsHide: true` suppresses it.+//+// This guard exists because sweeping `windowsHide: true` across call sites is+// what v1.5.x and v1.6.7 already did, and it regressed both times as new code+// landed with a fresh `import { spawn } from 'child_process'`. Owning the+// import is the only form of the rule a new file cannot silently skip.+// Background: docs/WINDOWS_CONSOLE.md.++const WRAPPER = 'lib/childProcess.js';++// Trees that cannot import the wrapper, and so are held to the weaker+// per-call-site rule instead. `aiToolkit/` is vendored and contractually+// self-contained (aiToolkit/CLAUDE.md: no imports out to other PortOS modules).+// `autofixer/` and `browser/` are separate packages with their own+// package.json — but they ARE PM2-forked apps (ecosystem.config.cjs), so they+// sit in exactly the console-less blast radius this guard covers.+const CALL_SITE_TREES = ['lib/aiToolkit/', '../autofixer/', '../browser/'];++// collectServerSources returns paths relative to server/, so a sibling package+// walked from SERVER_DIR comes back as '../autofixer/…' and readServerSource+// resolves it by joining back onto SERVER_DIR.+const SIBLING_PACKAGES = ['../autofixer', '../browser'];++const SPAWN_FNS = ['spawn', 'spawnSync', 'fork', 'exec', 'execSync', 'execFile', 'execFileSync'];++/**+ * Blank comment lines while preserving line count, so a rule can be *described*+ * in a comment without the guard flagging the description as a violation+ * (`cosHealthMonitor.js` explains the pm2 rule using the banned pattern).+ * Line-based on purpose: every real `child_process` mention outside the wrapper+ * is a JSDoc `@param {import('child_process').ChildProcess}` line, and a false+ * positive here is loud and one line to fix.+ * @param {string} src+ * @returns {string[]}+ */+function blankComments(src) {+ return src.split('\n').map((line) => (/^\s*(\/\/|\*|\/\*)/.test(line) ? '' : line));+}++/**+ * Extract whole call expressions by name, brace-balanced so a call wrapped+ * across several lines is captured entire. A per-line scan misses exactly the+ * multi-line shape prettier produces for a call with several arguments — which+ * is the shape one of the two pm2 regressions this guard was written for+ * actually had.+ * @param {string[]} lines - comment-blanked source lines+ * @param {string[]|null} names - function names to match, or null for any callee+ * @returns {{name: string, text: string, line: number}[]}+ */+function callExpressions(lines, names) {+ const src = lines.join('\n');+ const pattern = new RegExp(+ '(?<![.\\w])(' + (names ? names.join('|') : '[A-Za-z_$][\\w$]*') + ')\\s*\\(',+ 'g'+ );+ const found = [];+ let match;+ while ((match = pattern.exec(src))) {+ let depth = 0;+ let end = src.length;+ for (let i = match.index + match[0].length - 1; i < src.length; i++) {+ if (src[i] === '(') depth++;+ else if (src[i] === ')' && --depth === 0) {+ end = i;+ break;+ }+ }+ found.push({+ name: match[1],+ text: src.slice(match.index, end + 1),+ line: src.slice(0, match.index).split('\n').length,+ });+ }+ return found;+}++const IMPORTS_CHILD_PROCESS = /(?:from\s*|import\s*\(\s*)['"](?:node:)?child_process['"]/;++const allFiles = [+ ...collectServerSources(),+ ...SIBLING_PACKAGES.flatMap((pkg) => collectServerSources(join(SERVER_DIR, pkg))),+];++// One read pass, then a raw-source pre-filter, then parse only what survives.+// The tree is ~1500 files / ~20 MB while fewer than 20 mention child_process or+// pm2 at all, so blanking every file for every rule would add about a second of+// pure CPU to `npm test` for nothing. A hit inside a comment survives the+// pre-filter and is then correctly discarded by blankComments, so narrowing+// this way cannot hide a violation.+const candidates = allFiles+ .map((rel) => ({ rel, raw: readServerSource(rel) }))+ .filter(({ raw }) => raw.includes('child_process') || /['"]pm2['"]/.test(raw));++const parsed = new Map(candidates.map(({ rel, raw }) => [rel, blankComments(raw)]));++const inCallSiteTree = (rel) => CALL_SITE_TREES.some((t) => rel.startsWith(t));++describe('comment blanking', () => {+ // Every rule below filters through blankComments, so a stripper that blanked+ // too much would silently turn all of them into no-ops.+ it('blanks comment lines and keeps code, preserving line numbers', () => {+ const lines = blankComments(+ [+ "import { spawn } from 'child_process';",+ '// import { spawn } from "child_process";',+ " * @param {import('child_process').ChildProcess} child",+ "const url = 'https://example.com';",+ ].join('\n')+ );+ expect(lines).toHaveLength(4);+ expect(lines[0]).toContain("from 'child_process'");+ expect(lines[1]).toBe('');+ // A JSDoc type position is not a runtime import; every file with a+ // ChildProcess-typed param would fail the guard otherwise.+ expect(lines[2]).toBe('');+ expect(lines[3]).toContain('https://example.com');+ });+});++describe('call-expression extraction', () => {+ it('captures a call split across lines', () => {+ const calls = callExpressions(+ blankComments("await execFile('pm2', ['logs'], {\n timeout: 5,\n shell: true\n});"),+ ['execFile']+ );+ expect(calls).toHaveLength(1);+ // The single most important property: a per-line scan sees `shell: true`+ // and `'pm2'` on different lines and matches neither.+ expect(calls[0].text).toContain("'pm2'");+ expect(calls[0].text).toContain('shell: true');+ });++ it('does not match a method call that merely ends in the same name', () => {+ expect(callExpressions(['foo.spawn(1)'], ['spawn'])).toEqual([]);+ });+});++describe('child_process import guard', () => {+ it('scans a non-trivial set of files (guard is not vacuous)', () => {+ expect(allFiles.length).toBeGreaterThan(50);+ expect(candidates.length).toBeGreaterThan(5);+ // Each sibling package must actually be reached. If one is renamed or moved,+ // its rule below would iterate nothing and pass green forever.+ for (const tree of CALL_SITE_TREES) {+ expect(+ candidates.filter(({ rel }) => rel.startsWith(tree)).length,+ `no spawning files found under ${tree} — has it moved?`+ ).toBeGreaterThan(0);+ }+ });++ it('routes every server runtime spawn through server/lib/childProcess.js', () => {+ const offenders = candidates+ .map(({ rel }) => rel)+ .filter((rel) => rel !== WRAPPER && !inCallSiteTree(rel))+ .filter((rel) => parsed.get(rel).some((line) => IMPORTS_CHILD_PROCESS.test(line)));++ expect(+ offenders,+ 'These files import child_process directly, so their spawns default to a\n' ++ 'visible console on Windows. Import from server/lib/childProcess.js instead:\n' ++ offenders.map((f) => ` - ${f}`).join('\n')+ ).toEqual([]);+ });++ it('keeps windowsHide on every spawn in trees that cannot import the wrapper', () => {+ // Per call site, not per file. A file-level "mentions windowsHide somewhere"+ // check is the weak form of exactly this rule: aiToolkit/runner.js already+ // contains the string, so a third spawn added there would never be checked —+ // reintroducing, at smaller scale, the failure mode the wrapper exists to end.+ const offenders = [];+ for (const { rel } of candidates.filter(({ rel }) => inCallSiteTree(rel))) {+ for (const call of callExpressions(parsed.get(rel), SPAWN_FNS)) {+ // Only flag real spawns — these trees also define same-named locals and+ // re-export wrappers that forward options they never author.+ if (!/windowsHide/.test(call.text)) offenders.push(`${rel}:${call.line} ${call.name}(…)`);+ }+ }++ expect(+ offenders,+ 'These spawn without windowsHide and cannot inherit the wrapper default,\n' ++ 'so each must set it inline:\n' ++ offenders.map((o) => ` - ${o}`).join('\n')+ ).toEqual([]);+ });++ it('never resolves pm2 through a shell', () => {+ // `shell: true` on a bare `pm2` picks up pm2.cmd, adding a cmd.exe -> pm2.cmd+ // -> node hop that v1.6.7 removed. windowsHide does suppress the window+ // either way, but execPm2/spawnPm2 (services/pm2.js) exec `node pm2/bin/pm2`+ // directly and drop two process hops plus the PATH ambiguity.+ // Any callee, not just the child_process names: the regression this rule+ // exists for went through `execFileAsync`, a promisified local alias, and+ // most spawn sites in this codebase are reached through one. The `'pm2'`+ // literal plus `shell:` in the same call is a narrow enough filter that+ // widening the callee costs nothing.+ const offenders = [];+ for (const { rel } of candidates) {+ for (const call of callExpressions(parsed.get(rel), null)) {+ if (/['"]pm2['"]/.test(call.text) && /shell\s*:/.test(call.text)) {+ offenders.push(`${rel}:${call.line} ${call.name}(…)`);+ }+ }+ }++ expect(+ offenders,+ `pm2 invoked through a shell:\n${offenders.map((o) => ` - ${o}`).join('\n')}`+ ).toEqual([]);+ });+});diff --git a/server/lib/childProcess.js b/server/lib/childProcess.jsnew file mode 100644index 0000000000..e694e25edf--- /dev/null+++ b/server/lib/childProcess.js@@ -0,0 +1,113 @@+/**+ * Drop-in `child_process` replacement that defaults every spawn to+ * `windowsHide: true` (`CREATE_NO_WINDOW`), so a console-less PM2 fork never+ * makes Windows allocate a visible console for a child. An explicit+ * `windowsHide: false` is always respected — the default only fills the gap.+ *+ * Server runtime code must import from here rather than `child_process`;+ * `childProcess.guards.test.js` enforces that. Why a wrapper instead of another+ * per-call-site sweep, what the console handoff actually is, and what is out of+ * scope: docs/WINDOWS_CONSOLE.md.+ *+ * Note `CREATE_NO_WINDOW` is ignored for `detached: true` spawns — those are+ * safe because `DETACHED_PROCESS` gives the child no console at all, not+ * because this default is doing the work.+ */++import {+ ChildProcess,+ exec as nodeExec,+ execFile as nodeExecFile,+ execFileSync as nodeExecFileSync,+ execSync as nodeExecSync,+ fork as nodeFork,+ spawn as nodeSpawn,+ spawnSync as nodeSpawnSync,+} from 'node:child_process';+import { promisify } from 'node:util';++export { ChildProcess };++/**+ * Fill in `windowsHide: true` unless the caller stated an opinion.+ * @param {object} [options]+ * @returns {object}+ */+function withHide(options) {+ if (options && Object.hasOwn(options, 'windowsHide')) return options;+ return { ...options, windowsHide: true };+}++/**+ * Normalize any of node's `(…[, args][, options][, callback])` overloads into+ * the positional list it expects, with `windowsHide` injected. Classifying by+ * type rather than position is what lets one helper serve all of them — the+ * spawn family simply never passes a callback.+ * @param {Array} rest - every argument after the command/file/module+ * @returns {Array}+ */+function normalize(rest) {+ let args;+ let options;+ let callback;+ for (const value of rest) {+ if (Array.isArray(value)) args = value;+ else if (typeof value === 'function') callback = value;+ else if (value && typeof value === 'object') options = value;+ }+ return [...(args ? [args] : []), withHide(options), ...(callback ? [callback] : [])];+}++/**+ * `child_process.spawn` with `windowsHide` defaulted on.+ * @returns {ChildProcess}+ */+export const spawn = (command, ...rest) => nodeSpawn(command, ...normalize(rest));++/** `child_process.spawnSync` with `windowsHide` defaulted on. */+export const spawnSync = (command, ...rest) => nodeSpawnSync(command, ...normalize(rest));++/**+ * `child_process.fork` with `windowsHide` defaulted on.+ * @returns {ChildProcess}+ */+export const fork = (modulePath, ...rest) => nodeFork(modulePath, ...normalize(rest));++/** `child_process.execSync` with `windowsHide` defaulted on. */+export const execSync = (command, options) => nodeExecSync(command, withHide(options));++/** `child_process.execFileSync` with `windowsHide` defaulted on. */+export const execFileSync = (file, ...rest) => nodeExecFileSync(file, ...normalize(rest));++/**+ * `child_process.exec` with `windowsHide` defaulted on.+ *+ * The `promisify.custom` hook delegates to the *native* promisified `exec`, so+ * `promisify(exec)` keeps resolving to `{ stdout, stderr }` (and keeps the+ * `.child` property on the returned promise). Without it, `promisify` would+ * fall back to generic callback wrapping and resolve to `stdout` alone,+ * silently breaking every `const { stdout } = await execAsync(...)` caller.+ *+ * Both hooks promisify at call time rather than at module load, so a test that+ * partially mocks child_process can't crash every importer on a binding it+ * never uses.+ * @returns {ChildProcess}+ */+export const exec = Object.assign(+ function exec(command, ...rest) {+ return nodeExec(command, ...normalize(rest));+ },+ { [promisify.custom]: (command, options) => promisify(nodeExec)(command, withHide(options)) }+);++/**+ * `child_process.execFile` with `windowsHide` defaulted on. Carries the same+ * `promisify.custom` delegation as `exec` above.+ * @returns {ChildProcess}+ */+export const execFile = Object.assign(+ function execFile(file, ...rest) {+ return nodeExecFile(file, ...normalize(rest));+ },+ { [promisify.custom]: (file, ...rest) => promisify(nodeExecFile)(file, ...normalize(rest)) }+);diff --git a/server/lib/childProcess.promisify.test.js b/server/lib/childProcess.promisify.test.jsnew file mode 100644index 0000000000..08c5a6a151--- /dev/null+++ b/server/lib/childProcess.promisify.test.js@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest';+import { promisify } from 'node:util';+import { exec, execFile, execFileSync, spawn } from './childProcess.js';++// Unmocked, against the real child_process, because the thing under test is the+// `promisify.custom` delegation — which only exists on node's own exec/execFile.+// A mocked child_process has no custom hook, so a mocked test would prove+// nothing about the shape real callers get back.+//+// `process.execPath -e` is the one command guaranteed present on every platform+// CI runs on.+const NODE = process.execPath;++describe('childProcess promisify fidelity', () => {+ it('resolves promisify(execFile) to { stdout, stderr }', async () => {+ const execFileAsync = promisify(execFile);+ const result = await execFileAsync(NODE, ['-e', 'process.stdout.write("hi")']);+ // The regression this guards: generic callback wrapping resolves to the+ // bare stdout string, so `const { stdout } = await …` yields undefined.+ expect(result).toEqual({ stdout: 'hi', stderr: '' });+ });++ it('resolves promisify(exec) to { stdout, stderr }', async () => {+ const execAsync = promisify(exec);+ const result = await execAsync(`"${NODE}" -e "process.stdout.write('hi')"`);+ expect(result.stdout).toBe('hi');+ expect(result.stderr).toBe('');+ });++ it('forwards options through the promisified path', async () => {+ const execFileAsync = promisify(execFile);+ const { stdout } = await execFileAsync(NODE, ['-e', 'process.stdout.write(process.env.PORTOS_PROBE)'], {+ env: { ...process.env, PORTOS_PROBE: 'forwarded' },+ });+ expect(stdout).toBe('forwarded');+ });++ it('rejects on a non-zero exit, preserving node error semantics', async () => {+ const execFileAsync = promisify(execFile);+ await expect(execFileAsync(NODE, ['-e', 'process.exit(3)'])).rejects.toMatchObject({ code: 3 });+ });+});++describe('childProcess real execution', () => {+ it('runs execFileSync and returns output', () => {+ const out = execFileSync(NODE, ['-e', 'process.stdout.write("sync")'], { encoding: 'utf8' });+ expect(out).toBe('sync');+ });++ it('runs spawn and streams stdout', async () => {+ const child = spawn(NODE, ['-e', 'process.stdout.write("streamed")']);+ const chunks = [];+ child.stdout.on('data', (c) => chunks.push(c));+ const code = await new Promise((resolve) => child.on('close', resolve));+ expect(code).toBe(0);+ expect(Buffer.concat(chunks).toString()).toBe('streamed');+ });+});diff --git a/server/lib/childProcess.test.js b/server/lib/childProcess.test.jsnew file mode 100644index 0000000000..e4cc542b90--- /dev/null+++ b/server/lib/childProcess.test.js@@ -0,0 +1,127 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Spy on the real child_process surface so each wrapper can be checked for the+// exact positional shape it forwards — the overload juggling is the part most+// likely to break a caller, not the flag itself. End-to-end promisify fidelity+// needs the unmocked module and lives in childProcess.promisify.test.js.+const calls = [];+vi.mock('node:child_process', () => {+ const record = (name) => (...args) => {+ calls.push({ name, args });+ return { name, args };+ };+ return {+ ChildProcess: class ChildProcess {},+ exec: record('exec'),+ execFile: record('execFile'),+ execFileSync: record('execFileSync'),+ execSync: record('execSync'),+ fork: record('fork'),+ spawn: record('spawn'),+ spawnSync: record('spawnSync'),+ };+});++const {+ exec,+ execFile,+ execFileSync,+ execSync,+ fork,+ spawn,+ spawnSync,+} = await import('./childProcess.js');++const lastOptions = () => {+ const { args } = calls.at(-1);+ return args.find((a) => a && !Array.isArray(a) && typeof a === 'object');+};++beforeEach(() => {+ calls.length = 0;+});++describe('childProcess windowsHide default', () => {+ it('injects windowsHide into every spawn family helper', () => {+ spawn('git', ['status']);+ expect(lastOptions()).toEqual({ windowsHide: true });++ spawnSync('git', ['status']);+ expect(lastOptions()).toEqual({ windowsHide: true });++ fork('./worker.js', ['--flag']);+ expect(lastOptions()).toEqual({ windowsHide: true });++ execSync('git status');+ expect(lastOptions()).toEqual({ windowsHide: true });++ execFileSync('git', ['status']);+ expect(lastOptions()).toEqual({ windowsHide: true });++ exec('git status');+ expect(lastOptions()).toEqual({ windowsHide: true });++ execFile('git', ['status']);+ expect(lastOptions()).toEqual({ windowsHide: true });+ });++ it('preserves caller options alongside the injected flag', () => {+ spawn('git', ['status'], { cwd: '/repo', stdio: 'pipe' });+ expect(lastOptions()).toEqual({ cwd: '/repo', stdio: 'pipe', windowsHide: true });+ });++ it('respects an explicit windowsHide: false', () => {+ // The default fills a gap; it must never override a stated intent.+ spawn('git', ['status'], { windowsHide: false });+ expect(lastOptions()).toEqual({ windowsHide: false });+ });++ it('does not mutate the caller-supplied options object', () => {+ const options = { cwd: '/repo' };+ spawn('git', ['status'], options);+ expect(options).toEqual({ cwd: '/repo' });+ });+});++describe('childProcess overload handling', () => {+ it('treats a non-array second argument as options, like node does', () => {+ spawn('git', { cwd: '/repo' });+ expect(calls.at(-1).args).toEqual(['git', { cwd: '/repo', windowsHide: true }]);+ });++ it('keeps the args array in its positional slot', () => {+ spawn('git', ['status', '--porcelain'], { cwd: '/repo' });+ expect(calls.at(-1).args).toEqual([+ 'git',+ ['status', '--porcelain'],+ { cwd: '/repo', windowsHide: true },+ ]);+ });++ it('handles exec(command, callback) without swallowing the callback', () => {+ const cb = () => {};+ exec('git status', cb);+ expect(calls.at(-1).args).toEqual(['git status', { windowsHide: true }, cb]);+ });++ it('handles every execFile overload', () => {+ const cb = () => {};++ execFile('git', cb);+ expect(calls.at(-1).args).toEqual(['git', { windowsHide: true }, cb]);++ execFile('git', ['status'], cb);+ expect(calls.at(-1).args).toEqual(['git', ['status'], { windowsHide: true }, cb]);++ execFile('git', { cwd: '/repo' });+ expect(calls.at(-1).args).toEqual(['git', { cwd: '/repo', windowsHide: true }]);++ execFile('git', ['status'], { cwd: '/repo' }, cb);+ expect(calls.at(-1).args).toEqual([+ 'git',+ ['status'],+ { cwd: '/repo', windowsHide: true },+ cb,+ ]);+ });+});diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex d6b01481f6..e795990f8f 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -16,7 +16,7 @@* lightweight cousin for fire-and-collect prompts.*/-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';import { buildCliChildEnv } from './cliChildEnv.js';diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.jsindex 0d54cc7844..dc695e95c7 100644--- a/server/lib/cliProviderRun.test.js+++ b/server/lib/cliProviderRun.test.js@@ -124,7 +124,7 @@ describe('runCliProviderPrompt', () => {// regardless of the host's exact PATH layout) so the round-trip still// completes — proves the resolved path, not the bare provider.command,// is what actually gets spawned.- const { execFileSync } = await import('child_process');+ const { execFileSync } = await import('./childProcess.js');const isWin = process.platform === 'win32';const catPath = isWin? execFileSync('where', ['node']).toString().split(/\r?\n/)[0].trim()diff --git a/server/lib/commandExists.js b/server/lib/commandExists.jsindex e91959cc8b..1f2f791e99 100644--- a/server/lib/commandExists.js+++ b/server/lib/commandExists.js@@ -1,4 +1,4 @@-import { execFile } from 'child_process';+import { execFile } from './childProcess.js';import { promisify } from 'util';const execFileAsync = promisify(execFile);diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.jsindex 10f620dbb8..8ab1aae5a7 100644--- a/server/lib/commandExists.test.js+++ b/server/lib/commandExists.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest'const execFileMock = { impl: (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' }) }-vi.mock('child_process', () => ({+vi.mock('./childProcess.js', () => ({execFile: (cmd, args, opts, cb) => execFileMock.impl(cmd, args, opts, cb),}))diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.jsindex 78c11a855a..b8b8f73ffd 100644--- a/server/lib/cudaCapability.js+++ b/server/lib/cudaCapability.js@@ -23,7 +23,7 @@* resolves — nothing throws into a route (CLAUDE.md child-process exception).*/-import { execFile } from 'node:child_process';+import { execFile } from './childProcess.js';/*** One CSV row per GPU: `<name>, <total VRAM in MiB>`. `nounits` strips the " MiB"diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.jsindex a99d51ef0e..9b422f949e 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -43,7 +43,7 @@// the supervisor records the exit status — exactly as if the original handle// had never gone away (#1332).-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { EventEmitter } from 'events';import { constants as osConstants } from 'os';import { join } from 'path';diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex d8b8f7d837..0e835842ea 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach, vi } from 'vitest';import { mkdir, mkdtemp, rm, stat, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';-import { ChildProcess, execFile } from 'child_process';+import { ChildProcess, execFile } from './childProcess.js';import { promisify } from 'util';import { pinPlatform } from './testHelper.js';import { killProcessTree } from './bufferedSpawn.js';diff --git a/server/lib/execGit.js b/server/lib/execGit.jsindex 072211e22d..0018000420 100644--- a/server/lib/execGit.js+++ b/server/lib/execGit.js@@ -3,7 +3,7 @@* to avoid a circular dependency (git.js imports worktreeManager.js).*/-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';/*** Execute a git command safely using spawn (prevents shell injection).diff --git a/server/lib/execGit.test.js b/server/lib/execGit.test.jsindex 5ca1788223..017959efbf 100644--- a/server/lib/execGit.test.js+++ b/server/lib/execGit.test.js@@ -1,11 +1,11 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';-vi.mock('child_process', () => ({+vi.mock('./childProcess.js', () => ({spawn: vi.fn()}));-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { execGit } from './execGit.js';const makeChild = () => {diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex ee7366b9e4..c07b7127e7 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -6,7 +6,7 @@* caching, or rename-safety semantics.*/-import { execFile, spawn } from 'child_process';+import { execFile, spawn } from './childProcess.js';import { existsSync, statSync } from 'fs';import { unlink, rename } from 'fs/promises';import { join, resolve as resolvePath, sep as PATH_SEP, dirname } from 'path';diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex bfe750948e..c7fe6d76da 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -6,7 +6,7 @@import { access, appendFile, chmod, mkdir, open, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';import { existsSync, statSync, createReadStream } from 'fs';-import { execFile } from 'child_process';+import { execFile } from './childProcess.js';import { promisify } from 'util';import { createHash, randomUUID } from 'crypto';import { join, dirname, basename, extname, resolve as resolvePath, sep as PATH_SEP } from 'path';diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.jsindex 1634ab5b3a..7a398c5666 100644--- a/server/lib/hfDownload.js+++ b/server/lib/hfDownload.js@@ -23,7 +23,7 @@// parseHfDownloadLine is the single decoder — downloadHfRepo and the tests// share it so a wire-shape change cannot drift between them.-import { spawn } from 'node:child_process';+import { spawn } from './childProcess.js';import { join } from 'node:path';import {resolveFlux2Python, isFlux2VenvHealthy,diff --git a/server/lib/icloudFile.js b/server/lib/icloudFile.jsindex edc04dc258..c2ff7a7f50 100644--- a/server/lib/icloudFile.js+++ b/server/lib/icloudFile.js@@ -124,7 +124,7 @@import { readFile, stat } from 'fs/promises';import { realpathSync } from 'fs';import { dirname } from 'path';-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { bufferedSpawn } from './bufferedSpawn.js';import { createSingleFlight } from './singleFlight.js';diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.jsindex 6f9ccb9686..c5abf2c6cb 100644--- a/server/lib/icloudFile.test.js+++ b/server/lib/icloudFile.test.js@@ -19,7 +19,7 @@ vi.mock('fs/promises', async (importOriginal) => ({readFile: (...args) => readFileMock(...args),}));-vi.mock('child_process', async (importOriginal) => ({+vi.mock('./childProcess.js', async (importOriginal) => ({...await importOriginal(),spawn: (...args) => spawnMock(...args),}));diff --git a/server/lib/index.js b/server/lib/index.jsindex 901f52bc64..55d012229b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -97,6 +97,7 @@ export * from './ansiStrip.js';// ANTIGRAVITY_CONFIGURED_DEFAULT, so a flat `export *` would trip the// barrel's duplicate-identifier collision check.export * as antigravity from './antigravity.js';+export * as childProcess from './childProcess.js';export * from './cliChildEnv.js';export * from './cliProviderArgs.js';export * from './cliProviderRun.js';diff --git a/server/lib/localMemory.js b/server/lib/localMemory.jsindex 0b4f81b634..d7a368a6f0 100644--- a/server/lib/localMemory.js+++ b/server/lib/localMemory.js@@ -1,6 +1,6 @@/** Shared best-effort local-model memory reclamation and headroom reporting. */-import { execFile } from 'child_process';+import { execFile } from './childProcess.js';import { platform, freemem, totalmem } from 'os';import { promisify } from 'util';import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload, getBaseUrl as ollamaBaseUrl } from '../services/ollamaManager.js';diff --git a/server/lib/memoryStats.js b/server/lib/memoryStats.jsindex d16a3b3f36..2500ef6b23 100644--- a/server/lib/memoryStats.js+++ b/server/lib/memoryStats.js@@ -1,5 +1,5 @@import os from 'os';-import { exec } from 'child_process';+import { exec } from './childProcess.js';import { promisify } from 'util';import { readFile } from 'fs/promises';diff --git a/server/lib/memoryStats.test.js b/server/lib/memoryStats.test.jsindex ef26bd55bb..973441c76b 100644--- a/server/lib/memoryStats.test.js+++ b/server/lib/memoryStats.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import os from 'os';-vi.mock('child_process', () => ({+vi.mock('./childProcess.js', () => ({exec: vi.fn()}));@@ -9,7 +9,7 @@ vi.mock('fs/promises', () => ({readFile: vi.fn()}));-const { exec } = await import('child_process');+const { exec } = await import('./childProcess.js');const { readFile } = await import('fs/promises');const { getMemoryStats, _resetMemoryStatsCache } = await import('./memoryStats.js');diff --git a/server/lib/openFolder.js b/server/lib/openFolder.jsindex e0a6b2068e..5beeb975c8 100644--- a/server/lib/openFolder.js+++ b/server/lib/openFolder.js@@ -8,7 +8,7 @@* logs rather than crashing the Node process.*/-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';/*** Open a local path in the system file manager (Finder / Explorer / Nautilus).diff --git a/server/lib/planIds.js b/server/lib/planIds.jsindex c78bd18e5a..b43d17de88 100644--- a/server/lib/planIds.js+++ b/server/lib/planIds.js@@ -24,7 +24,7 @@import { execGit } from './execGit.js';import { stripMarkdownEmphasis } from './markdownText.js';-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';const SLUG_MAX_LEN = 50;const CHECKBOX_RE = /^(?<indent>\s*)-\s+\[(?<box>[ xX])\]\s+(?:\[(?<id>[a-z0-9][a-z0-9-]*)\]\s+)?(?<rest>.*)$/;diff --git a/server/lib/planIds.prScan.test.js b/server/lib/planIds.prScan.test.jsindex 534a0c6d51..40bf5b312c 100644--- a/server/lib/planIds.prScan.test.js+++ b/server/lib/planIds.prScan.test.js@@ -11,7 +11,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { EventEmitter } from 'events';const spawnMock = vi.fn();-vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));+vi.mock('./childProcess.js', () => ({ spawn: (...args) => spawnMock(...args) }));const { listOpenPullRequestHeadRefs } = await import('./planIds.js');diff --git a/server/lib/planIds.test.js b/server/lib/planIds.test.jsindex a7d921ef99..d7ecc907a6 100644--- a/server/lib/planIds.test.js+++ b/server/lib/planIds.test.js@@ -5,7 +5,7 @@ const execGitMock = vi.hoisted(() => vi.fn());const spawnMock = vi.hoisted(() => vi.fn());vi.mock('./execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));-vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));+vi.mock('./childProcess.js', () => ({ spawn: (...args) => spawnMock(...args) }));import {slugify,diff --git a/server/lib/platform.js b/server/lib/platform.jsindex 842b4864d5..43b2f6816e 100644--- a/server/lib/platform.js+++ b/server/lib/platform.js@@ -1,4 +1,4 @@-import { exec, execSync } from 'child_process';+import { exec, execSync } from './childProcess.js';import { promisify } from 'util';const execAsync = promisify(exec);diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex 7abf9cd733..faeb9ab96b 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -10,7 +10,7 @@//// The Malloc* family is documented in libmalloc(3) and only affects macOS;// stripping the prefix is a no-op on Linux/Windows.-import { execFile, execFileSync } from 'child_process';+import { execFile, execFileSync } from './childProcess.js';import { promisify } from 'util';const execFileAsync = promisify(execFile);diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 8e1ece3b9c..d8775f9795 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -1,4 +1,4 @@-import { execFile, spawn } from 'node:child_process';+import { execFile, spawn } from './childProcess.js';import { existsSync, readdirSync } from 'node:fs';import { arch, homedir, platform } from 'node:os';import { dirname, join } from 'node:path';diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.jsindex 06121515da..2083103044 100644--- a/server/lib/pythonSetup.test.js+++ b/server/lib/pythonSetup.test.js@@ -48,8 +48,8 @@ vi.mock('node:fs', async () => {};});-vi.mock('node:child_process', async () => {- const actual = await vi.importActual('node:child_process');+vi.mock('./childProcess.js', async () => {+ const actual = await vi.importActual('./childProcess.js');const util = await vi.importActual('node:util');// `promisify(execFile)` uses execFile's util.promisify.custom symbol so the// resolved value is `{ stdout, stderr }` (not a bare string). Honor that ondiff --git a/server/lib/setupScriptRunner.js b/server/lib/setupScriptRunner.jsindex 529a41e5d0..e84b447ba2 100644--- a/server/lib/setupScriptRunner.js+++ b/server/lib/setupScriptRunner.js@@ -13,7 +13,7 @@* creating a venv.*/-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { join } from 'path';import { PATHS } from './fileUtils.js';import { resolveBashBinary, toBashPath } from './bashResolver.js';diff --git a/server/lib/setupScriptRunner.test.js b/server/lib/setupScriptRunner.test.jsindex 053aa95e6d..eb1367919f 100644--- a/server/lib/setupScriptRunner.test.js+++ b/server/lib/setupScriptRunner.test.js@@ -5,7 +5,7 @@ import { pinPlatform } from './testHelper.js';// Mock the collaborators so the behavior under test is observable without// launching bash, probing the filesystem for a Python, or firing a real kill.const spawnMock = vi.fn();-vi.mock('child_process', async (importOriginal) => {+vi.mock('./childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: (...a) => spawnMock(...a) };});diff --git a/server/lib/sidecarProcess.js b/server/lib/sidecarProcess.jsindex b379f347bf..0a6a77fcdc 100644--- a/server/lib/sidecarProcess.js+++ b/server/lib/sidecarProcess.js@@ -14,7 +14,7 @@* instead.*/-import { spawn } from 'child_process';+import { spawn } from './childProcess.js';import { safeChildProcessOptions } from './processEnv.js';// Only the trailing RESULT: line is ever consumed, and sidecar runs arediff --git a/server/lib/tailscale.js b/server/lib/tailscale.jsindex ef76182b3c..bf01e5b22c 100644--- a/server/lib/tailscale.js+++ b/server/lib/tailscale.js@@ -1,6 +1,6 @@import { existsSync } from 'fs';import { join, delimiter } from 'path';-import { execFile } from 'child_process';+import { execFile } from './childProcess.js';import { promisify } from 'util';import { safeJSONParse } from './fileUtils.js';diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.jsindex 402762bdad..1553274064 100644--- a/server/lib/tailscale.test.js+++ b/server/lib/tailscale.test.js@@ -5,12 +5,12 @@ vi.mock('fs', () => ({existsSync: vi.fn()}));-vi.mock('child_process', () => ({+vi.mock('./childProcess.js', () => ({execFile: vi.fn()}));import { existsSync } from 'fs';-import { execFile } from 'child_process';+import { execFile } from './childProcess.js';import {findTailscale,isSandboxedTailscale,diff --git a/server/lib/testDataIsolation.guards.test.js b/server/lib/testDataIsolation.guards.test.jsindex 9587de5a54..4cff265d49 100644--- a/server/lib/testDataIsolation.guards.test.js+++ b/server/lib/testDataIsolation.guards.test.js@@ -47,7 +47,7 @@*/import { describe, it, expect } from 'vitest';-import { execFileSync } from 'child_process';+import { execFileSync } from './childProcess.js';import { readFileSync } from 'fs';import { join, dirname, relative, sep } from 'path';import { fileURLToPath } from 'url';diff --git a/server/lib/testHelper.js b/server/lib/testHelper.jsindex 021ca35a1f..2a65e363c6 100644--- a/server/lib/testHelper.js+++ b/server/lib/testHelper.js@@ -10,7 +10,7 @@*/import { createServer } from 'http';-import { execFileSync } from 'child_process';+import { execFileSync } from './childProcess.js';import { homedir } from 'os';import { existsSync, readdirSync, readFileSync } from 'fs';import { join, relative } from 'path';diff --git a/server/lib/testHelper.test.js b/server/lib/testHelper.test.jsindex 4541b73a66..e07567557e 100644--- a/server/lib/testHelper.test.js+++ b/server/lib/testHelper.test.js@@ -9,7 +9,7 @@*/import { describe, it, expect, afterEach } from 'vitest';-import { execFileSync } from 'child_process';+import { execFileSync } from './childProcess.js';import { readFileSync } from 'fs';import { join, dirname, relative, sep } from 'path';import { fileURLToPath } from 'url';diff --git a/server/lib/zipWriter.test.js b/server/lib/zipWriter.test.jsindex a930f15526..eafca72e68 100644--- a/server/lib/zipWriter.test.js+++ b/server/lib/zipWriter.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { Readable, Writable } from 'stream';-import { execFileSync } from 'child_process';+import { execFileSync } from './childProcess.js';import { writeFileSync, mkdtempSync, rmSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';diff --git a/server/routes/apps/launch.js b/server/routes/apps/launch.jsindex 99b9185526..47593d9948 100644--- a/server/routes/apps/launch.js+++ b/server/routes/apps/launch.js@@ -9,7 +9,7 @@*/import { Router } from 'express';-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { basename, join } from 'path';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import { deriveProjectInfo } from '../../services/xcodeScripts.js';diff --git a/server/routes/apps/launch.test.js b/server/routes/apps/launch.test.jsindex 2d3672bec9..3e316a845f 100644--- a/server/routes/apps/launch.test.js+++ b/server/routes/apps/launch.test.js@@ -20,7 +20,7 @@ vi.mock('fs/promises', async (importOriginal) => ({access: vi.fn()}));-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: vi.fn(() => ({ on: vi.fn(), unref: vi.fn() }))}));@@ -28,7 +28,7 @@ vi.mock('child_process', async (importOriginal) => ({import * as appsService from '../../services/apps.js';import { deriveProjectInfo } from '../../services/xcodeScripts.js';import { access } from 'fs/promises';-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';const REPO_PATH = '/example/repos/my-client';diff --git a/server/routes/database.js b/server/routes/database.jsindex a50d8b7c29..3be7d62a1a 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -1,5 +1,5 @@import { Router } from 'express';-import { execFile, spawn } from 'child_process';+import { execFile, spawn } from '../lib/childProcess.js';import { existsSync, mkdirSync, createReadStream } from 'fs';import { join } from 'path';import { asyncHandler, ServerError } from '../lib/errorHandler.js';diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex e80be2b9de..dd26ccc130 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -34,7 +34,7 @@ vi.mock('../lib/db.js', () => ({}));// Mock child_process.execFile + spawn at the module level.-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,@@ -43,7 +43,7 @@ vi.mock('child_process', async (importOriginal) => {};});-import { execFile, spawn } from 'child_process';+import { execFile, spawn } from '../lib/childProcess.js';import { EventEmitter } from 'events';import { PassThrough } from 'stream';import { writeFileSync, mkdtempSync } from 'fs';diff --git a/server/routes/detect.js b/server/routes/detect.jsindex bf32c8f022..2ff89b7e7c 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { existsSync, realpathSync } from 'fs';import { readFile, stat } from 'fs/promises';import { join, resolve } from 'path';-import { exec } from 'child_process';+import { exec } from '../lib/childProcess.js';import { promisify } from 'util';import { execPm2 } from '../services/pm2.js';import { detectAppWithAi } from '../services/aiDetect.js';diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 866b7e60d3..7a51501194 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -6,7 +6,7 @@import { Router } from 'express';import { z } from 'zod';-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.js';import { promisify } from 'util';import * as instances from '../services/instances.js';import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 6d0974b92d..b0b1cb8e4d 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -3,7 +3,7 @@ import { writeFile, readdir, stat } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { join, dirname, resolve, sep } from 'path';import { fileURLToPath } from 'url';-import { exec, spawn } from 'child_process';+import { exec, spawn } from '../lib/childProcess.js';import { promisify } from 'util';import { platform } from 'os';import { createApp, getReservedPorts } from '../services/apps.js';diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.jsindex c2d7800394..5b20f05536 100644--- a/server/routes/scaffold.test.js+++ b/server/routes/scaffold.test.js@@ -28,7 +28,7 @@ vi.mock('fs', () => ({realpathSync: vi.fn((p) => p)}));-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({exec: vi.fn((cmd, opts, cb) => cb(null, { stdout: '', stderr: '' })),spawn: vi.fn(() => {const proc = new EventEmitter();@@ -59,7 +59,7 @@ vi.mock('../services/xcodeScripts.js', () => ({ toTargetName: vi.fn(() => 'TestAimport scaffoldRoutes from './scaffold.js';import { ensureDir } from '../lib/fileUtils.js';import { writeFile } from 'fs/promises';-import { spawn, exec } from 'child_process';+import { spawn, exec } from '../lib/childProcess.js';import { createApp } from '../services/apps.js';import { scaffoldVite } from './scaffoldVite.js';import { scaffoldPortOS } from './scaffoldPortOS.js';diff --git a/server/routes/scaffoldIOS.js b/server/routes/scaffoldIOS.jsindex 915358f4f4..2261a8e820 100644--- a/server/routes/scaffoldIOS.js+++ b/server/routes/scaffoldIOS.js@@ -1,6 +1,6 @@import { writeFile } from 'fs/promises';import { join } from 'path';-import { exec } from 'child_process';+import { exec } from '../lib/childProcess.js';import { promisify } from 'util';import { ensureDir, ensureDirs } from '../lib/fileUtils.js';import { XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, toBundleId, toTargetName } from '../services/xcodeScripts.js';diff --git a/server/routes/scaffoldVite.js b/server/routes/scaffoldVite.jsindex f3f5d17f1d..0a076c76ec 100644--- a/server/routes/scaffoldVite.js+++ b/server/routes/scaffoldVite.js@@ -1,7 +1,7 @@import { writeFile, readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { atomicWrite, ensureDir } from '../lib/fileUtils.js';import { safeJSONParse } from '../lib/fileUtils.js';diff --git a/server/routes/scaffoldXcode.js b/server/routes/scaffoldXcode.jsindex fda628f3fa..5aad451f9a 100644--- a/server/routes/scaffoldXcode.js+++ b/server/routes/scaffoldXcode.js@@ -1,6 +1,6 @@import { writeFile, chmod } from 'fs/promises';import { join } from 'path';-import { exec } from 'child_process';+import { exec } from '../lib/childProcess.js';import { promisify } from 'util';import { ensureDir, ensureDirs } from '../lib/fileUtils.js';import {diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 6bbe5ad5aa..5721120583 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -25,7 +25,7 @@ const installProcess = vi.hoisted(() => {};return { spawn, makeChild };});-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: installProcess.spawn,}));diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 67f55360e3..ff8086d327 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -8,7 +8,7 @@import { join } from 'path';import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { homedir } from 'os';import { cosEvents, emitLog } from './cosEvents.js';// The DEFINING module, not a barrel (#3450) — see the note indiff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 6c7b2b6f94..042b252b5e 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -83,7 +83,7 @@ vi.mock('../lib/bufferedSpawn.js', () => ({// Mock child_process.spawn to return a controllable fake processlet fakeProcess;-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({spawn: vi.fn(() => fakeProcess),// `execFile` is pulled in transitively by codeReview.js → lmStudioManager// (via `resolveReviewLoopOptions`'s dependency graph), even though this@@ -104,7 +104,7 @@ import { releaseRetryHold } from './agentWorktreeCleanup.js';// directly exercises the same code path production does.import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';import { existsSync } from 'fs';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';// Helper: feed the parser a sequence of stream-json linesdiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 14d33c8779..6eec6ceb9a 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -659,7 +659,7 @@ export async function getAgentProcessStats(agentId) {return { active: true, agentId, pid: null, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };}- const { exec } = await import('child_process');+ const { exec } = await import('../lib/childProcess.js');const { promisify } = await import('util');const execAsync = promisify(exec);diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 3addcf159c..8cb4c8848d 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -77,7 +77,7 @@ import {import { injectTuiModelAndEffort } from '../lib/providerVendors.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.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).diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex ad03696672..655c52e0d0 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -208,14 +208,14 @@ vi.mock('../lib/tuiHandshake.js', async (importOriginal) => {// (shellHasLiveChild). Default to an error callback so the probe resolves// "assume alive" (guard bypassed) for every test that doesn't exercise it —// the early-exit test below overrides this to report no child process.-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, execFile: vi.fn((_file, _args, _opts, cb) => cb(new Error('not mocked'))) };});import { existsSync } from 'fs';import { readFile } from 'fs/promises';-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';diff --git a/server/services/agents.js b/server/services/agents.jsindex 40e0845fd2..3161405669 100644--- a/server/services/agents.js+++ b/server/services/agents.js@@ -1,4 +1,4 @@-import { exec, execFile } from 'child_process';+import { exec, execFile } from '../lib/childProcess.js';import { promisify } from 'util';import { getSpawnedAgent } from './agentState.js';import { killAgent } from './agentOrchestrator.js';diff --git a/server/services/agents.test.js b/server/services/agents.test.jsindex 826dfa4dba..6e075b35ba 100644--- a/server/services/agents.test.js+++ b/server/services/agents.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock child_process before importing agents.js-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({exec: vi.fn(),// agents.js probes Windows via execFile(powershell, …) — see findWindowsProcesses.execFile: vi.fn()@@ -32,7 +32,7 @@ vi.mock('./agentOrchestrator.js', () => ({killAgent: vi.fn().mockResolvedValue({ success: true })}));-import { exec, execFile } from 'child_process';+import { exec, execFile } from '../lib/childProcess.js';import { pinPlatform } from '../lib/testHelper.js';import { registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import {diff --git a/server/services/appDeployer.js b/server/services/appDeployer.jsindex e89d4e450e..1fb251746b 100644--- a/server/services/appDeployer.js+++ b/server/services/appDeployer.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { join } from 'path';import { NON_PM2_TYPES } from './streamingDetect.js';diff --git a/server/services/askService.js b/server/services/askService.jsindex 124be788d1..00fd01aa58 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -571,7 +571,7 @@ async function* streamCompletion(provider, model, prompt, signal) {// because Ask prompts can run tens of thousands of characters once// sources + history are concatenated, which exceeds OS argv limits// (especially on Windows ~32k).- const { spawn } = await import('child_process');+ const { spawn } = await import('../lib/childProcess.js');let args = [...(provider.args || [])];// OpenCode runs headless via the `run` subcommand (reads the prompt from// stdin); ensure it leads the argv even if a customized/TUI provider configdiff --git a/server/services/askService.test.js b/server/services/askService.test.jsindex 0200aa473f..ba32c4758f 100644--- a/server/services/askService.test.js+++ b/server/services/askService.test.js@@ -10,7 +10,7 @@ vi.mock('./providers.js', () => ({getProviderById: vi.fn(),}));-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: vi.fn() };});@@ -52,7 +52,7 @@ vi.mock('./catalogDB.js', () => ({hybridSearchIngredients: vi.fn(),}));-const { spawn } = await import('child_process');+const { spawn } = await import('../lib/childProcess.js');const catalogDB = await import('./catalogDB.js');const memoryBackend = await import('./memoryBackend.js');const memoryEmbeddings = await import('./memoryEmbeddings.js');diff --git a/server/services/autonomousJobs/execution.js b/server/services/autonomousJobs/execution.jsindex 6ac5fee00d..97624a162d 100644--- a/server/services/autonomousJobs/execution.js+++ b/server/services/autonomousJobs/execution.js@@ -9,8 +9,7 @@* reject into the void. Behavior is preserved verbatim from the pre-split module.*/-import { spawn } from 'child_process'-import { PATHS } from '../../lib/fileUtils.js'+import { spawn } from '../../lib/childProcess.js';import { PATHS } from '../../lib/fileUtils.js'import { prepareCliSpawn, killProcessTree } from '../../lib/bufferedSpawn.js'import { withSpawnCwdEnv } from '../../lib/spawnCwd.js'import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../../lib/commandSecurity.js'diff --git a/server/services/autonomousJobs/execution.shellSpawn.test.js b/server/services/autonomousJobs/execution.shellSpawn.test.jsindex b2432e90d5..4af8891531 100644--- a/server/services/autonomousJobs/execution.shellSpawn.test.js+++ b/server/services/autonomousJobs/execution.shellSpawn.test.js@@ -18,7 +18,7 @@ const spawnMock = vi.fn()// Partial mock — other modules in this import graph (fileUtils) need the real// execFile/exec exports at load time.-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: (...args) => spawnMock(...args),}))diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.jsindex 5df46db617..b09fd7b595 100644--- a/server/services/autonomousJobs/scriptHandlers.js+++ b/server/services/autonomousJobs/scriptHandlers.js@@ -10,8 +10,7 @@ import { readdir, stat, rm } from 'fs/promises'import { join, dirname } from 'path'import { fileURLToPath } from 'url'import { existsSync } from 'fs'-import { spawn } from 'child_process'-import { DAY, PATHS, readJSONFile } from '../../lib/fileUtils.js'+import { spawn } from '../../lib/childProcess.js';import { DAY, PATHS, readJSONFile } from '../../lib/fileUtils.js'import { checkAndPrompt as autobiographyCheckAndPrompt } from '../autobiography.js'import { runGoalCheckIn } from '../goalCheckIn.js'import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'diff --git a/server/services/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.jsindex 039dbcfb98..24ace2dac7 100644--- a/server/services/autonomousJobs/selfDiagnostics.js+++ b/server/services/autonomousJobs/selfDiagnostics.js@@ -25,8 +25,7 @@* takes injectable deps so tests drive it without a live `gh` or filesystem.*/-import { spawn } from 'child_process'-import { PATHS, safeJSONParse } from '../../lib/fileUtils.js'+import { spawn } from '../../lib/childProcess.js';import { PATHS, safeJSONParse } from '../../lib/fileUtils.js'import { withSpawnCwdEnv } from '../../lib/spawnCwd.js'import { loadLearningData, computeWindowedStats } from '../taskLearning/store.js'diff --git a/server/services/backup.js b/server/services/backup.jsindex b1881b4891..58dc840e5c 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -6,7 +6,7 @@* Integrates with eventScheduler for daily cron scheduling.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { access, readdir, readFile, stat, unlink } from 'fs/promises';import { hostname } from 'os';import { join, resolve, relative, isAbsolute } from 'path';diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 6a4fb40aa4..13b952a7a8 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -61,10 +61,10 @@ vi.mock('./memoryBackend.js', () => ({import { EventEmitter } from 'events';import { createHash } from 'crypto';import { hostname } from 'os';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';// Partial mock: only override spawn. Preserve execFile et al. because// backup.js transitively imports fileUtils.js, which promisifies execFile.-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: vi.fn(),}));diff --git a/server/services/browserService.js b/server/services/browserService.jsindex 1b8197c855..9f4caee6b3 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -5,17 +5,14 @@*/import { readdir, stat, unlink } from 'fs/promises';-import { execFile } from 'child_process';-import { promisify } from 'util';import { join, basename, resolve, extname } from 'path';import { EventEmitter } from 'events';import { ensureDir, safeJSONParse, PATHS, tryReadFile, atomicWrite, sleep } from '../lib/fileUtils.js';import { normalizeBrowserConfig } from '../lib/browserConfig.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { readResponseJson } from '../lib/readResponseJson.js';+import { execPm2 } from './pm2.js';-const execFileAsync = promisify(execFile);-const PM2_SHELL = process.platform === 'win32';const PM2_SETTLE_MS = 1500;const HEALTH_TIMEOUT_MS = 3000;const NAVIGATE_TIMEOUT_MS = 10000;@@ -126,7 +123,10 @@ export async function getHealthStatus() {async function pm2Action(action, args) {console.log(`🌐 Browser PM2 ${action}: portos-browser`);- await execFileAsync('pm2', [action, ...args], { shell: PM2_SHELL });+ // execPm2 runs `node pm2/bin/pm2` directly. Resolving bare `pm2` through a+ // shell picks up pm2.cmd on Windows, and that cmd.exe hop opens a console+ // window out of PortOS's console-less PM2 fork — see docs/WINDOWS_CONSOLE.md.+ await execPm2([action, ...args]);console.log(`✅ Browser PM2 ${action} complete`);// Give PM2 a moment to settle@@ -153,7 +153,7 @@ export async function restartBrowser() {// ---------- PM2 status (process-level) ----------export async function getProcessStatus() {- const { stdout } = await execFileAsync('pm2', ['jlist'], { shell: PM2_SHELL });+ const { stdout } = await execPm2(['jlist']);const processes = safeJSONParse(stdout, [], { allowArray: true });const browserProc = processes.find(p => p.name === 'portos-browser');@@ -177,9 +177,8 @@ export async function getProcessStatus() {// ---------- Logs ----------export async function getRecentLogs(lines = 50) {- const { stdout, stderr } = await execFileAsync('pm2', ['logs', 'portos-browser', '--nostream', '--lines', String(lines)], {- timeout: LOGS_TIMEOUT_MS,- shell: PM2_SHELL+ const { stdout, stderr } = await execPm2(['logs', 'portos-browser', '--nostream', '--lines', String(lines)], {+ timeout: LOGS_TIMEOUT_MS}).catch(() => ({ stdout: '', stderr: '' }));return { stdout: stdout || '', stderr: stderr || '' };diff --git a/server/services/certProvisioner.js b/server/services/certProvisioner.jsindex 34f2552679..a3c9938c01 100644--- a/server/services/certProvisioner.js+++ b/server/services/certProvisioner.js@@ -17,7 +17,7 @@* process is still serving HTTP (e.g. provision was run twice without a* restart in between).*/-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.js';import { existsSync, mkdirSync, statSync } from 'fs';import { promisify } from 'util';import { PATHS, atomicWrite } from '../lib/fileUtils.js';diff --git a/server/services/certRenewer.js b/server/services/certRenewer.jsindex 3f48f97c29..4280a609e7 100644--- a/server/services/certRenewer.js+++ b/server/services/certRenewer.js@@ -11,7 +11,7 @@* Self-signed certs don't renew (the script issues 10-year certs for local* use); the renewer is a no-op in that mode.*/-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.js';import { existsSync, readFileSync, statSync } from 'fs';import { promisify } from 'util';import { PATHS } from '../lib/fileUtils.js';diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.jsindex 3d2d05c2d9..f57d1086cf 100644--- a/server/services/claudeCodeUsage.js+++ b/server/services/claudeCodeUsage.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync, lstatSync, readlinkSync, readFileSync } from 'fs';import { stripAnsi } from '../lib/ansiStrip.js';import { parseHumanReset } from '../lib/quotaReset.js';diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 6a35a16c6a..d2e85fa3e1 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// --- Mock every dependency agentWorktreeCleanup.js pulls in transitively ----vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({spawn: vi.fn(),execSync: vi.fn(),// `execFile` is pulled in transitively by codeReview.js → lmStudioManagerdiff --git a/server/services/commands.js b/server/services/commands.jsindex 2ad5b12065..339b49103e 100644--- a/server/services/commands.js+++ b/server/services/commands.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { logAction } from './history.js';import { ALLOWED_COMMANDS, validateCommand } from '../lib/commandSecurity.js';import { safeChildProcessEnv } from '../lib/processEnv.js';diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex ee5b40279d..6ef55663b0 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -6,8 +6,6 @@* snapshot to CoS state, and emits health events for downstream consumers.*/-import { execFile } from 'child_process';-import { promisify } from 'util';import { execPm2 } from './pm2.js';import { safeJSONParse } from '../lib/fileUtils.js';import { getMemoryStats } from '../lib/memoryStats.js';@@ -15,9 +13,6 @@ import { loadState, saveState, withStateLock, isDaemonRunning } from './cosStateimport { cosEvents, emitLog } from './cosEvents.js';import { annotateExpectedExit } from './apps.js';-const _execFileAsync = promisify(execFile);-const execFileAsync = (cmd, args, opts) => _execFileAsync(cmd, args, { ...opts, windowsHide: true });-/*** Run a daemon health check: inspect PM2 processes and memory, auto-restart* errored processes, store the result, and emit health events.@@ -90,7 +85,10 @@ export async function runHealthCheck() {emitLog('warn', `🔄 ${names.length} errored PM2 process(es) detected: ${names.join(', ')} — attempting restart`);const restartResults = await Promise.all(names.map(async (name) => {- const result = await execFileAsync('pm2', ['restart', name], { shell: process.platform === 'win32' }).catch(e => ({ stdout: '', stderr: e.message }));+ // 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}`);diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex 647943e82c..02d6c8bd77 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -29,8 +29,14 @@ 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).vi.mock('./pm2.js', () => ({- execPm2: vi.fn(async () => ({ stdout: mock.pm2Stdout }))+ execPm2: vi.fn(async (args) => (+ args[0] === 'jlist' ? { stdout: mock.pm2Stdout } : mock.restartImpl(args)+ ))}));vi.mock('../lib/memoryStats.js', () => ({@@ -42,12 +48,15 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn()}));-vi.mock('child_process', () => ({- execFile: (cmd, args, opts, cb) => mock.restartImpl(cmd, args, opts, cb)-}));-import { runHealthCheck, getHealthStatus } from './cosHealthMonitor.js';+// The restart assertions differ only in what they record off the pm2 argv —+// the whole argv, or just the process name.+const recordRestarts = (sink, pick = (args) => args) => async (args) => {+ sink.push(pick(args));+ return { stdout: 'restarted', stderr: '' };+};+const baseState = () => ({config: { maxTotalProcesses: 10, maxProcessMemoryMb: 1024 },stats: {}@@ -62,8 +71,8 @@ describe('cosHealthMonitor.runHealthCheck', () => {mock.events = [];mock.desktopProcessNames = new Set();mock.desktopLookupError = null;- // default execFile success- mock.restartImpl = (cmd, args, opts, cb) => cb(null, { stdout: 'restarted', stderr: '' });+ // default restart success+ mock.restartImpl = async () => ({ stdout: 'restarted', stderr: '' });});it('short-circuits when the daemon is not running', async () => {@@ -95,7 +104,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {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.restartImpl = (cmd, args, opts, cb) => cb(new Error('restart failed'), null);+ 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);expect(mock.events.some(e => e.name === 'health:critical')).toBe(true);@@ -113,10 +122,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {mock.desktopProcessNames = new Set(['game']);mock.pm2Stdout = erroredGame();const restarted = [];- mock.restartImpl = (cmd, args, opts, cb) => {- restarted.push(args);- cb(null, { stdout: 'restarted', stderr: '' });- };+ mock.restartImpl = recordRestarts(restarted);const { issues } = await runHealthCheck();@@ -168,10 +174,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {{ name: 'web', pm2_env: { status: 'errored' }, monit: { memory: 0 } }]);const restarted = [];- mock.restartImpl = (cmd, args, opts, cb) => {- restarted.push(args[1]);- cb(null, { stdout: 'restarted', stderr: '' });- };+ mock.restartImpl = recordRestarts(restarted, (args) => args[1]);const { metrics, issues } = await runHealthCheck();@@ -186,10 +189,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {{ name: 'web', pm2_env: { status: 'errored' }, monit: { memory: 0 } }]);const restarted = [];- mock.restartImpl = (cmd, args, opts, cb) => {- restarted.push(args[1]);- cb(null, { stdout: 'restarted', stderr: '' });- };+ mock.restartImpl = recordRestarts(restarted, (args) => args[1]);const { metrics } = await runHealthCheck();diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 81f1511a13..298ea9c23c 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -1,7 +1,7 @@import { readdir, stat, lstat, rm, writeFile as fsWriteFile } from 'fs/promises';import { join, relative, resolve, isAbsolute } from 'path';import { existsSync } from 'fs';-import { execFile } from 'child_process';+import { execFile } from '../lib/childProcess.js';import { promisify } from 'util';import { PATHS, ensureDir, isTopLevelEntryName } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';diff --git a/server/services/git.js b/server/services/git.jsindex 399ed89905..a2a5143066 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { join } from 'path';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';diff --git a/server/services/git.test.js b/server/services/git.test.jsindex 4de54da7f8..9b7ad6c88a 100644--- a/server/services/git.test.js+++ b/server/services/git.test.js@@ -94,7 +94,7 @@ describe('createPR', () => {});// Regression: `spawn` was previously used inside createPR but the- // `import { spawn } from 'child_process'` line was dropped during a refactor,+ // `import { spawn } from '../lib/childProcess.js'` line was dropped during a refactor,// causing every CoS-agent PR to fail with "spawn is not defined" and falling// back to the recovery-task path. The check below ensures a real call into// createPR doesn't throw a ReferenceError before completing.diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.jsindex 4fe36e2e9f..153c47abcc 100644--- a/server/services/github.ghHealth.test.js+++ b/server/services/github.ghHealth.test.js@@ -16,7 +16,7 @@ vi.mock('./settings.js', () => ({}));const spawnMock = vi.fn();-vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));+vi.mock('../lib/childProcess.js', () => ({ spawn: (...args) => spawnMock(...args) }));const {classifyGhProbe, ghRemedy, checkGhHealth, __resetGhHealthCache,diff --git a/server/services/github.js b/server/services/github.jsindex f5f1fd8837..5fd73d007a 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { join } from 'path';import { atomicWrite, readJSONFile, PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';diff --git a/server/services/github.test.js b/server/services/github.test.jsindex d7d0a47da9..07981da551 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -1,12 +1,12 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: vi.fn() };});-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { execGh, getPullRequestState } from './github.js';const makeChild = () => {diff --git a/server/services/githubCloner.js b/server/services/githubCloner.jsindex 987455d525..12fc8e750b 100644--- a/server/services/githubCloner.js+++ b/server/services/githubCloner.js@@ -5,7 +5,7 @@* Supports shallow clones to save space and provides progress tracking.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { join } from 'path';import { ensureDir, PATHS } from '../lib/fileUtils.js';diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex ff46cec8d6..bfe38749d0 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';// Mirrors execGh's DEFAULT_EXEC_GH_TIMEOUT_MS. `glab` hits the network, so a// stalled call (hung keychain prompt, dead VPN) would otherwise leave thediff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.jsindex 59fdbada8a..d9802dd1ac 100644--- a/server/services/gitlab.test.js+++ b/server/services/gitlab.test.js@@ -8,7 +8,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { EventEmitter } from 'events';const spawnMock = vi.fn();-vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));+vi.mock('../lib/childProcess.js', () => ({ spawn: (...args) => spawnMock(...args) }));const { findMergeRequestForBranch } = await import('./gitlab.js');diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex 03703700dd..7e6bdfa828 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -11,7 +11,7 @@* tool parameter, so an image-only agy render is rejected up front.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';import { randomUUID } from 'crypto';import { isAbsolute, join, resolve as pathResolve, sep } from 'path';diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.jsindex 1c17cc300c..e116dd841d 100644--- a/server/services/imageGen/agy.test.js+++ b/server/services/imageGen/agy.test.js@@ -18,7 +18,7 @@ const makeFakeChild = () => {return child;};-vi.mock('child_process', async (importOriginal) => {+vi.mock('../../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 2fc42839d5..0e80c07ae0 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -29,7 +29,7 @@* needs the guard too.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { copyFile, readFile, readdir, stat, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 00b6dad035..6ef3f68ca9 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -29,7 +29,7 @@ const makeFakeChild = () => {};// Partial mock — keep execFile/exec real for fileUtils.dirSize and friends,// only swap spawn so we can assert + drive the codex child.-vi.mock('child_process', async (importOriginal) => {+vi.mock('../../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex 0c3cd223c1..0834a91469 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -32,7 +32,7 @@* drew itself rather than generated (see fabricationGuard.js).*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';import { isAbsolute, join, resolve as pathResolve, sep } from 'path';import { tmpdir } from 'os';diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex 678354568e..b0a7f0de22 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -23,7 +23,7 @@ const makeFakeChild = () => {child.signalCode = null;return child;};-vi.mock('child_process', async (importOriginal) => {+vi.mock('../../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();const { readFileSync } = await import('fs');return {diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex c7ffe534ae..3224d2b6bb 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -12,7 +12,7 @@* raw status text mflux prints to stderr.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import sharp from 'sharp';import { writeFile, readFile, readdir, stat, unlink, rm, mkdtemp } from 'fs/promises';import { existsSync, watch as fsWatch } from 'fs';diff --git a/server/services/imageGen/renderTargets.guard.test.js b/server/services/imageGen/renderTargets.guard.test.jsindex 8ce882c7af..319aa4989e 100644--- a/server/services/imageGen/renderTargets.guard.test.js+++ b/server/services/imageGen/renderTargets.guard.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { execFileSync } from 'child_process';+import { execFileSync } from '../../lib/childProcess.js';import { readFileSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';diff --git a/server/services/imageTo3d/laneRunner.js b/server/services/imageTo3d/laneRunner.jsindex ba53cb5d22..7270cf239a 100644--- a/server/services/imageTo3d/laneRunner.js+++ b/server/services/imageTo3d/laneRunner.js@@ -18,7 +18,7 @@* (CLAUDE.md child-process exception).*/-import { spawn } from 'node:child_process';+import { spawn } from '../../lib/childProcess.js';import { sleep as defaultSleep } from '../../lib/fileUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { createLineReader } from '../../lib/streamLines.js';diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex aa1c03e02b..c9430e57b7 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -22,7 +22,7 @@ import { existsSync } from 'node:fs';import { homedir, platform, totalmem } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';-import { spawn, execFile } from 'node:child_process';+import { spawn, execFile } from '../../lib/childProcess.js';import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import { getTarget } from './targets.js';import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';diff --git a/server/services/imageTo3d/trellis2Cuda.js b/server/services/imageTo3d/trellis2Cuda.jsindex b7f75f24c6..e65c312d57 100644--- a/server/services/imageTo3d/trellis2Cuda.js+++ b/server/services/imageTo3d/trellis2Cuda.js@@ -36,7 +36,7 @@ import { existsSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';-import { spawn } from 'node:child_process';+import { spawn } from '../../lib/childProcess.js';import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import {hfGatedRepoHelp,diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.jsindex 977e5359eb..b90e44df5e 100644--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js@@ -1,4 +1,4 @@-import { execFileSync } from 'node:child_process';+import { execFileSync } from '../../lib/childProcess.js';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';diff --git a/server/services/layeredIntelligence/runCli.js b/server/services/layeredIntelligence/runCli.jsindex 5228dc0d58..9999a4f4b5 100644--- a/server/services/layeredIntelligence/runCli.js+++ b/server/services/layeredIntelligence/runCli.js@@ -4,7 +4,7 @@* filer can both use it without an import cycle.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';/** Run a CLI, resolving `{ code, stdout, stderr }` (never rejects). */diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 9ce95c4474..11b71188b8 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -20,8 +20,7 @@* multimodal). See `server/lib/localLlmDisk.js` for the disk logic.*/-import { execFile, spawn } from 'child_process'-import { promisify } from 'util'+import { execFile, spawn } from '../lib/childProcess.js';import { promisify } from 'util'import { readFileSync, createWriteStream } from 'fs'import { rm } from 'fs/promises'import { join } from 'path'diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 835f402e02..f823c3e6ad 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -87,7 +87,7 @@ const cp = vi.hoisted(() => ({spawn: null,execFile: null,}));-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({spawn: (...a) => cp.spawn(...a),execFile: (cmd, args, opts, cb) => cp.execFile(cmd, args, opts, cb),}));diff --git a/server/services/loraTraining/displayPower.js b/server/services/loraTraining/displayPower.jsindex e9c048636d..7015ea9fdc 100644--- a/server/services/loraTraining/displayPower.js+++ b/server/services/loraTraining/displayPower.js@@ -17,7 +17,7 @@* lifecycle), so per the repo convention the spawn boundary is wrapped and never* throws into the event loop.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { platform } from 'os';// Whether auto display-sleep is enabled for this host. Apple Silicon only (thediff --git a/server/services/loraTraining/displayPower.test.js b/server/services/loraTraining/displayPower.test.jsindex aa4327a6c6..c6c7da19a7 100644--- a/server/services/loraTraining/displayPower.test.js+++ b/server/services/loraTraining/displayPower.test.js@@ -7,7 +7,7 @@ const h = vi.hoisted(() => ({}));vi.mock('os', () => ({ platform: () => h.platform }));-vi.mock('child_process', () => ({+vi.mock('../../lib/childProcess.js', () => ({spawn: (cmd, args) => {h.spawned.push({ cmd, args });return { on: () => {}, unref: () => {} };diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex d1df13afb0..48255c9e80 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -13,7 +13,7 @@* The trainers checkpoint on SIGTERM, so a cancel keeps its progress.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { existsSync } from 'fs';import { copyFile, writeFile } from 'fs/promises';import { join, basename, dirname } from 'path';diff --git a/server/services/loraTraining/memoryPrep.test.js b/server/services/loraTraining/memoryPrep.test.jsindex 6e6c9e6c18..d9953b3a2b 100644--- a/server/services/loraTraining/memoryPrep.test.js+++ b/server/services/loraTraining/memoryPrep.test.js@@ -30,7 +30,7 @@ vi.mock('os', () => ({totalmem: () => h.totalBytes,freemem: () => h.freeBytes,}));-vi.mock('child_process', () => ({+vi.mock('../../lib/childProcess.js', () => ({execFile: (_cmd, cb) => {if (h.vmStatThrows) return cb(new Error('vm_stat missing'));return cb(null, h.vmStat);diff --git a/server/services/mediaService.js b/server/services/mediaService.jsindex 987b432e9a..d19c700919 100644--- a/server/services/mediaService.js+++ b/server/services/mediaService.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { PassThrough } from 'stream';import { safeChildProcessOptions } from '../lib/processEnv.js';diff --git a/server/services/mediaService.test.js b/server/services/mediaService.test.jsindex 513c020ce2..92fc06a0fe 100644--- a/server/services/mediaService.test.js+++ b/server/services/mediaService.test.js@@ -3,7 +3,7 @@ import { PassThrough } from 'stream';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const spawn = vi.hoisted(() => vi.fn());-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: (...args) => spawn(...args),}));diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsindex 720cd0c911..ac7739199f 100644--- a/server/services/mortalLoomStore.test.js+++ b/server/services/mortalLoomStore.test.js@@ -22,7 +22,7 @@ vi.mock('fs/promises', () => ({stat: (...args) => statMock(...args),}));-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({spawn: (...args) => spawnMock(...args),}));diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.jsindex 7fdd0a277e..c4b7c48250 100644--- a/server/services/musicVideo/audioAnalysis.js+++ b/server/services/musicVideo/audioAnalysis.js@@ -25,7 +25,7 @@* thin ffmpeg-decode wrapper around it.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { findFfmpeg } from '../../lib/ffmpeg.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 4e956b638c..11cc3b6b9d 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -20,7 +20,7 @@* rather than whatever the current beat grid would produce.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { join } from 'path';diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.jsindex 4d6cb4307e..8d761e9542 100644--- a/server/services/musicVideo/render.terminal.test.js+++ b/server/services/musicVideo/render.terminal.test.js@@ -31,7 +31,7 @@ const h = vi.hoisted(() => {return { procs, spawn };});-vi.mock('child_process', () => ({ spawn: h.spawn }));+vi.mock('../../lib/childProcess.js', () => ({ spawn: h.spawn }));vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));vi.mock('../../lib/fileUtils.js', () => ({diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 51be73daa5..6c68fd5b48 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -18,8 +18,7 @@ import { homedir } from 'os'import { join, dirname } from 'path'import { readdir, stat, link, unlink } from 'fs/promises'import { createHash } from 'crypto'-import { execFile, spawn } from 'child_process'-import { promisify } from 'util'+import { execFile, spawn } from '../lib/childProcess.js';import { promisify } from 'util'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'import { readJSONFile, sha256File, safeJSONParse, ensureDir, atomicWrite, sleep } from '../lib/fileUtils.js'diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 1b1e039a04..3a3c10cf76 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -10,7 +10,7 @@ import { pinPlatform } from '../lib/testHelper.js'// be scripted (brew --version, services start/stop/list). `spawn` is referenced// at module import (startServer) but never invoked by these tests.const execMock = { impl: () => {} }-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({execFile: (cmd, args, opts, cb) => execMock.impl(cmd, args, opts, cb),spawn: vi.fn()}))diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.jsindex b936d4e2da..4425514387 100644--- a/server/services/perpetualWork.js+++ b/server/services/perpetualWork.js@@ -22,7 +22,7 @@* full recheck cadence on a blip.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { readFile } from 'fs/promises';import { join } from 'path';import { emitLog } from './cosEvents.js';diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.jsindex 7c3d7fc813..ad711bb98e 100644--- a/server/services/perpetualWork.test.js+++ b/server/services/perpetualWork.test.js@@ -6,12 +6,12 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn()}));-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: vi.fn() };});-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import {isActionableIssue,titleMarksEpic,diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex 05fba4e4de..10df7e6306 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -43,8 +43,8 @@ vi.mock('../../lib/ffmpeg.js', async () => {const spawnCalls = [];let mockExitCode = 0;let mockStderr = '';-vi.mock('child_process', async () => {- const actual = await vi.importActual('child_process');+vi.mock('../../lib/childProcess.js', async () => {+ const actual = await vi.importActual('../../lib/childProcess.js');const fs = await import('fs/promises');return {...actual,diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex 72c0b2a302..2dd864380f 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -28,7 +28,7 @@*/import { existsSync, statSync } from 'fs';-import { execFile } from 'child_process';+import { execFile } from '../../lib/childProcess.js';import { platform as osPlatform, arch as osArch } from 'os';import { promisify } from 'util';import { unlink } from 'fs/promises';diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsindex f6de951c08..e5b57da5ba 100644--- a/server/services/pipeline/musicGen.test.js+++ b/server/services/pipeline/musicGen.test.js@@ -324,8 +324,8 @@ vi.mock('os', async () => ({arch: () => h.osArch,}));-vi.mock('child_process', async () => {- const actual = await vi.importActual('child_process');+vi.mock('../../lib/childProcess.js', async () => {+ const actual = await vi.importActual('../../lib/childProcess.js');return {...actual,// isEngineHealthy probes the venv with `python -c <import>`; promisify()diff --git a/server/services/pm2.js b/server/services/pm2.jsindex a19e5b3c9d..bb3d61099e 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -1,5 +1,5 @@import pm2 from 'pm2';-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { writeFile, unlink } from 'fs/promises';import { join, dirname } from 'path';@@ -32,7 +32,8 @@ function isJsScript(script) {/*** Spawn PM2 CLI via local binary (node pm2/bin/pm2).* Always uses the local PM2 binary to avoid depending on a global pm2 install.- * On Windows this also avoids pm2.cmd which creates visible CMD windows.+ * On Windows this also skips the pm2.cmd shim, dropping the cmd.exe -> pm2.cmd+ * -> node hops and the PATH-resolution ambiguity that comes with them.** A default 'error' listener is attached so that an ENOENT or EACCES error* (e.g. missing Node binary) doesn't crash Node via the uncaught-EventEmitter@@ -45,10 +46,9 @@ function isJsScript(script) {* @returns {ChildProcess}*/export function spawnPm2(pm2Args, opts = {}) {- const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], {- ...opts,- windowsHide: true- });+ // windowsHide comes from lib/childProcess.js. Re-asserting it here would also+ // outrank a caller's explicit opt-out, which the wrapper deliberately honors.+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], opts);// Default error handler — prevents an uncaught EventEmitter 'error' crash// when no caller attaches its own handler. Callers that do attach their own// 'error' listener receive the event too (multiple listeners are additive).diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.jsindex 0b003665c2..614b9007dc 100644--- a/server/services/pm2.launch.test.js+++ b/server/services/pm2.launch.test.js@@ -10,7 +10,7 @@ const mockPm2 = vi.hoisted(() => ({vi.mock('pm2', () => ({ default: mockPm2 }));const mockSpawn = vi.hoisted(() => vi.fn());-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../lib/childProcess.js', async (importOriginal) => ({...(await importOriginal()),spawn: mockSpawn,}));diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex 5c792ff5c0..605b395a81 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -1,10 +1,9 @@import { readFile, writeFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join, basename, relative } from 'path';-import { exec } from 'child_process';+import { exec, spawn } from '../lib/childProcess.js';import { promisify } from 'util';import { getActiveProvider, getProviderById } from './providers.js';-import { spawn } from 'child_process';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { getReservedPorts, getAllApps } from './apps.js';diff --git a/server/services/runner.js b/server/services/runner.jsindex ef49797caf..32e568e8d8 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -2,7 +2,7 @@* Compatibility shim for PortOS services that import from runner.js* Re-exports toolkit runner service functions with local overrides*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { writeFile, readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 9e817965de..c2ab2bf987 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -6,7 +6,7 @@ import EventEmitter from 'events';// these tests need a real directory rather than a synthetic '/workspace' path.const TEST_WORKSPACE = process.cwd();-vi.mock('child_process', async (importOriginal) => {+vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, spawn: vi.fn() };});@@ -51,7 +51,7 @@ vi.mock('fs/promises', () => ({readFile: vi.fn().mockResolvedValue('{}'),}));-const { spawn } = await import('child_process');+const { spawn } = await import('../lib/childProcess.js');const { writeFile, readFile } = await import('fs/promises');const { atomicWrite, tryReadFile } = await import('../lib/fileUtils.js');const runner = await import('./runner.js');diff --git a/server/services/signalSync.js b/server/services/signalSync.jsindex a3a5d89631..0fe55e708b 100644--- a/server/services/signalSync.js+++ b/server/services/signalSync.js@@ -34,7 +34,7 @@*/import { DatabaseSync } from 'node:sqlite';import { promisify } from 'node:util';-import { execFile } from 'node:child_process';+import { execFile } from '../lib/childProcess.js';import { copyFile, mkdtemp, writeFile, rm } from 'node:fs/promises';import { statSync } from 'node:fs';import { tmpdir } from 'node:os';diff --git a/server/services/trackYoutubeImport.test.js b/server/services/trackYoutubeImport.test.jsindex 49dd589916..afeac30725 100644--- a/server/services/trackYoutubeImport.test.js+++ b/server/services/trackYoutubeImport.test.js@@ -14,11 +14,11 @@ vi.mock('./tracks/index.js', () => ({createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),DURATION_MAX_SEC: 3600,}));-vi.mock('child_process', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));+vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));const { findYtDlp } = await import('../lib/ytdlp.js');const { findFfmpeg } = await import('../lib/ffmpeg.js');-const { spawn } = await import('child_process');+const { spawn } = await import('../lib/childProcess.js');const {YOUTUBE_URL_RE, assertYoutubeUrl, startYoutubeImport,} = await import('./trackYoutubeImport.js');diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex 9e57232492..f8d925ffbb 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -1,4 +1,4 @@-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { readFile, unlink } from 'fs/promises';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.jsindex f2087d78b8..73f8979806 100644--- a/server/services/updateExecutor.test.js+++ b/server/services/updateExecutor.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';import { pinPlatform } from '../lib/testHelper.js';-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({spawn: vi.fn()}));@@ -25,7 +25,7 @@ vi.mock('./updateChecker.js', () => ({recordUpdateResult: vi.fn().mockResolvedValue(undefined)}));-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';import { readFile } from 'fs/promises';import { recordUpdateResult } from './updateChecker.js';diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex b66dcf9135..00ee9d0a23 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -21,7 +21,7 @@* disabled/missing-binary up front; this module assumes it's enabled.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';import { isAbsolute, join, resolve as pathResolve, sep } from 'path';import { tmpdir } from 'os';diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.jsindex b7824b956c..93aae3d755 100644--- a/server/services/videoGen/grok.test.js+++ b/server/services/videoGen/grok.test.js@@ -20,7 +20,7 @@ const makeFakeChild = () => {child.signalCode = null;return child;};-vi.mock('child_process', async (importOriginal) => {+vi.mock('../../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();const { readFileSync } = await import('fs');return {diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex bf00ea0002..148de4845a 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -10,7 +10,7 @@* the model sees them.*/-import { execFile, spawn } from 'child_process';+import { execFile, spawn } from '../../lib/childProcess.js';import { existsSync, statSync } from 'fs';import { unlink, writeFile, copyFile } from 'fs/promises';import { join, basename } from 'path';diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 43afebcac9..5a633f93be 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -291,7 +291,7 @@ const { makeProc } = vi.hoisted(() => ({},}));-vi.mock('child_process', () => ({+vi.mock('../../lib/childProcess.js', () => ({spawn: vi.fn(() => makeProc()),execFile: vi.fn((_bin, _args, _opts, cb) => cb?.(null, '', '')),}));@@ -458,7 +458,7 @@ describe('generateChainedVideo — continuation strategy (context window vs lastasync function runChain(chainParams, totalChunks, probeFrames = null) {const { spawnDetached } = await import('../../lib/detachedSpawn.js');const { trimVideoFromFrame, probeFrameCount } = await import('../../lib/ffmpeg.js');- const { spawn } = await import('child_process');+ const { spawn } = await import('../../lib/childProcess.js');const { readJSONFile, atomicWrite } = await import('../../lib/fileUtils.js');vi.mocked(spawnDetached).mockClear();vi.mocked(trimVideoFromFrame).mockClear();@@ -619,7 +619,7 @@ describe('generateChainedVideo — continuation strategy (context window vs last// already rendered. Moving the cut into the concat has to keep that: the// untrimmed chunks were never re-encoded, so they're still in codec// lockstep and the demuxer can still assemble them.- const { spawn } = await import('child_process');+ const { spawn } = await import('../../lib/childProcess.js');const failingProc = () => {const listeners = {};const proc = {@@ -901,7 +901,7 @@ describe('generateVideo — ltx2 FFLF image resizing', () => {// Windows uses the separate diffusers runner, which intentionally consumes// only the start image. This assertion is specific to the MLX FFLF helper.it.skipIf(process.platform === 'win32')('resizes both start and end frames before passing them to the ltx2 helper', async () => {- const { execFile } = await import('child_process');+ const { execFile } = await import('../../lib/childProcess.js');const { spawnDetached } = await import('../../lib/detachedSpawn.js');const execFileMock = vi.mocked(execFile);const spawnMock = vi.mocked(spawnDetached);@@ -3085,7 +3085,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {};it('materializes each still into a 9-frame clip at the render resolution', async () => {- const { execFile } = await import('child_process');+ const { execFile } = await import('../../lib/childProcess.js');const { spawnDetached } = await import('../../lib/detachedSpawn.js');const execFileMock = vi.mocked(execFile);const spawnMock = vi.mocked(spawnDetached);@@ -3179,7 +3179,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {// Promise.all rejects at the first failure while siblings are still in// flight, so a push-on-success registry would miss the ones that landed// afterwards. Every target path is registered before any encode starts.- const { execFile } = await import('child_process');+ const { execFile } = await import('../../lib/childProcess.js');const { unlink } = await import('fs/promises');const execFileMock = vi.mocked(execFile);const unlinkMock = vi.mocked(unlink);@@ -3222,7 +3222,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {// try/catch, so without explicit cleanup here the resized-source temp// file would leak into os.tmpdir() even though the clip temp files// themselves were already covered by the test above.- const { execFile } = await import('child_process');+ const { execFile } = await import('../../lib/childProcess.js');const { unlink } = await import('fs/promises');const execFileMock = vi.mocked(execFile);const unlinkMock = vi.mocked(unlink);diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 4f2c81f86f..cc7d9c808e 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -9,7 +9,7 @@* so it has no dependency back on local.js.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { existsSync } from 'fs';import { join } from 'path';import { homedir, cpus, type as osType, release as osRelease } from 'os';diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.jsindex 95e6278975..71339de563 100644--- a/server/services/videoGen/runtimes.test.js+++ b/server/services/videoGen/runtimes.test.js@@ -13,7 +13,7 @@ vi.mock('fs', async (importOriginal) => ({...await importOriginal(),existsSync: runtimeMocks.existsSync,}));-vi.mock('child_process', async (importOriginal) => ({+vi.mock('../../lib/childProcess.js', async (importOriginal) => ({...await importOriginal(),spawn: runtimeMocks.spawn,}));diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex 1703660c60..f8b146e4a8 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -15,7 +15,7 @@* Media History shows them alongside generated clips.*/-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { join } from 'path';diff --git a/server/services/videoTimeline/local.terminal.test.js b/server/services/videoTimeline/local.terminal.test.jsindex f8dcaef2f7..f3c626dfd4 100644--- a/server/services/videoTimeline/local.terminal.test.js+++ b/server/services/videoTimeline/local.terminal.test.js@@ -30,7 +30,7 @@ const h = vi.hoisted(() => {return { procs, spawn };});-vi.mock('child_process', () => ({ spawn: h.spawn }));+vi.mock('../../lib/childProcess.js', () => ({ spawn: h.spawn }));vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));vi.mock('../../lib/fileUtils.js', () => ({diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 251d2c3433..be30f0c357 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -23,7 +23,7 @@* guess).*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { writeFile, rm, mkdtemp, copyFile } from 'fs/promises';import { existsSync } from 'fs';import { tmpdir } from 'os';diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.jsindex 5124ad95d9..3a5f24a880 100644--- a/server/services/voice/bootstrap.js+++ b/server/services/voice/bootstrap.js@@ -2,7 +2,7 @@// provisioning. Piper (TTS) is spawned per-request in services/voice/tts.js.import { existsSync } from 'fs';-import { execFile } from 'child_process';+import { execFile } from '../../lib/childProcess.js';import { promisify } from 'util';import { basename, join } from 'path';import { createServer } from 'net';diff --git a/server/services/voice/tts-piper.js b/server/services/voice/tts-piper.jsindex e90183d059..098c09b9e2 100644--- a/server/services/voice/tts-piper.js+++ b/server/services/voice/tts-piper.js@@ -1,6 +1,6 @@// Piper TTS backend — spawn-per-request CLI: text on stdin, WAV on stdout.-import { spawn } from 'child_process';+import { spawn } from '../../lib/childProcess.js';import { randomUUID } from 'crypto';import { existsSync, readFileSync, unlinkSync } from 'fs';import { tmpdir } from 'os';diff --git a/server/services/xcodeScripts.js b/server/services/xcodeScripts.jsindex 17a3887fb7..12e7f2d990 100644--- a/server/services/xcodeScripts.js+++ b/server/services/xcodeScripts.js@@ -1,7 +1,7 @@import { existsSync } from 'fs';import { readFile, writeFile } from 'fs/promises';import { join } from 'path';-import { exec, execFile } from 'child_process';+import { exec, execFile } from '../lib/childProcess.js';import { promisify } from 'util';import { activateAppLine, osascriptSystemEvents } from './xcodeScriptBuilders.js';diff --git a/server/services/xcodeScripts.test.js b/server/services/xcodeScripts.test.jsindex d59f2c3f19..73fd7d4e4b 100644--- a/server/services/xcodeScripts.test.js+++ b/server/services/xcodeScripts.test.js@@ -15,7 +15,7 @@ vi.mock('fs/promises', () => ({readFile: vi.fn(),writeFile: vi.fn()}));-vi.mock('child_process', () => ({+vi.mock('../lib/childProcess.js', () => ({exec: hoisted.execMock,execFile: hoisted.execFileMock}));diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.jsindex 6f593c3d17..79eb2d3a6b 100644--- a/server/services/youtubeIngest.js+++ b/server/services/youtubeIngest.js@@ -36,7 +36,7 @@* The durable, federated record of "I kept this" is the links entry.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { readdir, readFile, rename, rm, stat, unlink } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.jsindex 8b9864b852..e0d6f7aec9 100644--- a/server/services/ytdlpAudioImport.js+++ b/server/services/ytdlpAudioImport.js@@ -20,7 +20,7 @@* http(s) URL (SSRF-guarded) — so the core never sees an unvetted URL.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { readdir, unlink } from 'fs/promises';import { tmpdir } from 'os';diff --git a/server/services/ytdlpAudioImport.test.js b/server/services/ytdlpAudioImport.test.jsindex f805bde09d..b3b1f4a4dd 100644--- a/server/services/ytdlpAudioImport.test.js+++ b/server/services/ytdlpAudioImport.test.js@@ -3,11 +3,11 @@ import { EventEmitter } from 'events';vi.mock('../lib/ytdlp.js', () => ({ findYtDlp: vi.fn(async () => '/usr/local/bin/yt-dlp') }));vi.mock('../lib/ffmpeg.js', () => ({ findFfmpeg: vi.fn(async () => '/usr/local/bin/ffmpeg') }));-vi.mock('child_process', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));+vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));const { findYtDlp } = await import('../lib/ytdlp.js');const { findFfmpeg } = await import('../lib/ffmpeg.js');-const { spawn } = await import('child_process');+const { spawn } = await import('../lib/childProcess.js');const { resolveYtDlpBinaries, downloadAudioToTempMp3 } = await import('./ytdlpAudioImport.js');// A fake yt-dlp child. `emit` optionally pushes stdout/stderr lines before thediff --git a/server/services/ytdlpVideoImport.js b/server/services/ytdlpVideoImport.jsindex a853ac413a..239bf6bc66 100644--- a/server/services/ytdlpVideoImport.js+++ b/server/services/ytdlpVideoImport.js@@ -16,7 +16,7 @@* unvetted URL.*/-import { spawn } from 'child_process';+import { spawn } from '../lib/childProcess.js';import { readdir, unlink } from 'fs/promises';import { join, dirname } from 'path';import { ensureDir } from '../lib/fileUtils.js';