/** * worktree — 把**当前会话**真正切进一个隔离的 git worktree。 * * ## 为什么需要这个扩展 * * pi 没有 `cd`:`ctx.cwd` 来自 `SessionManager.getCwd()`,会话创建时固化。bash 里的 * `cd && …` 只影响那条子进程 —— 会话 cwd、原生工具基准、`@` 补全、系统提示里的 * 项目上下文、**以及 statusline 读 git 的目录**全都还钉在主仓。这正是 2026-10-30 那次 * mc-heavy 会话的形态:模型自以为在隔离目录里干活,statusline 显示的还是 main 的 diff。 * * pi 的公开 API 里没有 `switchCwd`(上游 issue #4423 提过、被 auto-close)。唯一可行的 * 公开路径是「造一个 cwd 不同的会话文件,然后切过去」: * * SessionManager.forkFrom(当前会话, 目标目录) // 历史照抄,header cwd = 目标目录 * → ctx.switchSession(那个文件, { withSession }) * * 切换后 runtime 整体重建:`ctx.cwd`、cwd-bound 的服务、资源发现、statusline 全部跟上。 * 完整设计与实测见 docs/superpowers/specs/2026-10-30-pi-worktree-design.md。 * * ## 三条入口 * * /worktree new <名> 用户自己敲 → 不问,直接建 + 切 * worktree 工具 {name} 模型决定 → 先 ctx.ui.confirm 得到同意,建树 + 登记,并返回 * `terminate: true` —— 这一轮**立刻结束**,agent_settled 随即派发 * 内部命令 /worktree __enter 完成切换 * worktree 工具 {action:"exit"} 模型收尾 → 不问(不删任何东西,只是回主检出),登记 + terminate, * agent_settled 派发 /worktree __exit 切回主仓根 * * 为什么 exit 必须也是**工具**:pi 不把已注册命令暴露成工具,`switchSession` 只在 * `ExtensionCommandContext` 上(模型工具拿到的 `ExtensionToolContext` 没有它)。只有 `/worktree exit` * 时模型根本调不到退出 —— 2026-11-15 mc-heavy 实测:模型 `tool_search("… exit worktree")` 一无所获, * 于是按技能「platform 没提供 exit 工具就留在原地」放弃清理,下一轮又把 bash 里的 `cd <主仓>` * 误当成会话 cwd 已切走,删树之后 bash 在 spawn 阶段就彻底不可用,整场会话只剩原生工具。 * * 为什么工具不当场切:它跑在一个正在执行的回合里,那时替换 runtime 会让 pi 判旧 ctx 过期, * 还会把这一轮的结果写丢。两个方向共用同一条 pending → agent_settled → 内部命令通道。 * * 为什么必须 terminate:不 terminate 时本轮会继续跑(pi 的 agent loop 只在**整批**工具结果 * 都终止时才早退),模型于是把整段活干完才结束轮次 —— 那段时间会话 cwd 仍在主仓, * statusline / @ 补全 / 沙箱删除边界全指向主检出,隔离名存实亡。2026-10-30 实测:一次 * 「用 gitworktree 改 AGENTS.md」的任务里树在 15 分钟后才建,之后又跑了 38 次工具调用、 * 5 次写盘才切换。代价:早退要求整批结果都为真,所以这个工具必须单独调用。 * * ## 开关 * * PI_WORKTREE=off 关整层(加载期读) * PI_WORKTREE_CONTINUE=off 只关切换后的自动续句(执行期读) */ import fs from "node:fs"; import path from "node:path"; import { Type } from "typebox"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; import { linkIgnoredDirs } from "../background-tasks/worktree.ts"; import { branchFor, continuationText, exitContinuationText, validateName, worktreePath } from "./layout.ts"; import { createWorktreeAt, ensureExclude, exitTarget, listWorktrees, removeWorktree, repoInfo } from "./git.ts"; import { clearPending, getPending, markDispatched, setPending } from "./state.ts"; /** 关闭续句时读这个环境变量(执行期读,便于一次会话内切换)。 */ const CONTINUE_DISABLED = () => (process.env.PI_WORKTREE_CONTINUE ?? "").trim().toLowerCase() === "off"; /** 切进 worktree 之后要 symlink 进来的被 gitignore 依赖目录(与 background-tasks 同口径)。 */ const LINK_DIRS = ["node_modules"] as const; /** 命令 / 工具共用的结果形状。 */ type EnterResult = { ok: true } | { ok: false; reason: string }; /** pi 包里的 SessionManager 子集 —— 只用这两个静态方法,便于测试注入替身。 */ interface SessionModule { SessionManager: { forkFrom(sourcePath: string, targetCwd: string): { getSessionFile(): string | undefined }; create(cwd: string): { getSessionFile(): string | undefined }; }; } /** 命令上下文里我们用到的那几个成员(pi 的真实类型是超集)。 */ type CmdCtx = ExtensionContext & { readonly sessionManager: { getSessionFile(): string | undefined; getCwd(): string }; switchSession( sessionPath: string, options?: { cwdOverride?: string; withSession?: (ctx: CmdCtx) => Promise }, ): Promise<{ cancelled: boolean }>; }; /** * 把会话切到 `targetPath`。 * * 三段:拿会话文件 → fork 或新建 → switchSession(续句在 withSession 里发)。 * 源会话文件为空/不存在时不能 `forkFrom`(它会抛 "source session file is empty or invalid", * 实测:会话还没写过任何消息时就是这种状态),退回 `SessionManager.create` + `cwdOverride`。 */ async function enter( ctx: CmdCtx, target: { path: string; branch: string; kind?: "enter" | "exit" }, piModule: SessionModule, ): Promise { const source = ctx.sessionManager.getSessionFile(); const usable = typeof source === "string" && fs.existsSync(source) && fs.statSync(source).size > 0; const manager = usable ? piModule.SessionManager.forkFrom(source as string, target.path) : piModule.SessionManager.create(target.path); const file = manager.getSessionFile(); if (!file) return { ok: false, reason: `无法为目标目录创建会话文件:${target.path}` }; const sendContinuation = !CONTINUE_DISABLED(); const exiting = target.kind === "exit"; await ctx.switchSession(file, { cwdOverride: target.path, withSession: async (next) => { if (sendContinuation) { const text = exiting ? exitContinuationText(target.path, target.branch) : continuationText(target.path, target.branch); await next.sendUserMessage(text); } }, }); return { ok: true }; } export default function worktreeExtension(pi: ExtensionAPI, piModule?: SessionModule): void { if ((process.env.PI_WORKTREE ?? "").trim().toLowerCase() === "off") return; /** 惰性取真包:模块求值期不碰 pi,单测注入替身即可。 */ const moduleOf = async (): Promise => piModule ?? ((await import("@earendil-works/pi-coding-agent")) as unknown as SessionModule); /** 建 worktree(含 exclude 与依赖 symlink)。返回目标路径与分支。 */ const prepare = (repoRoot: string, name: string) => { ensureExclude(repoRoot); const created = createWorktreeAt({ repoRoot, name }); if (!created.ok) return created; // node_modules 被 gitignore 才链;链不上不致命(任务可能跑不起来,但目录与分支是对的) linkIgnoredDirs(repoRoot, created.path, [...LINK_DIRS]); return created; }; /** * 解析出要进的 worktree:已存在(列在 worktree list 里)就复用,否则按 `create` 决定新建还是报错。 * * 这里刻意**不建目录**:调用方要先拿 path/branch 去问用户,同意了再 `prepare`。 */ const resolveTarget = ( repoRoot: string, name: string, opts: { create: boolean }, ): { ok: true; path: string; branch: string; existing: boolean } | { ok: false; reason: string } => { const wanted = validateName(name); if (!wanted.ok) return wanted; const existing = listWorktrees(repoRoot).find( (w) => w.path === worktreePath(repoRoot, wanted.name) || w.branch === branchFor(wanted.name), ); if (existing) { return { ok: true, path: existing.path, branch: existing.branch ?? branchFor(wanted.name), existing: true }; } if (!opts.create) { return { ok: false, reason: `没有名为 "${wanted.name}" 的 worktree(用 /worktree new ${wanted.name} 建一个,或让 worktree 工具的 create 保持默认值 true)`, }; } return { ok: true, path: worktreePath(repoRoot, wanted.name), branch: branchFor(wanted.name), existing: false }; }; /** `new` / `enter` 的共用实现:解析目标 → 需要就建 → 切过去。 */ const enterByName = async (ctx: CmdCtx, name: string, opts: { create: boolean }): Promise => { const info = repoInfo(ctx.cwd); if (!info.ok) return info; const resolved = resolveTarget(info.info.repoRoot, name, opts); if (!resolved.ok) return resolved; let target: { path: string; branch: string } = { path: resolved.path, branch: resolved.branch }; if (!resolved.existing) { const created = prepare(info.info.repoRoot, name); if (!created.ok) return created; target = { path: created.path, branch: created.branch }; } const module = await moduleOf(); return enter(ctx, target, module); }; // ── /worktree 命令 ────────────────────────────────────────────────── pi.registerCommand("worktree", { description: "Work in an isolated git worktree — /worktree [new | enter | exit | rm | list]", handler: async (args, ctx) => { const commandCtx = ctx as unknown as CmdCtx; const argv = args.trim().split(/\s+/).filter(Boolean); const sub = argv[0] ?? "status"; const rest = argv.slice(1).join(" "); const fail = (reason: string) => ctx.ui.notify(reason, "error"); switch (sub) { case "new": case "enter": { if (!rest) return fail(`用法:/worktree ${sub} `); const result = await enterByName(commandCtx, rest, { create: sub === "new" }); if (!result.ok) fail(result.reason); return; } case "__enter": { // 内部命令:模型工具登记待办后,由 agent_settled 派发到这里 const pending = getPending(); if (!pending) return fail("没有待进入的 worktree(这个命令只由工具触发)"); clearPending(); const result = await enter(commandCtx, { path: pending.path, branch: pending.branch }, await moduleOf()); if (!result.ok) fail(result.reason); return; } case "__exit": { // 内部命令:与 __enter 同形,只是方向相反(工具 action:"exit" → agent_settled) const pending = getPending(); if (!pending) return fail("没有待退出的 worktree(这个命令只由工具触发)"); clearPending(); const result = await enter( commandCtx, { path: pending.repoRoot, branch: pending.branch, kind: "exit" }, await moduleOf(), ); if (!result.ok) fail(result.reason); return; } case "exit": { const target = exitTarget(commandCtx.cwd); if (!target.ok) return fail(target.reason); // needed 把「linked worktree 或 cwd 已消失」两种形态合在一处: // 树合并后被删、会话 cwd 还钉在原地时祖先探测报 isLinkedWorktree=false, // 但用户恰恰最需要 exit 回主仓。 if (!target.needed) return fail("当前不在 worktree 里,无需 exit"); const result = await enter( commandCtx, { path: target.path, branch: target.branch, kind: "exit" }, await moduleOf(), ); if (!result.ok) fail(result.reason); return; } case "rm": { if (!rest) return fail("用法:/worktree rm "); const info = repoInfo(commandCtx.cwd); if (!info.ok) return fail(info.reason); const target = worktreePath(info.info.repoRoot, rest); const removed = removeWorktree(info.info.repoRoot, target); if (!removed.ok) { return fail(`${removed.reason}\n(该 worktree 里可能有未提交改动;先提交或用 git worktree remove --force ${target})`); } ctx.ui.notify(`已删除 worktree ${target}`, "info"); return; } case "list": { const info = repoInfo(commandCtx.cwd); if (!info.ok) return fail(info.reason); const lines = listWorktrees(info.info.repoRoot).map( (w) => `${w.path}${w.branch ? ` [${w.branch}]` : " [detached]"}`, ); ctx.ui.notify(lines.join("\n"), "info"); return; } default: { const info = repoInfo(commandCtx.cwd); if (!info.ok) return fail(info.reason); const lines = [`cwd: ${commandCtx.cwd}`, `repo: ${info.info.repoRoot}`]; if (info.info.cwdMissing) { lines.push("(cwd 已不存在 —— 该 worktree 大概已被删除;用 /worktree exit 回主仓)"); } else if (info.info.isLinkedWorktree) { lines.push("(当前就在 linked worktree 里)"); } lines.push("", "用法:/worktree new | enter | exit | rm | list"); ctx.ui.notify(lines.join("\n"), "info"); return; } } }, }); // ── worktree 工具(模型入口:进入必须先 ask,退出不问) ────────────── pi.registerTool({ name: "worktree", label: "Worktree", description: [ "Enter an isolated git worktree for the current session, or leave it back to the main checkout. Either way it ends this turn so the switch happens immediately.", "A `cd` inside a shell command does NOT change the session: the session cwd, native tools, @ completion and the statusline's git read all stay where they were. Use this tool to really move the session.", "action \"enter\" (default): the worktree lives at /.worktrees/ on a branch of the same name. The user must approve — this asks before creating anything.", "action \"exit\": switches the session back to the main repo root. No approval needed, it deletes nothing. Call it before removing a worktree: while the session cwd still points into that tree, `git worktree remove` leaves the session pinned to a deleted directory and bash stops working entirely for the rest of the session.", "When the task needs isolation, call it before any read, edit or bash call: everything you touch before the switch lands in the main checkout, not in the worktree.", "Its result ends the turn, which is what lets the session switch. Early termination needs every tool result in the batch to agree, so call it alone — not batched with other tools.", "The switch is announced by the user's own session — do not claim you have moved before that message arrives.", ].join("\n"), promptSnippet: "Enter an isolated git worktree as the first action of the task, and leave it with action \"exit\" before removing that tree; either call ends this turn so the switch takes effect immediately. Never fake the move with `cd`.", promptGuidelines: [ "When the task needs an isolated checkout, call this tool first and alone — before any read, edit or bash call. Work done before the switch happens in the main checkout.", "When the work is integrated and the tree is about to go, call it with action \"exit\" first and alone. Removing the tree while the session cwd still points into it breaks bash for the rest of the session — `cd` in a shell command is not a way out.", "Never batch it with other tool calls: pi only ends the turn when every result in the batch terminates.", "Never prefix shell commands with `cd &&` and call that isolation.", "For action \"enter\" pass a short branch-style name (letters, digits, `.`, `_`, `-`, optional `/`); it becomes both the directory name and the branch. Action \"exit\" takes no name.", "The turn ends with this result and the session switches; when the new cwd is announced, continue from there.", ], parameters: Type.Object({ action: Type.Optional( Type.Union([Type.Literal("enter"), Type.Literal("exit")], { description: "\"enter\" (default) moves the session into a worktree; \"exit\" moves it back to the main repo root.", }), ), name: Type.Optional( Type.String({ description: "Worktree name for action \"enter\"; becomes /.worktrees/ and the branch name (e.g. feat/login).", }), ), create: Type.Optional( Type.Boolean({ description: "action \"enter\" only: create the worktree if it does not exist. Default true; false requires an existing one.", }), ), }), async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const raw = params as { action?: unknown; name?: unknown; create?: unknown }; const action = String(raw?.action ?? "enter").trim().toLowerCase() === "exit" ? "exit" : "enter"; const commandCtx = ctx as unknown as CmdCtx; // ── 退出:不问(不删任何东西,只是回主检出),但同样只能走轮次边界 ── if (action === "exit") { const target = exitTarget(commandCtx.cwd); if (!target.ok) return textResult(target.reason, { ok: false }); if (!target.needed) { // 已在主仓根:不 terminate、不落 pending,让本轮照常继续(重建 runtime 是白代价) return textResult( `The session is already at the main checkout ${target.path}; there is nothing to exit. It is safe to remove worktrees from here.`, { ok: true, path: target.path, branch: target.branch, needed: false }, ); } // pending 的 path/repoRoot 都是主仓根:__exit 读 repoRoot 作目的地,path 留给取证 setPending({ kind: "exit", path: target.path, branch: target.branch, repoRoot: target.path, requestedAt: Date.now(), }); return textResult( `Leaving the worktree: the session will switch to ${target.path}${target.branch ? ` on branch ${target.branch}` : ""}. This turn ends here — wait for the new-cwd announcement, then remove the worktree from there. Do not run \`git worktree remove\` in this turn: the session cwd still points into that tree until the switch lands.`, { ok: true, path: target.path, branch: target.branch, needed: true }, true, ); } // ── 进入 ── const name = String(raw?.name ?? "").trim(); if (!name) return textResult('name must not be empty (required for action "enter").', { ok: false }); const info = repoInfo(commandCtx.cwd); if (!info.ok) return textResult(info.reason, { ok: false }); const resolved = resolveTarget(info.info.repoRoot, name, { create: raw?.create !== false }); if (!resolved.ok) return textResult(resolved.reason, { ok: false }); const approved = await ctx.ui.confirm( "进入 git worktree", `${resolved.existing ? "进入" : "创建并进入"} ${resolved.path}(分支 ${resolved.branch})?\n同意后本轮立刻结束、会话马上切过去,statusline 的目录与 diff 也会跟着变。`, ); if (!approved) return textResult(`User declined to enter worktree "${name}". Staying in ${commandCtx.cwd}.`, { ok: false }); let target: { path: string; branch: string } = { path: resolved.path, branch: resolved.branch }; if (!resolved.existing) { const created = prepare(info.info.repoRoot, name); if (!created.ok) return textResult(created.reason, { ok: false }); target = { path: created.path, branch: created.branch }; } setPending({ kind: "enter", path: target.path, branch: target.branch, repoRoot: info.info.repoRoot, requestedAt: Date.now(), }); return textResult( `Worktree ${target.path} on branch ${target.branch} is ready. This turn ends here and the session switches immediately — do not claim you are already there; wait for the new-cwd announcement, then continue the task there.`, { ok: true, path: target.path, branch: target.branch }, true, ); }, }); // ── 事件接线 ──────────────────────────────────────────────────────── // 模型工具的待办在这里落地:这一轮真的结束了,替换 runtime 才安全。 // 只负责「派发」,待办由命令消费后清空(清早了命令就不知道要切哪里); // 已有 dispatchedAt 就不再派发 —— settled 每次运行结束都会触发。 // kind 决定方向:两个内部命令共用同一条通道,区别只在切回哪里。 pi.on("agent_settled", () => { const pending = getPending(); if (!pending || pending.dispatchedAt !== undefined) return; markDispatched(); const command = pending.kind === "exit" ? "/worktree __exit" : "/worktree __enter"; pi.sendUserMessage(command, { expandPromptTemplates: true }); }); // linked worktree 里在主行之外再挂一个 🌳 名,让"我在哪"一眼可见 pi.on("session_start", (_event, ctx) => { const info = repoInfo(ctx.cwd); if (info.ok && info.info.isLinkedWorktree) { ctx.ui.setStatus("worktree", `🌳 ${path.basename(ctx.cwd)}`); } else { ctx.ui.setStatus("worktree", undefined); } }); } /** * 工具结果的最小形状(与 background-tasks 的 textResult 同形)。 * * `terminate` 会写进 `AgentToolResult.terminate`:pi 的 agent loop 在整批工具结果都带它时 * 跳过后续模型请求、直接结束本轮(`shouldTerminateToolBatch`)—— worktree 工具靠这一条 * 让切换在调用后立刻发生,而不是等模型把整段活干完。 */ function textResult(text: string, details: Record, terminate?: boolean) { return { content: [{ type: "text" as const, text }], details, ...(terminate ? { terminate: true } : {}) }; }