GeezerVison is showing github.com — cli: run resolves the workspace from $PWD instead of the process cwd (still on 2.0.32) · Issue #56386 · anomalyco/opencode
cli: run resolves the workspace from $PWD instead of the process cwd (still on 2.0.32) #56386DescriptionDescription
opencode run resolves its workspace from the inherited PWD environment variable instead of the process's actual working directory, and chdirs to $PWD. A caller that sets a child's cwd without updating PWD (systemd WorkingDirectory, subprocess(cwd=...), any non-shell spawn) therefore attaches the wrong directory to the session.
I hit this from a headless orchestrator that launches opencode run per task with an explicit cwd. The agent's relative file writes landed in the daemon's home directory instead of the target checkout, and absolute paths into the real cwd were rejected as Permission denied: edit, because the permission root was $PWD rather than the real cwd.
The non-interactive path computes the directory as:
let d = n.root ?? process.env.PWD ?? process.cwd(), w = Re(d)
function Re(e) { process.chdir(e); return process.cwd() }
Re() chdirs to $PWD before the standalone server is spawned (cwd: process.cwd()), so --standalone does not help, and v2 removed --dir from opencode run, so there is no supported flag to override the directory.
This was reported against v1 and closed without a fix: #27392 (auto-closed for inactivity), #27583 (fix PR closed unmerged), #47080 (closed with the v1 to v2 triage note). This is the requested 2.0 report; it still reproduces on 2.0.32.
Plugins
None configured.
OpenCode version
2.0.32 (npm @opencode/cli, latest)
Steps to reproduce
mkdir -p /tmp/rt/actual /tmp/rt/elsewhere
- From
/tmp/rt/actual, run: PWD=/tmp/rt/elsewhere opencode run --standalone --format json -m <provider>/<model> 'Use the write tool to create marker.txt containing exactly: hi. Do not use bash.'
- Check where
marker.txt was written.
Expected: /tmp/rt/actual/marker.txt. Actual: /tmp/rt/elsewhere/marker.txt. Same result without --standalone.
Screenshot and/or share link
N/A (headless CLI repro; the written path is the evidence)
Operating System
Linux 7.0.0-38-generic (Linux Mint 22.3, Ubuntu 24.04 base), x86_64
Terminal
Headless subprocess, no TTY (TERM=xterm-256color, TERM_PROGRAM unset) Activityopencode-agent commented on Oct 17, 2026 Thanks for the detailed report. I reproduced this on 2.0.32, and it still happens on the latest dev (a49f179).
What I did: started from actual/ with PWD set to elsewhere/, then ran opencode run with a mocked model that calls write with the relative path marker.txt. The file was created in elsewhere/ instead of the process's real cwd. The result is the same with and without --standalone. The script below reproduces it end to end with a local mock provider, so no credentials are needed.
The cause matches what you found. The run command takes its root as process.env.PWD ?? process.cwd() and then chdirs there (packages/cli/src/run/run.ts; mini.ts and run/v1.ts do the same). Until this is fixed, setting PWD to the child's real cwd before spawning opencode is the workaround.
Related earlier reports, all closed without a fix: #27392, #27583 (unmerged PR) and #47080 (v1).
Reproduction script (repro.sh)
#!/usr/bin/env bash
# Repro for #56386: `opencode run` uses $PWD instead of the real cwd.
# Uses a tiny mock OpenAI-compatible server that always asks for one `write` of marker.txt.
# Usage: ./repro.sh (uses `opencode` from PATH)
# OC_DEV=/path/to/opencode ./repro.sh (runs from source checkout)
set -u
BASE=$(mktemp -d /tmp/opencode/rt.XXXX)
mkdir -p "$BASE/actual" "$BASE/elsewhere" "$BASE/home"
PORT=${PORT:-18765}
cat > "$BASE/mock.ts" <<'TS'
let n = 0
Bun.serve({ port: Number(process.env.PORT), async fetch(req) {
const url = new URL(req.url)
if (!url.pathname.endsWith("/chat/completions")) return new Response("{}", { headers: { "content-type": "application/json" } })
const body = await req.json()
const hasTool = body.messages.some((m: any) => m.role === "tool")
const id = "c" + n++
const chunks = hasTool
? [{ choices: [{ index: 0, delta: { role: "assistant", content: "done" } }] },
{ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }]
: [{ choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_1", type: "function",
function: { name: "write", arguments: JSON.stringify({ path: "marker.txt", content: "hi" }) } }] } }] },
{ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }]
const s = chunks.map(c => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: 0, model: "m", ...c })}\n\n`).join("") + "data: [DONE]\n\n"
return new Response(s, { headers: { "content-type": "text/event-stream" } })
}})
TS
PORT=$PORT bun "$BASE/mock.ts" & MOCK=$!
sleep 1
export HOME="$BASE/home" XDG_CONFIG_HOME="$BASE/home/.config" XDG_DATA_HOME="$BASE/home/.local/share" XDG_STATE_HOME="$BASE/home/.local/state" XDG_CACHE_HOME="$BASE/home/.cache"
export OPENCODE_CONFIG_CONTENT='{"autoupdate":false,"permission":{"edit":"allow","bash":"deny"},"provider":{"mock":{"npm":"@ai-sdk/openai-compatible","name":"Mock","options":{"baseURL":"http://127.0.0.1:'$PORT'/v1","apiKey":"x"},"models":{"m":{"name":"m","tool_call":true}}}}}'
if [ -n "${OC_DEV:-}" ]; then
export BUN_OPTIONS="--conditions=browser --preload=$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js" # so spawned server subprocesses also load from source
OC=(bun --conditions=browser --preload="$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js" "$OC_DEV/packages/cli/src/index.ts")
else
OC=(opencode)
fi
"${OC[@]}" --version
cd "$BASE/actual"
echo "real cwd: $(pwd -P) PWD passed: $BASE/elsewhere"
PWD="$BASE/elsewhere" timeout 120 "${OC[@]}" run ${STANDALONE---standalone} --format json -m mock/m 'Create marker.txt containing hi' > "$BASE/out.json" 2>&1
echo "exit: $?"
echo "--- marker.txt locations:"
ls -la "$BASE/actual/marker.txt" "$BASE/elsewhere/marker.txt" 2>&1
kill $MOCK
echo "output tail:"; tail -c 1500 "$BASE/out.json"
Run it: bash repro.sh
bettercallcaleb commented on Nov 5, 2026 Additional independent reproduction on Linux with OpenCode 1.19.5 (v1) using a headless Python runner. This is historical v1 evidence, not a claim that I retested v2; the current issue already has a v2 reproduction.
The runner launched opencode run --pure --format json ... using subprocess.Popen(cwd=target_repo, env=os.environ.copy(), stdin=DEVNULL). The child process received the real repository as its OS working directory but inherited a stale PWD from the launcher.
In a minimal, isolated two-file JavaScript repository (a one-line arithmetic fix plus a Node test), the uncorrected run executed shell commands in the launcher's directory instead of the target repository, failed to find the expected files, and received a read-tool permission rejection for an absolute path into the actual checkout. The process exited with status 0, without editing code; the test remained failing.
Keeping the task, model endpoint, and files unchanged, these launcher variants produced:
| Launch configuration |
Observed outcome |
cwd=target_repo, inherited stale PWD, no --dir |
No edit; test failed |
cwd=target_repo, corrected PWD=target_repo |
Code fixed; test passed in 12.9 s |
cwd=target_repo, stale PWD, explicit --dir target_repo |
Code fixed; test passed in 12.8 s |
cwd=target_repo, corrected PWD, explicit --dir target_repo |
Code fixed; test passed in 16.4 s |
In a separate, longer multi-file task using the same local inference interface, correcting the launcher also changed an unsuccessful no-edit timeout (1,500 s) into a completed patch (877.3 s; all 56 tests and a separate persistence holdout passed). The larger-task comparison is not a controlled one-variable causal experiment; the small repo comparison above is the clearest reproduction.
User impact: for headless orchestrators, the mismatch can silently change the agent's workspace and permission boundary while still returning process exit status 0. A robust fix would derive the workspace from the process cwd (or detect and report disagreement with PWD). The existing workaround is to set PWD explicitly before spawn; v1 also accepts --dir.
No private repository URLs, hostnames, local account names, or environment-specific paths are included. Jonakss commented on Nov 5, 2026 Still reproduces on 2.2.5, and the root cause is unchanged — packages/cli/src/run/run.ts still does const root = options.root ?? process.env.PWD ?? process.cwd() and then process.chdir(root).
Repro, headless, no shell involved:
cwd=/tmp/pwdtest PWD=/tmp/pwdtest → pwd prints /tmp/pwdtest
cwd=/tmp/pwdtest PWD=/tmp → pwd prints /tmp
Only the environment variable changes; the process cwd is identical in both runs.
Two things that may matter for whoever picks this up:
-
The shell tool is not the culprit. It spawns with location.directory, which comes from the root resolved above. The CLI chdirs to $PWD at startup, so by the time anything else looks at "the current working directory" it is already $PWD. A report titled "the shell runs in $PWD" is easy to dismiss; the actual claim is that a parent process spawning the CLI with cwd=X silently gets a session rooted somewhere else — CI, editors, sandboxes and agent orchestrators all hit it.
-
Bash does not behave this way. env PWD=/somewhere/else bash -c 'echo $PWD' prints the real cwd: bash compares st_dev/st_ino before trusting PWD, and rewrites PWD for its children. Comparing with realpathSync (as in fix(cli): trust $PWD only when it matches the process cwd #59368) covers symlinks but misses bind-mounts, and it leaves the stale PWD in the environment, so child processes inherit it again.
One correction to the issue body: on 2.2.5 the positional <directory> argument does win over $PWD (verified with --standalone), so there is a workaround today — it may have been added after 2.0.32.
#59368 had essentially this fix; it was closed as a duplicate of #56389, which takes the simpler route (drop $PWD entirely). The part of #59368 that keeps the symlinked path is worth keeping, so I raised it there. dalisoft commented on Nov 15, 2026 Independent reproduction on official OpenCode 2.3.0 / macOS arm64: opencode run --server ... and opencode mini create the session in the stale $PWD directory, while the full TUI uses the actual cwd. Regression test: #64126. The earlier fix PR #56389 covers the same source change. dalisoft commented on Nov 15, 2026 Related TUI path: packages/tui/src/app.tsx fell back to api.location.get() (the server active location) if the initial file.list failed, which can also put the full TUI in the wrong directory with a stale shared service. PR #64126 now fixes that fallback and adds a unit test for both paths. dalisoft commented on Nov 15, 2026 Split out the full-TUI part that #56389 does not cover: #64128 fixes the TUI file.list fallback so it resolves the client cwd instead of the server active location. The run/mini fix remains #56389.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|