Skip to content

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

refactor([issue-3193]): discover cwd-passing spawns instead of listing them, and cover the sites that found

[._.]/ Adam Eivy9e6dc567eed2
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 431a2ade07..e51468c517 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -188,12 +188,9 @@ app.post('/spawn', async (req, res) => {
// Ensure workspacePath is valid
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
- // withSpawnCwdEnv pins PWD to `cwd`. Passing `cwd` to spawn() changes the
- // child's real working directory but leaves the inherited PWD naming the
- // PortOS checkout this runner was started in — and OpenCode resolves its
- // project root as `process.env.PWD ?? process.cwd()`, so every CoS agent on
- // that provider wrote into the PortOS folder while this handler's own log line
- // correctly reported the app's workspace. See issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). This is the path the
+ // bug was reported through: the log line above named the app's workspace
+ // correctly while every OpenCode agent still ran in the PortOS folder.
const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...envVars }, cwd); delete e.CLAUDECODE; return e; })();
// Resolve a bare npm-installed CLI (opencode/codex/claude/… — a .cmd/.bat
diff --git a/server/lib/README.md b/server/lib/README.md
index 4623211602..3bd8e91b2f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -157,7 +157,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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`, `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. |
-| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every AI CLI/TUI spawn site.
+| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `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/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 0e093be742..996af2dd53 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -408,21 +408,21 @@ export function createRunnerService(config = {}) {
const args = [...(provider.args || [])];
console.log(`🚀 Executing CLI: ${provider.command} ${args.join(' ')} (${prompt.length} chars via stdin)`);
- // PWD is pinned to the spawn cwd: passing `cwd` to spawn() changes the
- // child's real working directory but leaves the inherited PWD naming the
- // directory the host process was started in, and OpenCode resolves its
- // project root as `process.env.PWD ?? process.cwd()` — so it would run in
- // the host's directory instead of `workspacePath` (issue #3193). Inlined
- // rather than importing PortOS's `withSpawnCwdEnv` because this toolkit is
- // vendored and must not import out to other PortOS modules. The
- // case-insensitive filter matters on Windows, where a spread of
- // `process.env` can surface this variable as `Pwd`/`pwd` and a second
- // `PWD` key would hand the child two spellings of one variable.
- const childEnv = Object.fromEntries(
- Object.entries({ ...process.env, ...provider.envVars })
- .filter(([key]) => !(workspacePath && /^pwd$/i.test(key))),
- );
- if (workspacePath) childEnv.PWD = workspacePath;
+ // Pin PWD to the spawn cwd — `spawn({ cwd })` does not rewrite the
+ // inherited PWD, and OpenCode resolves its project root as
+ // `process.env.PWD ?? process.cwd()`, so it would run wherever the host
+ // process was started instead of in `workspacePath`. Deliberately mirrors
+ // PortOS's `withSpawnCwdEnv` line for line rather than importing it: this
+ // toolkit is vendored and must not import out to other PortOS modules.
+ // (PortOS overrides `executeCliRun` via `setCliRunner`, so this particular
+ // spawn is dormant here — the copy keeps the vendored toolkit correct
+ // standalone.) The case-insensitive delete matters on Windows, where a
+ // spread of `process.env` can surface the variable as `Pwd`/`pwd`.
+ const childEnv = { ...process.env, ...provider.envVars };
+ if (workspacePath) {
+ for (const key of Object.keys(childEnv)) if (/^pwd$/i.test(key)) delete childEnv[key];
+ childEnv.PWD = workspacePath;
+ }
// Resolved against `childEnv` (not bare process.env) so a
// provider-configured PATH override is honored.
const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 58eb5defa6..ca77fb94a5 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -1,6 +1,7 @@
import { spawn, ChildProcess } from 'child_process';
import { existsSync } from 'fs';
import { delimiter, isAbsolute, join } from 'path';
+import { withSpawnCwdEnv } from './spawnCwd.js';
/**
* Shared buffered-spawn + Windows kill-tree machinery used by the app build and
@@ -268,6 +269,12 @@ export function bufferedSpawn(cmd, args, { cwd, timeoutMs, shell } = {}) {
return new Promise((resolve) => {
const child = spawn(cmd, args, {
cwd,
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). Done in this
+ // shared wrapper rather than at each caller so every present and future
+ // bufferedSpawn user inherits it; `withSpawnCwdEnv` returns an unchanged
+ // copy of process.env when no cwd was given, matching the previous
+ // implicit-inherit behavior exactly.
+ env: withSpawnCwdEnv(process.env, cwd),
windowsHide: true,
shell: shell === undefined ? needsShell(cmd) : shell,
});
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 11b4f5a1a6..3c099fb397 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -108,9 +108,7 @@ export function runCliProviderPrompt(args = {}) {
// models map for OpenCode Ollama providers (empty/no-op otherwise) so the
// injected `--model ollama/<id>` isn't rejected as "not valid" — see
// issue-2190. effectiveProvider carries the per-call model as defaultModel.
- // withSpawnCwdEnv pins PWD to the directory this child actually runs in, so
- // a CLI that reads its project root from PWD (OpenCode does) can't fall back
- // to the PortOS checkout the server was started in — see issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
const effectiveCwd = cwd || process.cwd();
const childEnv = withSpawnCwdEnv(
{ ...baseEnv, ...provider.envVars, ...buildOpencodeEnvVars(effectiveProvider, effectiveProvider.defaultModel) },
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 2ba2c74886..39421aecc1 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -49,6 +49,7 @@ import { constants as osConstants } from 'os';
import { join } from 'path';
import { open, readFile, rm, stat, readdir } from 'fs/promises';
import { ensureDir, sleep } from './fileUtils.js';
+import { withSpawnCwdEnv } from './spawnCwd.js';
// Default cadence for tailing the job's log files and polling for completion.
// 250ms matches the high-frequency-write batching cadence used elsewhere — far
@@ -219,7 +220,7 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
// exitCode / signalCode), so callers are unaffected. Surviving a pm2 restart
// is a POSIX-only guarantee; Windows keeps its prior spawn semantics.
if (process.platform === 'win32') {
- return spawn(bin, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'] });
+ return spawn(bin, args, { env: withSpawnCwdEnv(env ?? process.env, cwd), cwd, stdio: ['ignore', 'pipe', 'pipe'] });
}
const handle = new EventEmitter();
@@ -259,7 +260,8 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
// launcher; `.unref()` so the server never waits on the (instantly-exiting)
// outer sh.
const launcher = spawn('sh', ['-c', LAUNCHER, 'sh', controlDir, bin, ...args], {
- env,
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
+ env: withSpawnCwdEnv(env ?? process.env, cwd),
cwd,
detached: true,
stdio: 'ignore',
diff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.js
index 14b163911b..5e571bb215 100644
--- a/server/lib/spawnCwd.js
+++ b/server/lib/spawnCwd.js
@@ -118,15 +118,12 @@ const PWD_KEY_RE = /^pwd$/i;
* @returns {object} a copy of `env` with `PWD` set to `cwd` (unchanged copy when `cwd` is absent)
*/
export function withSpawnCwdEnv(env, cwd) {
- const next = {};
- const pin = typeof cwd === 'string' && cwd.length > 0;
- for (const [key, value] of Object.entries(env || {})) {
- // Only strip the stale variants when there's a real value to replace them
- // with — otherwise a caller that spawns without an explicit cwd would have
- // its inherited PWD deleted, which is a different (and equally wrong) lie.
- if (pin && PWD_KEY_RE.test(key)) continue;
- next[key] = value;
- }
- if (pin) next.PWD = cwd;
+ const next = { ...(env || {}) };
+ // No cwd means the child inherits the parent's real working directory, so the
+ // inherited PWD is already truthful — stripping it would substitute a
+ // different lie for the one being fixed.
+ if (typeof cwd !== 'string' || !cwd) return next;
+ for (const key of Object.keys(next)) if (PWD_KEY_RE.test(key)) delete next[key];
+ next.PWD = cwd;
return next;
}
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 3c06a5b6bc..0d48da49ac 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from 'fs';
import { tmpdir, homedir } from 'os';
-import { join } from 'path';
+import { join, relative } from 'path';
+import { fileURLToPath } from 'url';
import { resolveSpawnCwd, withSpawnCwdEnv } from './spawnCwd.js';
describe('resolveSpawnCwd', () => {
@@ -185,39 +186,108 @@ describe('withSpawnCwdEnv', () => {
});
});
-// Source invariant: every place PortOS spawns an AI CLI/TUI into a user
-// workspace must pin PWD, or that provider silently runs in the PortOS checkout
-// again (#3193). A unit-tested helper is worthless if a new spawn site forgets
-// to call it, and the failure is invisible in normal use — the spawn logs still
-// print the right cwd, only the FILES land in the wrong repo. So assert the call
-// at each site rather than trusting convention.
-describe('every AI CLI/TUI spawn site pins PWD to its spawn cwd', () => {
- const SPAWN_SITES = [
- // The #3193 repro: CoS task → runner → OpenCode agent.
- ['../cos-runner/index.js', 'withSpawnCwdEnv('],
- // Settings → Providers → Run Prompt (the #3180 repro path).
- ['../services/runner.js', 'withSpawnCwdEnv('],
- // CoS agent spawned in-process rather than through the runner.
- ['../services/agentCliSpawning.js', 'withSpawnCwdEnv('],
- // Every PTY session: the user's Shell page and agent-TUI sessions, which
- // inject the CLI command into this shell.
- ['../services/shell.js', 'withSpawnCwdEnv('],
- // Fire-and-collect CLI prompts (vision, app detect, feature helpers).
- ['./cliProviderRun.js', 'withSpawnCwdEnv('],
- // TUI-driven one-shot prompt runs (PTY spawned directly, no login shell to
- // rewrite PWD for us).
- ['./tuiPromptRunner.js', 'withSpawnCwdEnv('],
- // `/usage` quota scraping — spawns the TUI in a throwaway sandbox dir.
- ['./tuiUsageScrape.js', 'withSpawnCwdEnv('],
- // The vendored toolkit must not import out to other PortOS modules, so it
- // inlines the same pin instead of calling the shared helper.
- ['./aiToolkit/runner.js', 'childEnv.PWD = workspacePath'],
- ];
-
- for (const [relPath, marker] of SPAWN_SITES) {
- it(`${relPath} pins PWD`, () => {
- const src = readFileSync(new URL(relPath, import.meta.url), 'utf8');
- expect(src, `${relPath} spawns an AI CLI/TUI — it must pin PWD to the spawn cwd (see withSpawnCwdEnv)`).toContain(marker);
- });
- }
+// Source invariant: any spawn that names its own working directory must also
+// pin PWD, or a CLI that reads PWD (OpenCode does) silently runs in the PortOS
+// checkout again (#3193). A unit-tested helper is worthless if a new spawn site
+// forgets to call it, and this failure is invisible in normal use — the spawn
+// logs still print the right cwd, only the FILES land in the wrong repo.
+//
+// Deliberately DISCOVERS the spawn sites rather than listing them: an allowlist
+// of "these files must contain the call" passes the day someone adds a ninth
+// spawn site, which is exactly when the guard needs to fire. Here a new
+// cwd-passing spawn fails the suite until it is either pinned or explicitly
+// exempted below with a reason.
+describe('every cwd-passing spawn pins PWD', () => {
+ const SERVER_DIR = fileURLToPath(new URL('..', import.meta.url));
+
+ // Files whose cwd-passing spawn does NOT need the pin, each with the reason it
+ // is safe. Anything not listed here must pin. The common reason is "this spawns
+ // a tool that resolves paths from its real cwd, never from PWD" — git, gh,
+ // glab, pm2, psql, npm, xcodegen, python.
+ const EXEMPT = new Map([
+ ['services/git.js', 'git/gh resolve from real cwd (and -C), never PWD'],
+ ['lib/execGit.js', 'git only'],
+ ['lib/planIds.js', 'git only'],
+ ['services/githubCloner.js', 'git clone/fetch only'],
+ ['services/gitlab.js', 'glab only'],
+ ['services/perpetualWork.js', 'git/gh/glab probes only'],
+ ['services/pm2Standardizer.js', 'git + pm2 only'],
+ ['services/pm2.js', 'pm2 only'],
+ ['services/appDeployer.js', 'deploy shell commands, not an AI CLI'],
+ ['services/xcodeScripts.js', 'xcodebuild/ls, not an AI CLI'],
+ ['services/imageTo3d/trellis2.js', 'python/uv toolchain inside its own install root'],
+ ['services/updateExecutor.js', "PortOS's own update scripts, run in the PortOS root by design"],
+ ['services/calendarGoogleSync.js', 'runs in process.cwd(), so the inherited PWD is already truthful'],
+ ['routes/database.js', 'psql/pg_dump, not an AI CLI'],
+ ['routes/scaffold.js', 'npm/git scaffolding, not an AI CLI'],
+ ['routes/scaffoldVite.js', 'npm scaffolding, not an AI CLI'],
+ ['routes/scaffoldIOS.js', 'xcodegen, not an AI CLI'],
+ ['routes/scaffoldXcode.js', 'xcodegen, not an AI CLI'],
+ ['routes/apps/launch.js', "detached launch into the user's own terminal; the CLI reads process.cwd()"],
+ ]);
+
+ // Files whose cwd-passing spawns all go through a shared wrapper that already
+ // pins, so they need no call of their own.
+ const DELEGATES = new Map([
+ ['services/appBuilder.js', 'bufferedSpawn'],
+ ['services/agentRunTracking.js', 'bufferedSpawn'],
+ ]);
+
+ // Files that pin by inlining the assignment instead of calling the shared
+ // helper, with the reason they cannot call it.
+ const INLINE_PIN = new Map([
+ ['lib/aiToolkit/runner.js', 'vendored toolkit — must not import out to other PortOS modules'],
+ ]);
+
+ const SPAWN_CALL_RE = /\b(?:spawn|ptySpawn|spawnImpl|pty\.spawn|bufferedSpawn|execFile|execAsync)\s*\(/g;
+
+ /** Recursively collect non-test .js files under `dir`, as server-relative paths. */
+ const collectSources = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) return [];
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) return collectSources(abs);
+ if (!entry.name.endsWith('.js') || entry.name.endsWith('.test.js')) return [];
+ return [relative(SERVER_DIR, abs)];
+ });
+
+ // A spawn "passes a cwd" when a `cwd` option appears within the call's own
+ // options object. Scanning a short window after the call open-paren keeps this
+ // to a regex instead of a parser, at the cost of the occasional false positive
+ // — which is fine: a false positive is an exemption line, not a wrong pass.
+ const passesCwd = (src) => {
+ for (const match of src.matchAll(SPAWN_CALL_RE)) {
+ if (/\bcwd\s*[:,]/.test(src.slice(match.index, match.index + 400))) return true;
+ }
+ return false;
+ };
+
+ it('discovers the cwd-passing spawn sites (guard is not vacuous)', () => {
+ const found = collectSources(SERVER_DIR).filter((rel) => passesCwd(readFileSync(join(SERVER_DIR, rel), 'utf8')));
+ // If this ever collapses toward zero the scan broke (a rename, a new spawn
+ // wrapper) and every assertion below would pass for the wrong reason.
+ expect(found.length, 'expected the scan to still find the known spawn sites').toBeGreaterThan(10);
+ expect(found).toContain('cos-runner/index.js');
+ expect(found).toContain('services/shell.js');
+ });
+
+ it('every cwd-passing spawn either pins PWD or is explicitly exempt', () => {
+ const unpinned = [];
+ for (const rel of collectSources(SERVER_DIR)) {
+ const src = readFileSync(join(SERVER_DIR, rel), 'utf8');
+ if (!passesCwd(src)) continue;
+ if (EXEMPT.has(rel)) continue;
+ if (DELEGATES.has(rel) && src.includes(DELEGATES.get(rel))) continue;
+ const pinned = INLINE_PIN.has(rel)
+ ? /childEnv\.PWD\s*=/.test(src)
+ : src.includes('withSpawnCwdEnv(');
+ if (!pinned) unpinned.push(rel);
+ }
+ expect(
+ unpinned,
+ 'These files spawn a child with an explicit cwd but never pin PWD. A CLI that '
+ + 'resolves its project root from PWD (OpenCode does) will ignore that cwd and run '
+ + 'in the PortOS checkout instead — see withSpawnCwdEnv in server/lib/spawnCwd.js '
+ + '(#3193). Either pin PWD, or add the file to EXEMPT above with the reason it is safe.',
+ ).toEqual([]);
+ });
});
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index 153c459e5d..e20b98977e 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -177,9 +177,8 @@ ${prompt}`;
// for the same reason.
// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with
// the models map so --model is accepted (the static env var lacked this).
- // withSpawnCwdEnv pins PWD to the directory this TUI actually runs in, so a
- // CLI that reads its project root from PWD (OpenCode does) can't fall back to
- // the PortOS checkout the server was started in — see issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). This PTY runs the
+ // CLI directly, so there is no login shell to rewrite PWD for us.
const opencodeEnv = buildOpencodeEnvVars(provider, provider.defaultModel);
const childEnv = withSpawnCwdEnv(
{ ...process.env, ...(provider.envVars || {}), ...opencodeEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.js
index 2dfa12dd75..0f5512875c 100644
--- a/server/lib/tuiUsageScrape.js
+++ b/server/lib/tuiUsageScrape.js
@@ -99,9 +99,8 @@ export async function scrapeTuiUsage({
// Provider envVars (auth/config) merged over process.env, then the PTY hints.
// CLAUDECODE leaks when PortOS itself runs under Claude Code; strip it so a
// spawned TUI doesn't think it's nested (mirrors tuiPromptRunner.js).
- // withSpawnCwdEnv pins PWD to the sandbox dir so a CLI that reads its project
- // root from PWD (OpenCode does) scrapes usage from the sandbox rather than
- // opening the PortOS checkout as a project. See issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). Keeps the scrape in
+ // the throwaway sandbox instead of opening the PortOS checkout as a project.
const env = withSpawnCwdEnv(
{ ...process.env, ...extraEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },
sandboxDir,
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 983ca5e1b3..84f306f940 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -492,8 +492,7 @@ export async function spawnDirectly({
// can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override
// the static OPENCODE_CONFIG_CONTENT in provider.envVars; forgeTokenEnv sits
// before provider.envVars so an explicit provider GH_TOKEN override still wins.
- // withSpawnCwdEnv pins PWD to `cwd` so a CLI that reads its project root from
- // PWD (OpenCode does) can't fall back to the PortOS checkout — see issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }, cwd); 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
diff --git a/server/services/autonomousJobs/execution.js b/server/services/autonomousJobs/execution.js
index f0b090ed2b..4142c87abc 100644
--- a/server/services/autonomousJobs/execution.js
+++ b/server/services/autonomousJobs/execution.js
@@ -11,6 +11,7 @@
import { spawn } from 'child_process'
import { PATHS } from '../../lib/fileUtils.js'
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js'
import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../../lib/commandSecurity.js'
import { cosEvents } from '../cosEvents.js'
import { withLock } from './constants.js'
@@ -74,6 +75,10 @@ async function executeShellJob(job) {
let killed = false
const child = spawn(validation.baseCommand, validation.args || [], {
cwd: PATHS.root,
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). The allowlist
+ // includes AI CLIs, and the inherited PWD only happens to match PATHS.root
+ // when the server was started from its own checkout.
+ env: withSpawnCwdEnv(process.env, PATHS.root),
shell: false,
windowsHide: true
})
diff --git a/server/services/commands.js b/server/services/commands.js
index 229d9177cf..2ad5b12065 100644
--- a/server/services/commands.js
+++ b/server/services/commands.js
@@ -2,6 +2,7 @@ import { spawn } from 'child_process';
import { logAction } from './history.js';
import { ALLOWED_COMMANDS, validateCommand } from '../lib/commandSecurity.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
// Track active commands
const activeCommands = new Map();
@@ -38,9 +39,13 @@ export function executeCommand(command, workspacePath, onData, onComplete) {
// it strips macOS Malloc* debug noise but intentionally inherits the rest of
// the parent env — allowlisted commands like gh/git/npm legitimately need
// PATH/HOME and their auth tokens.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). The allowlist
+ // includes AI CLIs, so a command run against an app workspace must not be told
+ // it lives in the PortOS checkout.
+ const commandCwd = workspacePath || process.cwd();
const child = spawn(baseCommand, args, {
- cwd: workspacePath || process.cwd(),
- env: safeChildProcessEnv({ FORCE_COLOR: '1' }),
+ cwd: commandCwd,
+ env: withSpawnCwdEnv(safeChildProcessEnv({ FORCE_COLOR: '1' }), commandCwd),
shell: false,
windowsHide: true
});
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index 34d04520d8..5cf9f186fc 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -26,6 +26,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '
import { imageGenEvents } from '../imageGenEvents.js';
import { buildNoImageReason } from './noImageReason.js';
import { IMAGE_GEN_MODE } from './modes.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
const AGY_TIMEOUT_MS = (() => {
const n = Number(process.env.AGY_IMAGEGEN_TIMEOUT_MS);
@@ -245,7 +246,10 @@ async function runAgy(job, jobId, bin, args, {
}) {
const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
const { command, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
- const proc = spawn(command, spawnArgs, { cwd: scratchDir, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). agy reads
+ // process.cwd(), so this is defensive rather than a live fix; it keeps every
+ // scratch-dir spawn telling the child one consistent story about where it is.
+ const proc = spawn(command, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
let stdoutTail = '';
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index f29cb69ff7..a7a685363b 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -46,6 +46,7 @@ import sharp from 'sharp';
import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
import { IMAGE_GEN_MODE, describeFidelity } from './modes.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
// 20 minutes — grok's image_gen typically returns in well under a minute, but
// the agent turn wrapping it (skill load, tool call, file write) has no
@@ -283,7 +284,10 @@ async function runGrok(job, jobId, bin, args, {
// shell:false spawn — a no-op on POSIX.
const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
const { command: spawnBin, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
- const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). grok reads
+ // process.cwd(), so this is defensive rather than a live fix; it keeps every
+ // scratch-dir spawn telling the child one consistent story about where it is.
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
diff --git a/server/services/runner.js b/server/services/runner.js
index 1074de0ab2..57f5829fb2 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -266,9 +266,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
// buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared models
// map for OpenCode Ollama providers (empty/no-op otherwise) so the injected
// `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.
- // withSpawnCwdEnv pins PWD to the directory this child actually runs in, so a
- // CLI that reads its project root from PWD (OpenCode does) can't fall back to
- // the PortOS checkout the server itself was started in — see issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
const childEnv = withSpawnCwdEnv(
{ ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(provider, provider.defaultModel) },
effectiveCwd,
diff --git a/server/services/shell.js b/server/services/shell.js
index 9ca3f3cab5..33a76bcb8b 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -149,11 +149,9 @@ export function createShellSession(socket, options = {}) {
cols,
rows,
cwd,
- // withSpawnCwdEnv pins PWD to this session's cwd. An interactive login
- // shell normally rewrites PWD itself at startup, but a non-login shell may
- // not — and an agent-TUI session injects a CLI command into this shell, so
- // an inherited PWD naming the PortOS checkout would send a PWD-reading CLI
- // (OpenCode does) to the wrong repo. See issue #3193.
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). An interactive
+ // login shell rewrites PWD itself at startup, but a non-login shell may
+ // not, and an agent-TUI session injects its CLI command into this shell.
env: withSpawnCwdEnv({
...buildSafeEnv(), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)
// options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index f536ec255c..63f7f48976 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -37,6 +37,7 @@ import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { noImageReason, deriveAspectRatio, GROK_ASPECT_RATIOS } from '../imageGen/grok.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
// 30 minutes — an image-first video turn is two sequential tool calls
// (image_gen then image_to_video render + download), so it runs meaningfully
@@ -196,7 +197,10 @@ async function runGrokVideo(job, jobId, bin, args, {
// cwd moves to the scratch dir; bare names stay bare for PATH lookup.
const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
const { command: spawnBin, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
- const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). grok reads
+ // process.cwd(), so this is defensive rather than a live fix; it keeps every
+ // scratch-dir spawn telling the child one consistent story about where it is.
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
// The route stages a multipart source image into data/uploads and hands us
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index 08a6886a8d..7b1af653be 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -31,6 +31,7 @@ import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { resolveCliModel, isCodexProvider, buildCodexStartupArgs } from '../lib/providerModels.js';
import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
const CLI_VISION_TIMEOUT_MS = 120000;
const IMAGE_BASENAME = 'vision-input.png';
@@ -127,7 +128,12 @@ export async function describeImageViaCli({
const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareCliPrompt(command, args, stdin);
cleanupPromptFile = cleanup;
- const childEnv = { ...process.env, ...provider?.envVars };
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). Load-bearing here:
+ // the non-codex branch above tells the CLI the image is "in the current
+ // directory", and the vision provider is user-configurable — so on OpenCode
+ // (which resolves its project root from PWD) a stale value both hides
+ // vision-input.png and turns the CLI loose in the PortOS checkout.
+ const childEnv = withSpawnCwdEnv({ ...process.env, ...provider?.envVars }, cwd);
delete childEnv.CLAUDECODE;
// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap