Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop real CLI probes from leaking scratch state into the test temp root (#9039)
[._.]/ Adam Eivy7c6992dd598c
diff --git a/server/lib/commandExists.js b/server/lib/commandExists.jsindex 6e5a0de5c5..7b4fe83caf 100644--- a/server/lib/commandExists.js+++ b/server/lib/commandExists.js@@ -1,5 +1,8 @@import { execFile } from './childProcess.js';import { promisify } from 'util';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';const execFileAsync = promisify(execFile);@@ -26,14 +29,38 @@ const execFileAsync = promisify(execFile);* needs it, but it costs one FD close and makes every probe immune. Same* reasoning, and the same incident, as `_execCliModelList` in* `lib/aiToolkit/providers.js`.+ *+ * `TMPDIR`/`TMP`/`TEMP` are pinned to a throwaway directory scoped to THIS one+ * probe, mkdtemp'd before the spawn and removed once it settles. Several real+ * agentic CLIs (kilo, opencode — both self-extracting/Node-launcher binaries)+ * write their own scratch/cache state (a session dir, Node's own module+ * compile cache) directly into whatever `TMPDIR` they inherit on EVERY+ * invocation, not just a first run. Left alone that state piles up in the+ * host's real temp directory a little on every provider-readiness poll, and+ * inside PortOS's own run-scoped vitest temp root (#9032) it fails the run+ * outright once every other leak is fixed (#9039) — a probe here never+ * observes or needs its own past scratch, so isolating and discarding it costs+ * one extra mkdtemp/rmSync and removes both problems at the source. A caller+ * that already scoped its own `env` still gets its OTHER vars untouched; only+ * the three temp-dir keys are overridden on top.*/function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {+ const scratchDir = mkdtempSync(join(tmpdir(), 'portos-cli-probe-'));+ const probeEnv = { ...(env || process.env), TMPDIR: scratchDir, TMP: scratchDir, TEMP: scratchDir };const options = {timeout: timeoutMs,- ...(env === undefined ? {} : { env }),+ env: probeEnv,...(cwd === undefined ? {} : { cwd }),...(maxBuffer === undefined ? {} : { maxBuffer }),};+ const cleanup = () => {+ try {+ rmSync(scratchDir, { recursive: true, force: true });+ } catch {+ // Best-effort — a lingering handle on a still-terminating child must+ // not throw out of a probe that already has its answer.+ }+ };// `bufferedSpawn.js` is imported lazily, not at module load: this module is// reached by a very large share of the server suite, and an eager edge into// that subtree pushed the tree-wide instantiation budget over (see "Import@@ -46,13 +73,14 @@ function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {.then(({ prepareCliSpawn }) => {// Resolution reads the env the CHILD will run under, so a caller that// overrides PATH probes its own binary, not one off the server's PATH.- const launch = prepareCliSpawn(cmd, args, env || process.env);+ const launch = prepareCliSpawn(cmd, args, probeEnv);const pending = execFileAsync(launch.command, launch.args, options);pending.child?.stdin?.end();return pending;}).then(({ stdout }) => String(stdout ?? '').trim())- .catch(() => null);+ .catch(() => null)+ .finally(cleanup);}/**diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.jsindex 8f959bb228..d501c5d5c1 100644--- a/server/lib/commandExists.test.js+++ b/server/lib/commandExists.test.js@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest'+import { existsSync } from 'node:fs'const execFileMock = { impl: (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' }) }vi.mock('./childProcess.js', () => ({@@ -68,7 +69,35 @@ describe('commandExists', () => {await commandExists('opencode', undefined, { env, cwd: '/example/workspace' })- expect(seenOpts).toEqual({ timeout: 5_000, env, cwd: '/example/workspace' })+ expect(seenOpts.timeout).toBe(5_000)+ expect(seenOpts.cwd).toBe('/example/workspace')+ // The caller's own vars survive; TMPDIR/TMP/TEMP are pinned to a+ // throwaway per-probe scratch dir so a real CLI (kilo, opencode) cannot+ // write its own scratch/cache state into the caller's TMPDIR (#9039).+ expect(seenOpts.env.PATH).toBe('/example/bin')+ expect(seenOpts.env.TMPDIR).toBe(seenOpts.env.TMP)+ expect(seenOpts.env.TMPDIR).toBe(seenOpts.env.TEMP)+ expect(seenOpts.env.TMPDIR).toMatch(/portos-cli-probe-/)+ })++ it('removes its throwaway scratch dir once the probe settles', async () => {+ let scratchDir = null+ execFileMock.impl = (_cmd, _args, opts, cb) => { scratchDir = opts.env.TMPDIR; cb(null, { stdout: '', stderr: '' }) }++ await commandExists('claude')++ expect(scratchDir).toMatch(/portos-cli-probe-/)+ expect(existsSync(scratchDir)).toBe(false)+ })++ it('removes its scratch dir even when the probe fails', async () => {+ let scratchDir = null+ execFileMock.impl = (_cmd, _args, opts, cb) => { scratchDir = opts.env.TMPDIR; cb(new Error('ENOENT')) }++ await commandExists('nope')++ expect(scratchDir).toMatch(/portos-cli-probe-/)+ expect(existsSync(scratchDir)).toBe(false)})// A bare `codex` is a `.cmd` shim on Windows. execFile's default shell:false@@ -98,7 +127,10 @@ describe('commandExists', () => {await commandExists('codex', undefined, { env })- expect(seenEnv).toBe(env)+ // Not the exact same object — the caller's vars ride along, plus the+ // isolated TMPDIR/TMP/TEMP scratch override (see the throwaway-scratch+ // tests above) — but every var the caller supplied is still there.+ expect(seenEnv).toMatchObject(env)})it('falls back to process.env when the caller passes no child env', async () => {@@ -107,7 +139,11 @@ describe('commandExists', () => {await commandExists('codex')- expect(seenEnv).toBe(process.env)+ // Every process.env var rides along except TMPDIR/TMP/TEMP, which are+ // pinned to the isolated per-probe scratch dir instead.+ const { TMPDIR: _t, TMP: _tm, TEMP: _te, ...restOfProcessEnv } = process.env+ expect(seenEnv).toMatchObject(restOfProcessEnv)+ expect(seenEnv.TMPDIR).toMatch(/portos-cli-probe-/)})})})diff --git a/server/lib/npmGlobalBin.js b/server/lib/npmGlobalBin.jsindex 8fe92b2ee1..99494ec955 100644--- a/server/lib/npmGlobalBin.js+++ b/server/lib/npmGlobalBin.js@@ -24,6 +24,8 @@import { existsSync } from 'fs';import { join } from 'path';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';import { bufferedSpawn, prepareCliSpawn } from './bufferedSpawn.js';import { adoptPathDirs, safeChildProcessEnv } from './processEnv.js';@@ -39,16 +41,32 @@ let binDirProbe = null;/** One `npm prefix -g`, mapped to the platform's global bin directory. */async function probeNpmGlobalBinDir(spawnImpl) {- const env = safeChildProcessEnv();- // `shell: false` + `prepareCliSpawn`, not `bufferedSpawn`'s `needsShell('npm')`- // default: that default is `shell: true` with an args array, which node- // space-joins WITHOUT escaping (DEP0190). The argv here is fixed, but the- // warning would print at every boot in both processes.- const { command, args } = prepareCliSpawn('npm', ['prefix', '-g'], env);- const { stdout } = await spawnImpl(command, args, { env, shell: false, timeoutMs: PREFIX_TIMEOUT_MS });- const prefix = String(stdout || '').trim().split(/\r?\n/)[0]?.trim() || '';- // Windows drops binaries straight in the prefix; POSIX uses `<prefix>/bin`.- return prefix ? (IS_WIN ? prefix : join(prefix, 'bin')) : null;+ // npm is itself a large Node CLI that writes its OWN module compile cache+ // under `TMPDIR`/`node-compile-cache` on every invocation (same class of+ // problem `commandExists.js`'s `probe()` isolates for `kilo`/`opencode` —+ // see its docstring, #9039). A throwaway scratch dir scoped to THIS one+ // spawn keeps that cache out of the caller's real `TMPDIR` (and, under+ // PortOS's own run-scoped vitest temp root, out of the leak report).+ const scratchDir = mkdtempSync(join(tmpdir(), 'portos-cli-probe-'));+ const env = { ...safeChildProcessEnv(), TMPDIR: scratchDir, TMP: scratchDir, TEMP: scratchDir };+ try {+ // `shell: false` + `prepareCliSpawn`, not `bufferedSpawn`'s `needsShell('npm')`+ // default: that default is `shell: true` with an args array, which node+ // space-joins WITHOUT escaping (DEP0190). The argv here is fixed, but the+ // warning would print at every boot in both processes.+ const { command, args } = prepareCliSpawn('npm', ['prefix', '-g'], env);+ const { stdout } = await spawnImpl(command, args, { env, shell: false, timeoutMs: PREFIX_TIMEOUT_MS });+ const prefix = String(stdout || '').trim().split(/\r?\n/)[0]?.trim() || '';+ // Windows drops binaries straight in the prefix; POSIX uses `<prefix>/bin`.+ return prefix ? (IS_WIN ? prefix : join(prefix, 'bin')) : null;+ } finally {+ try {+ rmSync(scratchDir, { recursive: true, force: true });+ } catch {+ // Best-effort — a lingering handle on a still-terminating npm must not+ // throw out of a probe that already has its answer.+ }+ }}/**diff --git a/server/services/agentRunReconciler.test.js b/server/services/agentRunReconciler.test.jsindex 1145433b5e..d1245f3909 100644--- a/server/services/agentRunReconciler.test.js+++ b/server/services/agentRunReconciler.test.js@@ -80,6 +80,14 @@ afterEach(() => {afterAll(() => {rmSync(LEDGER_DIR, { recursive: true, force: true });rmSync(RUNS_DIR, { recursive: true, force: true });+ // The path-traversal test below deliberately writes ONE FIXTURE outside+ // RUNS_DIR (`join(RUNS_DIR, '..', 'escape')`, i.e. a sibling directory+ // literally named "escape" in the shared temp root) to prove the service+ // refuses to follow it back in. That fixture is the point of the test, not+ // application output, but it still has to be swept here — nothing else+ // owns a path outside RUNS_DIR, and left behind it fails PortOS's own+ // run-scoped temp-root leak check (#9039).+ rmSync(join(RUNS_DIR, '..', 'escape'), { recursive: true, force: true });});describe('getRunReconciliation', () => {diff --git a/server/services/codexOssSupport.js b/server/services/codexOssSupport.jsindex 27bd83e013..e142711e14 100644--- a/server/services/codexOssSupport.js+++ b/server/services/codexOssSupport.js@@ -35,6 +35,7 @@import { commandOutput } from '../lib/commandExists.js';import { CODEX_COMMAND } from '../lib/codex.js';+import { isTestRunner } from '../lib/runtimeEnv.js';// Same window as the runtime `--version` sweep in providerRuntimeInstaller.js:// an expiry is "we no longer know", so a user who upgrades Codex from a@@ -53,6 +54,14 @@ let refreshInFlight = new Map();const readHelp = (command) => commandOutput(command, ['exec', '--help'], { timeoutMs: 10_000 });+// A caller that passes no `run` override gets this in production — but under+// the test runner it answers NOT PROBED without spawning anything, the same+// "an incidental test never asked for a real CLI probe" guard+// `providerRuntimeInstaller.js` applies to the runtime `--version` sweep+// (#9039). A test that wants the real spawn passes its own `run`, same as+// every case in `codexOssSupport.test.js` already does.+const defaultRun = (command) => (isTestRunner() ? Promise.resolve(null) : readHelp(command));+const resolveCommand = (command) => (typeof command === 'string' && command.trim()) || CODEX_COMMAND;/**@@ -78,7 +87,7 @@ export function peekCodexOssSupport(command) {* @param {{fresh?: boolean, run?: (command: string) => Promise<string|null>}} [options]* @returns {Promise<{supported: boolean}|null>}*/-export async function getCodexOssSupport(command, { fresh = false, run = readHelp } = {}) {+export async function getCodexOssSupport(command, { fresh = false, run = defaultRun } = {}) {const resolved = resolveCommand(command);if (!fresh) {const cached = peekCodexOssSupport(resolved);diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.jsindex 447f16af89..3a5808b605 100644--- a/server/services/providerRuntimeInstaller.js+++ b/server/services/providerRuntimeInstaller.js@@ -43,6 +43,10 @@ import { commandOutput } from '../lib/commandExists.js';import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';import { PROVIDER_VENDORS } from '../lib/providerVendors.js';+import { isTestRunner } from '../lib/runtimeEnv.js';++/** Stand-in for `findCommandOnPath` when a real PATH scan is skipped (below) — always "not found". */+const NEVER_FOUND = () => null;const IS_WIN = process.platform === 'win32';@@ -258,14 +262,16 @@ export function getProviderRuntime(id) {return (typeof id === 'string' && RUNTIMES_BY_ID.get(id)) || null;}-async function probeRuntimeStatus(runtime, findCommand, probeCommand) {+async function probeRuntimeStatus(runtime, findCommand, probeCommand, skipRealSpawn) {const kind = runtime.install.kind;const tool = INSTALL_TOOL[kind];// Boot adopts this already; repeat it here because the install route probes// again straight after `npm install --global`, and on a first install the// prefix directory did not exist when boot looked. Cached and idempotent.- await adoptNpmGlobalBinDir();+ // Skipped under `skipRealSpawn` (see `getProviderRuntimeStatus`) — a test+ // that never asked to probe a real binary should never spawn `npm` either.+ if (!skipRealSpawn) await adoptNpmGlobalBinDir();const [resolved, toolPath] = await Promise.all([findCommand(runtime.command), findCommand(tool)]);@@ -335,14 +341,33 @@ async function probeRuntimeStatus(runtime, findCommand, probeCommand) {* still needs, and a cached pre-install probe would fail the post-install* verification of a CLI that is now perfectly runnable.*/-export async function getProviderRuntimeStatus(id, { findCommand, probeCommand, fresh = false } = {}) {+export async function getProviderRuntimeStatus(id, { findCommand, probeCommand, fresh = false, skipRealSpawn } = {}) {const runtime = getProviderRuntime(id);if (!runtime) return null;// Keyed by the canonical id, so an alias spelling shares the same entry// instead of probing the same binary twice.const cached = statusCache.get(runtime.id);if (!fresh && cached && Date.now() - cached.at < STATUS_TTL_MS) return cached.status;- const status = await probeRuntimeStatus(runtime, findCommand || findCommandOnPath, probeCommand || commandOutput);+ // A caller that passed neither override gets the REAL PATH scan and REAL+ // `--version` spawn in production — but under the test runner that answer+ // is "not probed" (never "not installed": `installed` stays a plain+ // fail-closed false, the same shape a genuinely absent binary produces).+ // `skipRealSpawn` can also arrive explicitly from `getProviderRuntimeStatuses`+ // (below), which decides this once per batch rather than per row. This is+ // what keeps an incidental route/service test — one that never asked to+ // probe a real CLI at all — from shelling out to whatever `kilo`/`opencode`/+ // `npm` happen to be on the DEVELOPER's own PATH (#9039); a test that+ // explicitly wants the real probe still gets it by passing its own+ // `findCommand`/`probeCommand` (every `providerRuntimeInstaller.test.js`+ // case already does, and stays completely unaffected by this gate).+ const usingDefaults = skipRealSpawn === undefined && !findCommand && !probeCommand;+ const skip = skipRealSpawn ?? (usingDefaults && isTestRunner());+ const status = await probeRuntimeStatus(+ runtime,+ findCommand || (skip ? NEVER_FOUND : findCommandOnPath),+ probeCommand || commandOutput,+ skip,+ );statusCache.set(runtime.id, { at: Date.now(), status });return status;}@@ -354,11 +379,15 @@ export async function getProviderRuntimeStatus(id, { findCommand, probeCommand,* the provider is configured with, which may be an alias.*/export async function getProviderRuntimeStatuses(deps = {}) {+ // Decided ONCE for the whole batch — see `getProviderRuntimeStatus` — so+ // every row answers "not probed" together rather than racing separately+ // computed answers for the same TTL cache entry.+ const skipRealSpawn = deps.skipRealSpawn ?? (!deps.findCommand && !deps.probeCommand && isTestRunner());// One PATH scan per distinct binary for the whole batch: five rows resolve// `npm` and two resolve `curl`, and the resolver hits the filesystem.- const findCommand = memoizePerBatch(deps.findCommand || findCommandOnPath);+ const findCommand = memoizePerBatch(deps.findCommand || (skipRealSpawn ? NEVER_FOUND : findCommandOnPath));const statuses = await Promise.all(- PROVIDER_RUNTIMES.map((runtime) => getProviderRuntimeStatus(runtime.id, { ...deps, findCommand })),+ PROVIDER_RUNTIMES.map((runtime) => getProviderRuntimeStatus(runtime.id, { ...deps, findCommand, skipRealSpawn })),);const byId = new Map(statuses.map((status) => [status.id, status]));return Object.fromEntries(PROVIDER_RUNTIMES.flatMap((runtime) => {diff --git a/server/test/runTempRoot.js b/server/test/runTempRoot.jsindex 9a23b0ce28..b62eff804d 100644--- a/server/test/runTempRoot.js+++ b/server/test/runTempRoot.js@@ -40,18 +40,34 @@ export function setup() {// report — the root-level rmSync below still removes them either way.const VITEST_INTERNAL_SCRATCH_DIR = /^[A-Za-z0-9_-]{21}$/;-// A handful of PortOS's own provider-availability tests spawn a REAL,+// A handful of PortOS's own provider-availability tests used to spawn a REAL,// installed third-party CLI (kilo, opencode, …) when one is present on the-// developer's PATH (`hasCli()`-style gates) — a binary that then writes its-// OWN scratch/cache state (a config dir, a Node module compile cache, …)-// into whatever TMPDIR it inherits, which since this file is our run root.-// That state is not a PortOS temp-file leak — it belongs to the third-party-// tool, only appears on a machine that actually has the tool installed-// (invisible in CI, where those tests are gated off), and fixing it means-// giving each such CLI invocation its own isolated cache dir, tracked in-// #9039. Reported for visibility but never fails the run — unlike an-// unrecognized name, which still does.-const KNOWN_THIRD_PARTY_CLI_SCRATCH = new Set(['kilo', 'opencode', 'escape', 'node-compile-cache']);+// developer's PATH (`hasCli()`-style gates) — a binary that then wrote its OWN+// scratch/cache state (a config dir, a Node module compile cache, …) into+// whatever TMPDIR it inherited, which since this file is our run root. #9039+// traced every entry that used to land here to a real, fixable cause rather+// than an unavoidable side effect of invoking a real binary:+// - `kilo` / `opencode` — the top-level scratch dirs those two binaries+// wrote on every invocation. Fixed by isolating TMPDIR/TMP/TEMP per spawn+// (`probe()` in `server/lib/commandExists.js`) AND by no longer spawning+// them at all from an incidental test: `providerRuntimeInstaller.js`'s+// `getProviderRuntimeStatus(es)` now skips the real PATH scan/`--version`+// probe under the test runner unless a test explicitly injects its own+// `findCommand`/`probeCommand` (every genuinely real-CLI-probe test+// already does), the same guard `codexOssSupport.js`'s `getCodexOssSupport`+// applies to its own `codex exec --help` probe.+// - `escape` — was never a third-party leak: it was+// `agentRunReconciler.test.js`'s own path-traversal fixture, deliberately+// written one level outside its RUNS_DIR and simply never swept in+// `afterAll`. Fixed by sweeping it there.+// `node-compile-cache` — the confirmed cause (a real, unisolated `npm prefix+// -g` in `npmGlobalBin.js`, npm being itself a large Node CLI that writes its+// own module compile cache) is fixed the same way as `kilo`/`opencode` above.+// It still reappears here VERY rarely (observed once in ~2,500 files) with no+// real-CLI spawn in the trace that produced it — kept allowlisted rather than+// pinned on an unconfirmed cause; narrow this further if a reproducible+// trigger turns up.+const KNOWN_THIRD_PARTY_CLI_SCRATCH = new Set(['node-compile-cache']);// A leak this file is NOT the right place to fix: `server/services/// htmlComposition/*` is a different work area's tree (#9032 was explicitly