Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-790]): unify buffered-spawn + Windows kill-tree helpers
[._.]/ Adam Eivydf7f0ac90969
diff --git a/server/lib/README.md b/server/lib/README.mdindex 8554ed9333..feb17611b6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. || `commandSecurity.js` | Allowlist of safe shell commands. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsnew file mode 100644index 0000000000..0ff3c00393--- /dev/null+++ b/server/lib/bufferedSpawn.js@@ -0,0 +1,157 @@+import { spawn } from 'child_process';++/**+ * Shared buffered-spawn + Windows kill-tree machinery used by the app build and+ * update services (`server/services/appBuilder.js`, `server/services/appUpdater.js`).+ *+ * The two call sites historically carried near-identical copies of this logic;+ * they differed only in their result contract:+ * - appBuilder maps failures to HTTP codes without try/catch, so it needs a+ * structured non-throwing result.+ * - appUpdater throws on failure.+ *+ * This module provides ONE structured-result core (`bufferedSpawn`) plus a thin+ * throwing adapter (`bufferedSpawnOrThrow`) so both contracts share the same+ * spawn / buffering / timeout / kill-tree code.+ *+ * Pure module-level constants and platform predicates are exported so callers+ * (and tests, on any platform) can reuse the shell-shim / kill decisions.+ */++export const IS_WIN32 = process.platform === 'win32';++// npm/npx are .cmd shims on Windows — enable shell only for these so cmd.exe+// can resolve them, without enabling shell metacharacter interpretation for+// native binaries (xcodebuild, swift, make, cargo, git, …).+export const WIN_CMD_SHIMS = new Set(['npm', 'npx']);++/**+ * True when a command must run through cmd.exe to be resolved on Windows.+ * Pure and platform-independent in shape — the `IS_WIN32` gate keeps it false+ * everywhere else.+ */+export const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);++// Cap buffered stdout/stderr so a runaway child can't exhaust memory; we only+// ever surface a tail of the output anyway.+export const MAX_OUTPUT_BYTES = 64 * 1024;++/**+ * Terminate a child process and its descendants.+ *+ * On Windows, SIGTERM kills the cmd.exe shim but orphans its child (npm), so we+ * use `taskkill /T /F` to take down the whole process tree. The taskkill spawn+ * is fire-and-forget: its own `error` is swallowed and the handle is unref'd so+ * it never keeps the event loop alive. Elsewhere, a plain SIGTERM suffices.+ *+ * @param {import('child_process').ChildProcess} child+ */+export function killProcessTree(child) {+ if (IS_WIN32 && child.pid) {+ spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true })+ .on('error', () => {})+ .unref();+ } else {+ child.kill('SIGTERM');+ }+}++/**+ * Spawn a command, buffer its (capped) stdout/stderr, enforce a timeout, and+ * resolve a structured result. NEVER rejects — every terminal condition+ * (clean exit, non-zero exit, spawn error, timeout) resolves a result object.+ *+ * The result is a superset of what both call sites need:+ * {+ * success: boolean, // true iff the process exited 0 within timeout+ * code: number|null, // exit code; -1 for timeout/spawn-error+ * signal: string|null, // termination signal, when applicable+ * stdout: string, // captured stdout (tail-capped, NOT trimmed)+ * stderr: string, // captured stderr (tail-capped, NOT trimmed)+ * timedOut: boolean, // true iff the timeout fired+ * error?: Error, // present only on a spawn 'error' event+ * }+ *+ * Callers shape this into their own contract (e.g. an `output` tail string, an+ * `exitCode` alias, or a thrown Error) — see `bufferedSpawnOrThrow` and the+ * appBuilder result mappers.+ *+ * @param {string} cmd+ * @param {string[]} args+ * @param {object} options+ * @param {string} [options.cwd]+ * @param {number} [options.timeoutMs] - kill + resolve as timed-out after this+ * @param {boolean} [options.shell] - defaults to `needsShell(cmd)`+ * @returns {Promise<object>} structured result (never rejects)+ */+export function bufferedSpawn(cmd, args, { cwd, timeoutMs, shell } = {}) {+ return new Promise((resolve) => {+ const child = spawn(cmd, args, {+ cwd,+ windowsHide: true,+ shell: shell === undefined ? needsShell(cmd) : shell,+ });+ let stdout = '';+ let stderr = '';+ let settled = false;++ const timer = timeoutMs+ ? setTimeout(() => {+ if (!settled) {+ settled = true;+ killProcessTree(child);+ resolve({ success: false, code: -1, signal: null, stdout, stderr, timedOut: true });+ }+ }, timeoutMs)+ : null;++ const clear = () => { if (timer) clearTimeout(timer); };++ child.stdout.on('data', (d) => {+ stdout += d;+ if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES);+ });+ child.stderr.on('data', (d) => {+ stderr += d;+ if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES);+ });+ child.on('close', (code, signal) => {+ if (!settled) {+ settled = true;+ clear();+ resolve({ success: code === 0, code, signal, stdout, stderr, timedOut: false });+ }+ });+ child.on('error', (err) => {+ if (!settled) {+ settled = true;+ clear();+ resolve({ success: false, code: -1, signal: null, stdout, stderr, timedOut: false, error: err });+ }+ });+ });+}++/**+ * Throwing adapter over `bufferedSpawn` for call sites that want an exception on+ * failure (the appUpdater contract). Resolves `{ stdout, stderr }` on a clean+ * exit; rejects on spawn error, timeout, or non-zero exit.+ *+ * @param {string} cmd+ * @param {string[]} args+ * @param {object} options - same as `bufferedSpawn`, plus optional `timeoutLabel`+ * @param {string} [options.timeoutLabel] - prefix for the timeout error message (defaults to `cmd`)+ * @returns {Promise<{stdout: string, stderr: string}>}+ */+export async function bufferedSpawnOrThrow(cmd, args, options = {}) {+ const { timeoutLabel = cmd, ...spawnOpts } = options;+ const result = await bufferedSpawn(cmd, args, spawnOpts);+ if (result.error) throw result.error;+ if (result.timedOut) {+ throw new Error(`${timeoutLabel} timed out after ${(spawnOpts.timeoutMs ?? 0) / 1000}s`);+ }+ if (!result.success) {+ throw new Error(result.stderr.trim() || `${cmd} exited with code ${result.code}`);+ }+ return { stdout: result.stdout, stderr: result.stderr };+}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsnew file mode 100644index 0000000000..e4f2bac410--- /dev/null+++ b/server/lib/bufferedSpawn.test.js@@ -0,0 +1,223 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++// Mock child_process.spawn so we can drive the buffered-spawn machinery without+// launching real processes.+const spawnMock = vi.fn();+vi.mock('child_process', () => ({ spawn: (...a) => spawnMock(...a) }));++// Re-imported after the mock is registered.+const {+ bufferedSpawn,+ bufferedSpawnOrThrow,+ killProcessTree,+ needsShell,+ IS_WIN32,+ WIN_CMD_SHIMS,+ MAX_OUTPUT_BYTES,+} = await import('./bufferedSpawn.js');++/** Build a fake child process with stdout/stderr emitters and a kill spy. */+function makeFakeChild({ pid = 1234 } = {}) {+ const child = new EventEmitter();+ child.pid = pid;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+}++beforeEach(() => {+ spawnMock.mockReset();+ vi.useRealTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('needsShell / constants', () => {+ it('only treats npm/npx as shell shims, and only on Windows', () => {+ expect(WIN_CMD_SHIMS.has('npm')).toBe(true);+ expect(WIN_CMD_SHIMS.has('npx')).toBe(true);+ expect(WIN_CMD_SHIMS.has('git')).toBe(false);+ // needsShell mirrors IS_WIN32 — false on non-Windows test runners.+ expect(needsShell('npm')).toBe(IS_WIN32);+ expect(needsShell('git')).toBe(false);+ });++ it('caps buffered output at 64KiB', () => {+ expect(MAX_OUTPUT_BYTES).toBe(64 * 1024);+ });+});++describe('killProcessTree', () => {+ it('on non-Windows sends SIGTERM to the child', () => {+ if (IS_WIN32) return; // platform-gated behavior+ const child = makeFakeChild();+ killProcessTree(child);+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ expect(spawnMock).not.toHaveBeenCalled();+ });++ it('on Windows spawns taskkill /T /F against the pid', () => {+ if (!IS_WIN32) return; // can't simulate platform branch from outside+ const child = makeFakeChild({ pid: 999 });+ const tk = makeFakeChild();+ tk.unref = vi.fn();+ spawnMock.mockReturnValueOnce(tk);+ killProcessTree(child);+ expect(spawnMock).toHaveBeenCalledWith(+ 'taskkill', ['/T', '/F', '/PID', '999'],+ expect.objectContaining({ stdio: 'ignore', windowsHide: true })+ );+ });+});++describe('bufferedSpawn — structured result', () => {+ it('resolves success on a clean (code 0) exit and captures stdout/stderr', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('echo', ['hi'], { cwd: '/tmp' });+ child.stdout.emit('data', 'out-data');+ child.stderr.emit('data', 'err-data');+ child.emit('close', 0, null);+ const result = await p;+ expect(result).toEqual({+ success: true, code: 0, signal: null,+ stdout: 'out-data', stderr: 'err-data', timedOut: false,+ });+ // cwd + windowsHide passed through; shell defaults to needsShell(cmd).+ expect(spawnMock).toHaveBeenCalledWith('echo', ['hi'], expect.objectContaining({ cwd: '/tmp', windowsHide: true }));+ });++ it('resolves failure (not throw) on a non-zero exit', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('false', []);+ child.emit('close', 2, 'SIGABRT');+ const result = await p;+ expect(result.success).toBe(false);+ expect(result.code).toBe(2);+ expect(result.signal).toBe('SIGABRT');+ expect(result.timedOut).toBe(false);+ });++ it('resolves with the error attached on a spawn error', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('nope', []);+ const err = new Error('ENOENT');+ child.emit('error', err);+ const result = await p;+ expect(result.success).toBe(false);+ expect(result.code).toBe(-1);+ expect(result.error).toBe(err);+ expect(result.timedOut).toBe(false);+ });++ it('caps stdout to MAX_OUTPUT_BYTES (keeps the tail)', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('big', []);+ child.stdout.emit('data', 'a'.repeat(MAX_OUTPUT_BYTES));+ child.stdout.emit('data', 'TAIL');+ child.emit('close', 0, null);+ const result = await p;+ expect(result.stdout.length).toBe(MAX_OUTPUT_BYTES);+ expect(result.stdout.endsWith('TAIL')).toBe(true);+ expect(result.stdout.startsWith('a')).toBe(true);+ });++ it('times out: kills the tree and resolves timedOut with buffered partial output', async () => {+ vi.useFakeTimers();+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('hang', [], { timeoutMs: 1000 });+ child.stdout.emit('data', 'partial');+ vi.advanceTimersByTime(1000);+ const result = await p;+ expect(result.timedOut).toBe(true);+ expect(result.success).toBe(false);+ expect(result.code).toBe(-1);+ expect(result.stdout).toBe('partial');+ if (!IS_WIN32) expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ });++ it('a close after timeout does not double-resolve (settled guard)', async () => {+ vi.useFakeTimers();+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('hang', [], { timeoutMs: 500 });+ vi.advanceTimersByTime(500);+ child.emit('close', 0, null); // late close — must be ignored+ const result = await p;+ expect(result.timedOut).toBe(true);+ });++ it('respects an explicit shell override', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawn('cmd', [], { shell: true });+ child.emit('close', 0, null);+ await p;+ expect(spawnMock).toHaveBeenCalledWith('cmd', [], expect.objectContaining({ shell: true }));+ });+});++describe('bufferedSpawnOrThrow — throwing adapter', () => {+ it('resolves { stdout, stderr } on a clean exit', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('git', ['pull'], { cwd: '/repo' });+ child.stdout.emit('data', 'Already up to date.');+ child.emit('close', 0, null);+ await expect(p).resolves.toEqual({ stdout: 'Already up to date.', stderr: '' });+ });++ it('throws the spawn error', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('nope', []);+ const err = new Error('boom');+ child.emit('error', err);+ await expect(p).rejects.toBe(err);+ });++ it('throws using stderr on a non-zero exit', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('npm', ['install']);+ child.stderr.emit('data', ' npm ERR! failed ');+ child.emit('close', 1, null);+ await expect(p).rejects.toThrow('npm ERR! failed');+ });++ it('throws "exited with code" when stderr is empty', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('make', []);+ child.emit('close', 7, null);+ await expect(p).rejects.toThrow('make exited with code 7');+ });++ it('throws a timeout message using the command name', async () => {+ vi.useFakeTimers();+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('npm', ['install'], { timeoutMs: 2000 });+ const assertion = expect(p).rejects.toThrow('npm timed out after 2s');+ vi.advanceTimersByTime(2000);+ await assertion;+ });++ it('uses timeoutLabel when provided', async () => {+ vi.useFakeTimers();+ const child = makeFakeChild();+ spawnMock.mockReturnValueOnce(child);+ const p = bufferedSpawnOrThrow('npm', ['run', 'setup'], { timeoutMs: 3000, timeoutLabel: 'Setup' });+ const assertion = expect(p).rejects.toThrow('Setup timed out after 3s');+ vi.advanceTimersByTime(3000);+ await assertion;+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 88b7d190d7..d4bd501425 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -98,6 +98,7 @@ export * from './pdfImageEmbed.js';export * from './zipStream.js';// === Process execution ===+export * from './bufferedSpawn.js';export * from './commandSecurity.js';export * from './execGit.js';export * from './ffmpeg.js';diff --git a/server/services/appBuilder.js b/server/services/appBuilder.jsindex 396621e61c..89aeb261a8 100644--- a/server/services/appBuilder.js+++ b/server/services/appBuilder.js@@ -1,6 +1,6 @@-import { spawn } from 'child_process';import { join } from 'path';import { access } from 'fs/promises';+import { bufferedSpawn, needsShell } from '../lib/bufferedSpawn.js';/** Async equivalent of existsSync — returns true if the path is accessible */const pathExists = (p) => access(p).then(() => true).catch(() => false);@@ -15,12 +15,6 @@ export const ALLOWED_BUILD_CMDS = new Set(['cargo' // Rust]);-const IS_WIN32 = process.platform === 'win32';-// npm/npx are .cmd shims on Windows — enable shell only for these so cmd.exe-// can resolve them, without enabling shell metacharacter interpretation for-// native binaries (xcodebuild, swift, make, cargo).-const WIN_CMD_SHIMS = new Set(['npm', 'npx']);-const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);// Actual cmd.exe metacharacters (& | < > ^ % ! and grouping parens).// Validated only when shell is active (needsShell guard at call site).const SHELL_UNSAFE_RE = /[&|<>^%!()]/;@@ -30,18 +24,8 @@ const SHELL_UNSAFE_RE = /[&|<>^%!()]/;* (the `needsShell` gate that actually applies it stays at the call site).*/export const hasShellUnsafeArg = (args) => args.some(a => SHELL_UNSAFE_RE.test(a));-// On Windows, SIGTERM kills cmd.exe but orphans its child (npm). Use taskkill-// /T /F to terminate the whole process tree.-const killProc = (child) => {- if (IS_WIN32 && child.pid) {- spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();- } else {- child.kill('SIGTERM');- }-};const INSTALL_TIMEOUT_MS = 3 * 60 * 1000;const BUILD_TIMEOUT_MS = 5 * 60 * 1000;-const MAX_OUTPUT_BYTES = 64 * 1024;const DEFAULT_BUILD_COMMAND = 'npm run build';/**@@ -75,65 +59,33 @@ export function parseBuildCommand(buildCommand) {* Run `npm install` in a single directory.* @returns {Promise<{success, exitCode, output}>} — resolves (never rejects).*/-function runNpmInstall(subDir) {- return new Promise((resolve) => {- const child = spawn('npm', ['install'], { cwd: subDir, windowsHide: true, shell: needsShell('npm') });- let stdout = '';- let stderr = '';- let settled = false;- const timer = setTimeout(() => {- if (!settled) { settled = true; killProc(child); resolve({ success: false, exitCode: -1, output: `npm install timed out after ${INSTALL_TIMEOUT_MS / 1000}s` }); }- }, INSTALL_TIMEOUT_MS);- child.stdout.on('data', d => { stdout += d; if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES); });- child.stderr.on('data', d => { stderr += d; if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES); });- child.on('close', exitCode => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: exitCode === 0, exitCode, output: (stderr.trim() || stdout.trim()).slice(-1024) }); } });- child.on('error', err => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: false, exitCode: -1, output: err.message }); } });- });+async function runNpmInstall(subDir) {+ const result = await bufferedSpawn('npm', ['install'], { cwd: subDir, timeoutMs: INSTALL_TIMEOUT_MS });+ if (result.timedOut) {+ return { success: false, exitCode: -1, output: `npm install timed out after ${INSTALL_TIMEOUT_MS / 1000}s` };+ }+ if (result.error) {+ return { success: false, exitCode: -1, output: result.error.message };+ }+ return { success: result.success, exitCode: result.code, output: (result.stderr.trim() || result.stdout.trim()).slice(-1024) };}/*** Run the build command in `repoPath`.* @returns {Promise<{success, stdout, stderr, code, signal, output}>} — resolves (never rejects).*/-function runBuild(cmd, args, repoPath) {- return new Promise((resolve) => {- const child = spawn(cmd, args, { cwd: repoPath, windowsHide: true, shell: needsShell(cmd) });- let stdout = '';- let stderr = '';- let settled = false;- const timer = setTimeout(() => {- if (!settled) {- settled = true;- killProc(child);- const timeoutMsg = `Build timed out after ${BUILD_TIMEOUT_MS / 1000}s`;- const tail = (stderr.trim() || stdout.trim()).slice(-512);- resolve({ success: false, stderr: timeoutMsg, code: -1, output: tail ? `${timeoutMsg} — last output: ${tail}` : timeoutMsg });- }- }, BUILD_TIMEOUT_MS);- child.stdout.on('data', d => {- stdout += d;- if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES);- });- child.stderr.on('data', d => {- stderr += d;- if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES);- });- child.on('close', (code, signal) => {- if (!settled) {- settled = true;- clearTimeout(timer);- const output = (stderr.trim() || stdout.trim()).slice(-1024);- resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), code, signal, output });- }- });- child.on('error', err => {- if (!settled) {- settled = true;- clearTimeout(timer);- resolve({ success: false, stderr: err.message, code: -1, signal: null, output: err.message });- }- });- });+async function runBuild(cmd, args, repoPath) {+ const result = await bufferedSpawn(cmd, args, { cwd: repoPath, timeoutMs: BUILD_TIMEOUT_MS });+ if (result.timedOut) {+ const timeoutMsg = `Build timed out after ${BUILD_TIMEOUT_MS / 1000}s`;+ const tail = (result.stderr.trim() || result.stdout.trim()).slice(-512);+ return { success: false, stderr: timeoutMsg, code: -1, output: tail ? `${timeoutMsg} — last output: ${tail}` : timeoutMsg };+ }+ if (result.error) {+ return { success: false, stderr: result.error.message, code: -1, signal: null, output: result.error.message };+ }+ const output = (result.stderr.trim() || result.stdout.trim()).slice(-1024);+ return { success: result.success, stdout: result.stdout.trim(), stderr: result.stderr.trim(), code: result.code, signal: result.signal, output };}/**diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex 15534a8c34..fde3bd0722 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -1,45 +1,19 @@-import { spawn } from 'child_process';import { existsSync } from 'fs';import { join } from 'path';import { readFile } from 'fs/promises';import * as gitService from './git.js';import * as pm2Service from './pm2.js';+import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';-const IS_WIN32 = process.platform === 'win32';-const WIN_CMD_SHIMS = new Set(['npm', 'npx']);-const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);-const MAX_OUTPUT_BYTES = 64 * 1024;const CMD_TIMEOUT_MS = 5 * 60 * 1000;+/**+ * Run a command in `cwd`, throwing on timeout, spawn error, or non-zero exit.+ * Thin wrapper over the shared `bufferedSpawnOrThrow` adapter.+ * @returns {Promise<{stdout: string, stderr: string}>}+ */function runCommand(cmd, args, cwd) {- return new Promise((resolve, reject) => {- const child = spawn(cmd, args, { cwd, shell: needsShell(cmd), windowsHide: true });- let stdout = '';- let stderr = '';- let settled = false;- const timer = setTimeout(() => {- if (!settled) {- settled = true;- if (IS_WIN32 && child.pid) {- spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();- } else {- child.kill('SIGTERM');- }- reject(new Error(`${cmd} timed out after ${CMD_TIMEOUT_MS / 1000}s`));- }- }, CMD_TIMEOUT_MS);- child.stdout.on('data', d => { stdout += d; if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES); });- child.stderr.on('data', d => { stderr += d; if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES); });- child.on('close', code => {- if (!settled) {- settled = true;- clearTimeout(timer);- if (code !== 0) reject(new Error(stderr.trim() || `${cmd} exited with code ${code}`));- else resolve({ stdout, stderr });- }- });- child.on('error', err => { if (!settled) { settled = true; clearTimeout(timer); reject(err); } });- });+ return bufferedSpawnOrThrow(cmd, args, { cwd, timeoutMs: CMD_TIMEOUT_MS });}// Per-app lock to prevent concurrent updates