From 75e82a4236adb549d989213344469f8b02e5cdca Mon Sep 17 00:00:00 2001 From: Tom Boucher Date: Mon, 16 Mar 2026 11:23:19 -0400 Subject: [PATCH] fix(session): rebuild tools when cwd changes in newSession (#633) (#638) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tools (write, read, edit, bash) capture cwd at creation time via createWriteTool(cwd), createReadTool(cwd), etc. When auto-mode enters a worktree, process.cwd() changes but tools were not recreated — they continued resolving relative paths against the original project root. This caused artifacts to be written to the main project's .gsd/ directory instead of the worktree's .gsd/ directory. The dispatcher then couldn't find the artifact at the expected worktree path and retried the unit indefinitely. Fix: detect cwd change in newSession() and call _buildRuntime() to recreate tools with the updated cwd. This is a targeted rebuild that only fires when cwd actually changed (typically once per auto-mode session when entering/exiting a worktree). Fixes #633 --- packages/pi-coding-agent/src/core/agent-session.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/pi-coding-agent/src/core/agent-session.ts b/packages/pi-coding-agent/src/core/agent-session.ts index 3d1351ddf..c856e9229 100644 --- a/packages/pi-coding-agent/src/core/agent-session.ts +++ b/packages/pi-coding-agent/src/core/agent-session.ts @@ -1356,6 +1356,7 @@ export class AgentSession { this.agent.reset(); // Update cwd to current process directory — auto-mode may have chdir'd // into a worktree since the original session was created. + const previousCwd = this._cwd; this._cwd = process.cwd(); this.sessionManager.newSession({ parentSession: options?.parentSession }); this.agent.sessionId = this.sessionManager.getSessionId(); @@ -1365,6 +1366,17 @@ export class AgentSession { this.sessionManager.appendThinkingLevelChange(this.thinkingLevel); + // Rebuild tools when cwd changed (e.g., auto-mode entered a worktree). + // Tools capture cwd at creation time for path resolution — without + // rebuilding, write/read/edit/bash resolve relative paths against + // the original project root instead of the worktree (#633). + if (this._cwd !== previousCwd) { + this._buildRuntime({ + activeToolNames: this.getActiveToolNames(), + includeAllExtensionTools: true, + }); + } + // Run setup callback if provided (e.g., to append initial messages) if (options?.setup) { await options.setup(this.sessionManager);