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(issue-2243): resolve+wrap CLI shim for CoS agent spawns on Windows
Adam Eivy23c3c264b8e2
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 57ac964862..b73c93a0c5 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -16,6 +16,7 @@ import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { prepareCliSpawn } from '../lib/bufferedSpawn.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { createStreamJsonParser } from './streamJsonParser.js';import { loadState, saveState, withState } from './runnerState.js';@@ -199,12 +200,23 @@ app.post('/spawn', async (req, res) => {// Ensure workspacePath is validconst cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;+ const childEnv = (() => { const e = { ...process.env, ...envVars }; delete e.CLAUDECODE; return e; })();++ // Resolve a bare npm-installed CLI (opencode/codex/claude/… — a .cmd/.bat+ // shim on Windows) to its real path and wrap a shim as `cmd.exe /c <path>` so+ // spawn() under shell:false can launch it. Without this, Windows can't find+ // `opencode.cmd` from the bare name → spawn ENOENT (errno -4058) → empty+ // output → startup-failure. Mirrors the working "Run Prompt" path+ // (server/services/runner.js); resolved against childEnv so a provider PATH+ // override is honored. See issue #2243.+ const { command: spawnCommand, args: finalSpawnArgs } = prepareCliSpawn(command, spawnArgs, childEnv);+// Spawn the CLI process- const claudeProcess = spawn(command, spawnArgs, {+ const claudeProcess = spawn(spawnCommand, finalSpawnArgs, {cwd,shell: false,stdio: ['pipe', 'pipe', 'pipe'],- env: (() => { const e = { ...process.env, ...envVars }; delete e.CLAUDECODE; return e; })(),+ env: childEnv,windowsHide: true});diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsnew file mode 100644index 0000000000..b4800bc230--- /dev/null+++ b/server/cos-runner/index.test.js@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++// index.js binds a socket server + `server.listen(PORT, HOST)` at module load,+// so it can't be imported into a unit test. These are source-inspection tests+// (the same convention as agentLifecycle.test.js) pinning the #2243 spawn fix:+// the runner must resolve+wrap a bare npm CLI shim before spawning, or a+// Windows `opencode`/`claude` .cmd shim fails with spawn ENOENT (errno -4058)+// → empty output → startup-failure.+const __dirname = dirname(fileURLToPath(import.meta.url));+const RUNNER_SRC = readFileSync(join(__dirname, 'index.js'), 'utf-8');++describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {+ it('imports prepareCliSpawn from the shared bufferedSpawn helper', () => {+ expect(RUNNER_SRC).toMatch(+ /import\s*\{\s*prepareCliSpawn\s*\}\s*from\s*'\.\.\/lib\/bufferedSpawn\.js';/+ );+ });++ it('resolves+wraps the agent CLI command before spawning it', () => {+ // The agent spawn (the /spawn handler) must feed its command/args through+ // prepareCliSpawn and spawn WHATEVER it returns — never the bare `command`.+ const call = RUNNER_SRC.match(+ /const\s*\{\s*command:\s*spawnCommand,\s*args:\s*finalSpawnArgs\s*\}\s*=\s*prepareCliSpawn\(\s*command,\s*spawnArgs,\s*childEnv\s*\)/+ );+ expect(call, 'agent spawn must call prepareCliSpawn(command, spawnArgs, childEnv)').not.toBeNull();+ // The resolved pair must be what spawn() actually receives.+ expect(RUNNER_SRC).toMatch(/spawn\(\s*spawnCommand,\s*finalSpawnArgs,/);+ });++ it('resolves the command against the child env (childEnv) so a provider PATH override is honored', () => {+ // childEnv (process.env + provider envVars, CLAUDECODE stripped) is built+ // BEFORE the resolve so PATH resolution sees the child's PATH, and is reused+ // as the spawn env — matching the working server/services/runner.js path.+ const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = (() =>');+ const prepareIdx = RUNNER_SRC.indexOf('prepareCliSpawn(command, spawnArgs, childEnv)');+ expect(childEnvIdx, 'childEnv must be defined').toBeGreaterThan(-1);+ expect(prepareIdx, 'prepareCliSpawn must run against childEnv').toBeGreaterThan(-1);+ expect(childEnvIdx, 'childEnv must be built before the resolve').toBeLessThan(prepareIdx);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 5b1fb1c39c..cdf4d915b5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -137,7 +137,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. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |-| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. |+| `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. Used by `appBuilder.js`, `appUpdater.js`, and the CoS agent spawners. || `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex b9a84ad3a9..c458b778e2 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -127,6 +127,40 @@ export function prepareWindowsSafeSpawn(command, args, isWin32 = IS_WIN32) {return { command, args };}+/**+ * Compose `resolveWindowsExecutable` + `prepareWindowsSafeSpawn` into the single+ * `{ command, args }` pair a caller should hand to `spawn()` under the default+ * `shell: false`. This is the canonical fix for spawning a bare npm-installed+ * CLI provider (`opencode`, `codex`, `claude`, …) — a `.cmd`/`.bat` shim on+ * Windows — safely: resolve the bare name to its explicit-extension path, then+ * wrap a `.cmd`/`.bat` target as `cmd.exe /c <path> <args>` (see the two+ * helpers' docstrings for why a direct `.cmd` spawn fails post-CVE-2024-27980+ * and why `shell:true` is unsafe).+ *+ * Every terminal condition off-Windows is a no-op: `resolveWindowsExecutable`+ * returns `null` (so the bare `command` is kept) and `prepareWindowsSafeSpawn`+ * returns `{ command, args }` unchanged — POSIX callers get exactly what they+ * passed in.+ *+ * Resolution reads `searchEnv.PATH`/`.Path` — pass the actual env the child+ * will run under (after merging a provider's `envVars`) so a per-provider PATH+ * override is honored; defaults to `process.env`.+ *+ * The `server/services/runner.js`, `visionCli.js`, and `cliProviderRun.js`+ * paths pre-date this helper and still inline the two-step form; new callers+ * (the Chief-of-Staff agent spawners) use this instead.+ *+ * @param {string} command - bare command name, or an existing path+ * @param {string[]} args+ * @param {NodeJS.ProcessEnv} [searchEnv] - env to read PATH from; defaults to `process.env`+ * @param {boolean} [isWin32] - injectable for tests; defaults to the real platform+ * @returns {{ command: string, args: string[] }} launchable pair for `spawn()`+ */+export function prepareCliSpawn(command, args, searchEnv = process.env, isWin32 = IS_WIN32) {+ const resolved = resolveWindowsExecutable(command, isWin32, searchEnv) || command;+ return prepareWindowsSafeSpawn(resolved, args, isWin32);+}+// cmd.exe metacharacters that act as command separators / redirection /// grouping on its raw command line.const CMD_METACHAR_RE = /[&|<>^()]/g;diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 3af8e4e01a..82d73010f6 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -24,6 +24,7 @@ const {needsShell,resolveWindowsExecutable,prepareWindowsSafeSpawn,+ prepareCliSpawn,IS_WIN32,WIN_CMD_SHIMS,MAX_OUTPUT_BYTES,@@ -254,6 +255,53 @@ describe('prepareWindowsSafeSpawn', () => {});});+describe('prepareCliSpawn (composed resolve+wrap — the CoS spawn fix, #2243)', () => {+ // isWin32 is passed explicitly so these tests are deterministic regardless of+ // the host platform actually running them. A real fakePathDir on PATH lets+ // resolveWindowsExecutable find the shim.+ let fakePathDir;++ beforeEach(async () => {+ fakePathDir = await mkdtemp(join(tmpdir(), 'prepare-cli-spawn-'));+ });++ afterEach(async () => {+ await rm(fakePathDir, { recursive: true, force: true });+ });++ it('resolves a bare .cmd shim on PATH AND wraps it in cmd.exe /c (the end-to-end Windows fix)', async () => {+ // This is exactly the CoS bug: on Windows a bare `opencode` can neither be+ // resolved nor spawned directly — prepareCliSpawn turns it into a+ // launchable `cmd.exe /c <opencode.cmd> ...` pair. The env override is what+ // the CoS spawners pass (childEnv) so a provider PATH is honored.+ await writeFile(join(fakePathDir, 'opencode.cmd'), '@echo off\n');+ const result = prepareCliSpawn('opencode', ['run', '-m', 'ollama/qwen2.5:7b-instruct'], { PATH: fakePathDir }, true);+ expect(result).toEqual({+ command: 'cmd.exe',+ args: ['/c', join(fakePathDir, 'opencode.cmd'), 'run', '-m', 'ollama/qwen2.5:7b-instruct'],+ });+ });++ it('resolves a bare command to a real .exe and leaves it unwrapped on Windows', async () => {+ await writeFile(join(fakePathDir, 'opencode.exe'), '');+ const result = prepareCliSpawn('opencode', ['run'], { PATH: fakePathDir }, true);+ expect(result).toEqual({ command: join(fakePathDir, 'opencode.exe'), args: ['run'] });+ });++ it('keeps the bare command when nothing resolves on PATH (Windows fallback)', () => {+ const result = prepareCliSpawn('opencode', ['run'], { PATH: fakePathDir }, true);+ expect(result).toEqual({ command: 'opencode', args: ['run'] });+ });++ it('is a no-op off Windows — passes the bare command + args straight through (POSIX unaffected)', async () => {+ // Even with a matching .cmd on PATH, the POSIX branch never resolves or+ // wraps: spawn() resolves `opencode` from PATH itself under shell:false.+ await writeFile(join(fakePathDir, 'opencode.cmd'), '@echo off\n');+ const result = prepareCliSpawn('opencode', ['run', '-m', 'ollama/x'], { PATH: fakePathDir }, false);+ expect(result).toEqual({ command: 'opencode', args: ['run', '-m', 'ollama/x'] });+ });+});+describe('bufferedSpawn — structured result', () => {it('resolves success on a clean (code 0) exit and captures stdout/stderr', async () => {const child = makeFakeChild();diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex ca2a72a005..e8d1a6d960 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -29,6 +29,7 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antimport { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';+import { prepareCliSpawn } from '../lib/bufferedSpawn.js';const AGENTS_DIR = PATHS.cosAgents;@@ -421,16 +422,26 @@ export async function spawnDirectly({// the models map so --model is accepted (the static env var lacked this).const opencodeEnv = buildOpencodeEnvVars(provider, model);- const claudeProcess = spawn(cliConfig.command, cliConfig.args, {+ // The pm2 shim must be prepended onto the FINAL PATH (after any+ // provider.envVars override) so a `--dangerously-skip-permissions` agent+ // can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override+ // the static OPENCODE_CONFIG_CONTENT in provider.envVars.+ const childEnv = (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();++ // Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real+ // path and wrap a shim as `cmd.exe /c <path>` so spawn() under shell:false+ // can launch it — without this Windows can't find e.g. `opencode.cmd` from the+ // bare name → spawn ENOENT (errno -4058) → startup-failure. Mirrors the+ // working "Run Prompt" path (server/services/runner.js); resolved against+ // childEnv so a provider PATH override is honored. See issue #2243.+ const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(cliConfig.command, cliConfig.args, childEnv);++ const claudeProcess = spawn(spawnCommand, spawnArgs, {cwd,shell: false,stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true,- // The pm2 shim must be prepended onto the FINAL PATH (after any- // provider.envVars override) so a `--dangerously-skip-permissions` agent- // can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override- // the static OPENCODE_CONFIG_CONTENT in provider.envVars.- env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()+ env: childEnv});registerSpawnedAgent(claudeProcess.pid, {diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 6bda283ce6..f54ff415bd 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -67,6 +67,13 @@ vi.mock('fs/promises', () => ({}));vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));+// Default passthrough for the Windows resolve+wrap helper (#2243) — POSIX+// behavior. A specific test overrides it with mockReturnValueOnce to assert the+// spawn wiring uses whatever prepareCliSpawn returns.+vi.mock('../lib/bufferedSpawn.js', () => ({+ prepareCliSpawn: vi.fn((command, args) => ({ command, args })),+}));+// Mock child_process.spawn to return a controllable fake processlet fakeProcess;vi.mock('child_process', () => ({@@ -78,6 +85,8 @@ vi.mock('child_process', () => ({}));import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';+import { spawn } from 'child_process';+import { prepareCliSpawn } from '../lib/bufferedSpawn.js';// Helper: feed the parser a sequence of stream-json linesfunction runStream(parser, events) {@@ -341,6 +350,9 @@ describe('stream error containment', () => {(await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);(await import('./agentLifecycle.js')).finalizeAgent.mockResolvedValue(undefined);minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);+ // Reset the resolve+wrap helper to its POSIX passthrough before each test+ // (afterEach's restoreAllMocks can clear the factory implementation).+ vi.mocked(prepareCliSpawn).mockImplementation((command, args) => ({ command, args }));});afterEach(() => {@@ -419,6 +431,37 @@ describe('stream error containment', () => {expect(logged).toBe(true);});+ it('routes the CLI command through prepareCliSpawn and spawns its resolved+wrapped result (#2243)', async () => {+ // The reported bug: on Windows a bare `opencode`/`claude` .cmd shim can't be+ // spawned directly under shell:false → ENOENT (-4058) → startup-failure.+ // spawnDirectly must hand the command through prepareCliSpawn (resolve ++ // cmd.exe wrap) and spawn WHATEVER it returns — asserted here with a sentinel.+ vi.mocked(prepareCliSpawn).mockReturnValueOnce({+ command: 'cmd.exe',+ args: ['/c', 'C:\\npm\\claude.cmd', '--print'],+ });++ const spawnPromise = spawnDirectly(minimalArgs);+ await new Promise((r) => setTimeout(r, 10)); // let the getClaudeSettingsEnv await settle++ // Called with the logical command + args and the child env (PATH-bearing) so+ // a provider PATH override is honored.+ expect(prepareCliSpawn).toHaveBeenCalledWith(+ minimalArgs.cliConfig.command,+ minimalArgs.cliConfig.args,+ expect.objectContaining({ PATH: expect.anything() }),+ );+ // spawn() received the resolved+wrapped pair, NOT the bare command.+ expect(spawn).toHaveBeenCalledWith(+ 'cmd.exe',+ ['/c', 'C:\\npm\\claude.cmd', '--print'],+ expect.objectContaining({ shell: false }),+ );++ fakeProcess.emit('close', 0);+ await spawnPromise.catch(() => {});+ });+describe('initialization timeout — 3-second phase transition', () => {it('calls updateAgent with working phase after 3s when agent has not started working', async () => {const { activeAgents } = await import('./agentState.js');diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 79c28f8eaa..86d0aa947a 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -23,6 +23,7 @@ import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysimport { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand } from '../lib/providerModels.js';+import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';@@ -632,13 +633,21 @@ export async function spawnViaRunner(agentId, task, opts) {? await getClaudeSettingsEnv(): {};+ // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with the+ // models map so the injected `--model ollama/<id>` is accepted (empty/no-op+ // otherwise). The direct-spawn path (agentCliSpawning.spawnDirectly) and the+ // "Run Prompt" path (server/services/runner.js) already do this; the runner+ // path omitted it, so an OpenCode Ollama CoS task on the runner would reject+ // the model even after the spawn itself succeeds. See issue #2243 / #2190.+ const opencodeEnv = buildOpencodeEnvVars(provider, model);+const result = await spawnAgentViaRunner({agentId,taskId: task.id,prompt,workspacePath,model,- envVars: { ...claudeSettingsEnv, ...provider.envVars },+ envVars: { ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv },cliCommand: cliConfig.command,cliArgs: cliConfig.args});diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 327fe0fba1..e4a0c01a7c 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -755,6 +755,31 @@ describe('agentLifecycle — instance provenance stamping (#1563)', () => {});});+describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () => {+ it('source: imports buildOpencodeEnvVars from opencodeConfig', () => {+ expect(AGENT_LIFECYCLE_SRC).toMatch(+ /import\s*\{\s*buildOpencodeEnvVars\s*\}\s*from\s*'\.\.\/lib\/opencodeConfig\.js';/+ );+ });++ it('source: spawnViaRunner merges buildOpencodeEnvVars into the runner envVars so --model ollama/<id> is accepted', () => {+ // The direct-spawn path and the "Run Prompt" path already inject the dynamic+ // OPENCODE_CONFIG_CONTENT (models map); the runner path omitted it, so an+ // OpenCode Ollama CoS task on the runner rejected the model even after the+ // spawn succeeded. Assert the merge exists inside spawnViaRunner and that the+ // env passed to the runner unions it.+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');+ expect(fnStart, 'spawnViaRunner must exist').toBeGreaterThan(-1);+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 4000);+ const buildIdx = fnBody.indexOf('buildOpencodeEnvVars(provider, model)');+ expect(buildIdx, 'must build the opencode env from provider+model').toBeGreaterThan(-1);+ // The spread must reach the envVars handed to spawnAgentViaRunner.+ expect(fnBody).toMatch(/envVars:\s*\{[^}]*\.\.\.opencodeEnv[^}]*\}/);+ expect(fnBody.indexOf('...opencodeEnv'), 'opencodeEnv must be spread AFTER provider.envVars so it overrides the static config')+ .toBeGreaterThan(fnBody.indexOf('...provider.envVars'));+ });+});+// ─── handleAgentCompletion error recovery ──────────────────────────────────//// `handleAgentCompletion` (agentLifecycle.js:841) does: