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: retain executable discovery when PATH probes fail
[._.]/ Adam Eivy737da6072c48
diff --git a/server/lib/README.md b/server/lib/README.mdindex e0247c9013..219ce4f56b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -404,7 +404,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. || `npmGlobalBin.js` | `adoptNpmGlobalBinDir()` — puts the directory `npm install --global` actually writes to onto `process.env.PATH`, from one cached `npm prefix -g`. npm resolves its prefix through a config cascade (cli flags, `npm_config_*`, project/user/global npmrc, a builtin npmrc that interpolates env vars), so guessing it from `%APPDATA%`/`$HOME` reproduces the bug on the next host — only npm can answer. Exists because a host whose npm prefix is NOT the directory its Node installer put on PATH (a machine-wide Windows prefix vs the per-user `%APPDATA%pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and then reported it unrunnable, advising a restart that inherits the same PATH. Called at boot in BOTH processes that spawn provider CLIs (`services/bootstrap.js`, `cos-runner/index.js`) and again from `providerRuntimeInstaller.js`'s probe, because on a first install the prefix directory did not exist when boot looked. |-| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. |+| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout, direct PATH fallback on probe failure) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. || `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. || `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. `resolveRemoteDefaultRef(path)` resolves local origin/HEAD, origin/main, then origin/master to `{ref, sha}` or null without fetching; also used by run-window diffs. || `ptySpawnDiagnostics.js` | `diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe})` + `probePtyRuntime(pty, cwd)` and the `PTY_UNAVAILABLE_PREFIX` / `PTY_WORKSPACE_MISSING_PREFIX` markers — turns node-pty’s one opaque `posix_spawn failed: No such file or directory` into a named fault. The executable is already cleared upstream (PATH resolve + `--version` probe), so a throw is either a `cwd` that vanished (cheap `existsSync`) or a PTY layer that cannot fork AT ALL — proven by re-forking a known-good command in a known-good directory; `diagnosed: false` means neither matched, and the caller re-throws rather than inventing a cause. **Retry policy is the caller’s and the two faults differ:** `agentTuiSpawning.js` matches only the PTY-layer prefix, mapping it to the actionable `runner-pty-unavailable` so the task blocks once with the repair, while a reaped workspace falls through to the retrying `spawn-rejected` because the next attempt provisions a fresh worktree. The motivating outage: an `npm ci` inside a CoS worktree emptied the primary checkout’s `server/node_modules` through a symlink, deleting the `spawn-helper` binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy. |diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex 7491757685..1960450ef4 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -134,9 +134,10 @@ export function buildSafeCliBaseEnv(env = process.env, provider = null) {// Resolve the first PATH hit for a binary via `which` (POSIX) / `where`// (Windows) — the "is this system tool installed, and where?" probe copied// inline across ytdlp/ffmpeg/pythonSetup/voice discovery. Returns the absolute-// path of the first match, or `null` when the binary isn't on PATH or the-// probe fails. Spawns through `safeChildProcessEnv()` (Malloc-stripped) with a-// 5s timeout; `where` can return several lines, so we take the first.+// path of the first match, or `null` when the binary isn't on PATH. Spawns+// with a 5s timeout; `where` can return several lines, so we take the first.+// If the probe fails (including a slow Windows subprocess startup), resolve+// the same PATH directly instead of declaring an installed tool unavailable.// Synchronous `whichFirst`, for the few callers that resolve a binary while// building a spawn and cannot await (pythonSetup's detectPythonSync, behind the// installer spawn). Same contract: absolute path of the first match, or null.@@ -148,14 +149,14 @@ export function whichFirstSync(name) {}));return stdout.trim().split(/\r?\n/)[0] || null;} catch {- return null; // not on PATH, or the probe itself failed+ return findCommandOnPath(name);}}export async function whichFirst(name) {const cmd = IS_WIN ? 'where' : 'which';const { stdout } = await execFileAsync(cmd, [name], safeChildProcessOptions({ timeout: 5000 }))- .catch(() => ({ stdout: '' }));+ .catch(() => ({ stdout: findCommandOnPath(name) || '' }));return stdout.trim().split(/\r?\n/)[0] || null;}diff --git a/server/lib/processEnv.spawnOptions.test.js b/server/lib/processEnv.spawnOptions.test.jsindex 2adc003f21..62f90fdede 100644--- a/server/lib/processEnv.spawnOptions.test.js+++ b/server/lib/processEnv.spawnOptions.test.js@@ -1,4 +1,5 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { basename, dirname } from 'path';const childProcessMocks = vi.hoisted(() => ({execFile: vi.fn(),@@ -31,6 +32,8 @@ describe('PATH probe spawn options', () => {childProcessMocks.execFileSync.mockReset();});+ afterEach(() => vi.unstubAllEnvs());+it('hides the async probe console', async () => {childProcessMocks.execFile.mockImplementation((_cmd, _args, _opts, callback) => {callback(null, { stdout: '/example/node\n', stderr: '' });@@ -50,4 +53,18 @@ describe('PATH probe spawn options', () => {windowsHide: true,}));});++ it.each([+ ['async', whichFirst],+ ['sync', whichFirstSync],+ ])('still discovers installed executables when the %s probe times out', async (_mode, probe) => {+ vi.stubEnv('PATH', dirname(process.execPath));+ vi.stubEnv('Path', dirname(process.execPath));+ const timeout = Object.assign(new Error('PATH probe timed out'), { killed: true, signal: 'SIGTERM' });+ childProcessMocks.execFile.mockImplementation((_cmd, _args, _opts, callback) => callback(timeout));+ childProcessMocks.execFileSync.mockImplementation(() => { throw timeout; });++ expect(await probe(basename(process.execPath))).toBe(process.execPath);+ expect(await probe('portos-nonexistent-binary-xyz-2392')).toBeNull();+ });});