/** * 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 完成切换 * * 为什么工具不当场切:它跑在一个正在执行的回合里,那时替换 runtime 会让 pi 判旧 ctx 过期, * 还会把这一轮的结果写丢。 * * 为什么必须 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, validateName, worktreePath } from "./layout.ts"; import { createWorktreeAt, ensureExclude, 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 }, 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(); await ctx.switchSession(file, { cwdOverride: target.path, withSession: async (next) => { if (sendContinuation) { await next.sendUserMessage(continuationText(target.path, target.branch)); } }, }); 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": { const info = repoInfo(commandCtx.cwd); if (!info.ok) return fail(info.reason); // cwd 已消失(worktree 合并后被删、会话 cwd 还钉在原地)同样要放行: // 此时祖先探测报 isLinkedWorktree=false,但用户恰恰最需要 exit 回主仓。 if (!info.info.isLinkedWorktree && !info.info.cwdMissing) { return fail("当前不在 worktree 里,无需 exit"); } // 回主仓根:分支取主仓当前分支(拿不到就留空,续句会换成“回到主仓”的说法) const mainBranch = listWorktrees(info.info.repoRoot).find( (w) => w.path === info.info.repoRoot, )?.branch; const result = await enter( commandCtx, { path: info.info.repoRoot, branch: mainBranch ?? "" }, 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, and end 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.", "The worktree lives at /.worktrees/ on a branch of the same name. The user must approve: this tool asks before creating anything.", "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 are inside the worktree before that message arrives.", ].join("\n"), promptSnippet: "Enter an isolated git worktree as the first action of the task; it ends this turn so the switch takes effect immediately. Never fake isolation 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.", "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.", "Pass a short branch-style name (letters, digits, `.`, `_`, `-`, optional `/`); it becomes both the directory name and the branch.", "The turn ends with this result and the session switches; when the new cwd is announced, continue the task there.", ], parameters: Type.Object({ name: Type.String({ description: "Worktree name; becomes /.worktrees/ and the branch name (e.g. feat/login).", }), create: Type.Optional( Type.Boolean({ description: "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 { name?: unknown; create?: unknown }; const name = String(raw?.name ?? "").trim(); if (!name) return textResult("name must not be empty.", { ok: false }); const commandCtx = ctx as unknown as CmdCtx; 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({ 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 每次运行结束都会触发。 pi.on("agent_settled", () => { const pending = getPending(); if (!pending || pending.dispatchedAt !== undefined) return; markDispatched(); pi.sendUserMessage("/worktree __enter", { 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 } : {}) }; }