/** * ============================================================ * src/tools/agent/worktree.ts —— 子 agent 的 git worktree 隔离助手 * ------------------------------------------------------------ * 搬自 Claude Code 官方 utils/worktree.ts 的核心路径(createAgentWorktree * 那条**无全局状态**的路径——并行子 agent 不能共享单例 session 状态), * 砍掉 settings/hooks/tmux/sparse-checkout/symlink 等锦上添花件。 * * 保留的官方实战经验(每条都对应真实事故教训): * - slug 白名单校验:slug 会被拼进目录路径与分支名,防路径穿越。 * - `git worktree add -b`:同名分支已存在时拒绝重建,不重置保留成果。 * - fail-closed 改动判定:任何 git 命令失败一律视为「有改动」,宁可多留 * 一个 worktree,绝不误删并行子 agent 的工作成果。 * - 普通清理核对忽略项且不强制删除;仅显式 discard 使用 --force,再等待释放分支锁; * 清理失败返回明确结果,不将已应用补丁误报为需要重做。 * - GIT_TERMINAL_PROMPT=0 + stdin ignore:防 git/ssh 弹交互式凭证输入挂死。 * * 目录选址 `/.agent-worktrees/`:刻意避开 `.minimal-agent*` 保留前缀 * (/new 会按前缀整目录 rm -rf,直接删 worktree 目录会留下悬空的 git 注册项); * 首次创建时追加进 `/info/exclude`(仓库本地 ignore,不污染共享 .gitignore)。 * ============================================================ */ import { runBoundedProcess } from '../../runtime/boundedProcess.js'; import { AsyncLocalStorage } from 'node:async_hooks'; const gitSignal = new AsyncLocalStorage(); export function withAgentGitSignal(signal: AbortSignal | undefined, run: () => Promise): Promise { return gitSignal.run(signal, run); } import { appendFile, readFile, writeFile, unlink, realpath, stat } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; import { join, resolve, relative, isAbsolute, sep } from 'node:path'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { dlog } from '../../utils/debugLog.js'; const WORKTREES_DIR = '.agent-worktrees'; interface GitResult { ok: boolean; stdout: string; stderr: string; } /** 跑一条 git 命令(防挂死 env + stdin ignore),spawn 失败也归一成 ok:false。 */ async function runGit(args: string[], cwd: string): Promise { try { const result = await runBoundedProcess('git', args, { cwd, timeoutMs: 60_000, signal: gitSignal.getStore(), env: { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '' }, }); return { ok: result.exitCode === 0, stdout: result.stdout.replace(/\r?\n$/, ''), stderr: result.stderr.trim() }; } catch (error) { return { ok: false, stdout: '', stderr: String(error) }; } } // Machine-readable XY status, including individual untracked files even if the user's // display configuration hides them. No quoting or rename tuples to misparse. const worktreeStatus = (cwd: string) => runGit(['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all'], cwd); /** slug 白名单(官方同款语义):会拼进路径和分支名,只放行安全字符。 */ export function validateSlug(slug: string): boolean { return /^[a-zA-Z0-9._-]{1,64}$/.test(slug) && slug !== '.' && slug !== '..'; } export interface AgentWorktree { /** Preserve a monorepo project's boundary, distinct from the Git root. */ executionPath?: string; ok: true; /** worktree 目录绝对路径 */ path: string; /** 临时分支名(agent/) */ branch: string; /** 创建时刻的基线提交(改动判定 / diff 摘要的锚点) */ baseSha: string; /** 主仓库根 */ gitRoot: string; } export type CreateWorktreeResult = AgentWorktree | { ok: false; error: string }; /** 把 worktree 目录加进仓库本地 ignore(best-effort,失败静默——只是降噪)。 */ async function ensureLocalExclude(cwd: string): Promise { try { const r = await runGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd); if (!r.ok || !r.stdout) return; const excludePath = join(r.stdout, 'info', 'exclude'); const line = `${WORKTREES_DIR}/`; const existing = await readFile(excludePath, 'utf8').catch(() => ''); if (existing.split(/\r?\n/).includes(line)) return; await appendFile(excludePath, `${existing.endsWith('\n') || existing === '' ? '' : '\n'}${line}\n`); } catch { /* ignore 失败只影响 git status 观感,不影响功能 */ } } /** * 在当前仓库创建一个子 agent 专用 worktree(基于 HEAD 的独立分支)。 * 非 git 仓库 / 无提交仓库返回 ok:false——把决策权交回主 agent(降级无隔离或串行)。 */ export async function createAgentWorktree( slug: string, fromCwd: string = getWorkingDir(), ): Promise { if (!validateSlug(slug)) { return { ok: false, error: `非法的 worktree 名称「${slug}」(只允许字母数字._-,≤64 字符)` }; } const root = await runGit(['rev-parse', '--show-toplevel'], fromCwd); if (!root.ok || !root.stdout) { return { ok: false, error: '当前目录不是 git 仓库,无法创建 worktree 隔离' }; } const gitRoot = root.stdout; // git rev-parse --show-toplevel 返回物理路径;macOS 上 /tmp、/var 等是符号链接, // 直接 relative 会把「同一目录」误判为"在仓库外"。两边都归一成真实路径再比较。 const [realRoot, realCwd] = await Promise.all([ realpath(gitRoot).catch(() => gitRoot), realpath(fromCwd).catch(() => resolve(fromCwd)), ]); const subdir = relative(realRoot, realCwd); if (isAbsolute(subdir) || subdir === '..' || subdir.startsWith(`..${sep}`)) return { ok: false, error: '执行目录不在 Git 仓库内' }; const head = await runGit(['rev-parse', 'HEAD'], gitRoot); if (!head.ok || !head.stdout) { return { ok: false, error: '仓库还没有任何提交(HEAD 不存在),无法创建 worktree——先 git commit 一次' }; } const baseSha = head.stdout; const path = join(gitRoot, WORKTREES_DIR, slug); const branch = `agent/${slug}`; await ensureLocalExclude(gitRoot); const add = await runGit(['worktree', 'add', '-b', branch, path, baseSha], gitRoot); if (!add.ok) { return { ok: false, error: `git worktree add 失败:${add.stderr || add.stdout}` }; } const executionPath = resolve(path, subdir); if (subdir && !(await stat(executionPath).catch(() => undefined))?.isDirectory()) { const cleanup = await removeAgentWorktree(path, branch, gitRoot); return { ok: false, error: `项目子目录在已提交的 HEAD 中不存在,未进入隔离工作区:${subdir}${cleanup.ok ? '' : `;清理未完成:${path},${cleanup.error}`}` }; } return { ok: true, path, executionPath, branch, baseSha, gitRoot }; } /** Resolve the managed Git root from the repository and id; never remove a saved cwd. */ export function managedWorktreeRoot(gitRoot: string, id: string): string | undefined { return validateSlug(id) ? join(gitRoot, WORKTREES_DIR, id) : undefined; } /** * worktree 相对基线是否有改动(未提交文件 或 新增提交)。 * fail-closed:任何 git 命令失败一律返回 true(有改动)——宁多留不误删。 */ export async function hasWorktreeChanges(path: string, baseSha: string): Promise { const status = await worktreeStatus(path); if (!status.ok) return true; if (status.stdout.length > 0) return true; const revList = await runGit(['rev-list', '--count', `${baseSha}..HEAD`], path); if (!revList.ok) return true; return Number.parseInt(revList.stdout, 10) > 0; } /** 相对基线的 diff 摘要(best-effort,失败返回空串)——给主 agent 收口审阅用。 */ export async function worktreeDiffStat(path: string, baseSha: string): Promise { const diff = await runGit(['diff', '--stat', baseSha], path); const parts: string[] = []; if (diff.ok && diff.stdout) parts.push(diff.stdout); // diff --stat 看不到未跟踪的新文件,用 status 补上 const status = await worktreeStatus(path); if (status.ok && status.stdout) { const untracked = status.stdout .split('\0') .filter((l) => l.startsWith('??')) .map((l) => ` 新文件(未跟踪): ${l.slice(3)}`); if (untracked.length > 0) parts.push(untracked.join('\n')); } return parts.join('\n'); } /** * 把 worktree 里的未提交改动确定性提交到临时分支(幂等:无改动直接 ok)。 * 为什么需要:子 agent 用 Edit/Write 改文件后通常**不会** git commit—— * 分支上没有提交的话,主 agent 收口时 `git merge` 合不到任何东西(改动只活在 * worktree 工作区里)。收尾时由引擎代提交,不依赖模型自觉。 * -c 内联身份兜底:机器没配 user.name/email 也能提交(squash 合并时最终 * 提交人仍是用户自己,临时分支上的作者名无所谓)。 */ export async function commitWorktreeChanges( path: string, message: string, ): Promise<{ ok: boolean; error?: string }> { const status = await worktreeStatus(path); if (!status.ok) return { ok: false, error: status.stderr || '无法核实隔离工作区的文件,未暂存或提交' }; if (!status.stdout) return { ok: true }; const sensitive = status.stdout.split('\0').map((line) => line.slice(3)).filter(isSensitiveWorktreePath); if (sensitive.length > 0) { return { ok: false, error: `拒绝自动提交敏感文件:${sensitive.join(', ')}` }; } const add = await runGit(['add', '-A'], path); if (!add.ok) return { ok: false, error: add.stderr || add.stdout }; const commit = await runGit( [ '-c', 'user.name=minimal-agent', '-c', 'user.email=agent@minimal-agent.local', 'commit', '-m', message, ], path, ); if (!commit.ok) return { ok: false, error: commit.stderr || commit.stdout }; return { ok: true }; } function isSensitiveWorktreePath(path: string): boolean { const normalized = path.replaceAll('\\', '/').toLowerCase(); const base = normalized.split('/').at(-1) ?? normalized; return base === '.env' || base.startsWith('.env.') || /(^|\/)\.ssh\//.test(normalized) || /(^|\/)(credentials?|secrets?)(\.|\/|$)/.test(normalized) || /\.(pem|key|p12|pfx|jks|keystore)$/.test(base) || base === 'id_rsa' || base === 'id_ed25519'; } export async function worktreeChangedFiles(path: string, baseSha: string): Promise { const result = await runGit(['diff', '--name-only', '-z', baseSha], path); const status = await worktreeStatus(path); const files = new Set(); if (result.ok) for (const row of result.stdout.split('\0')) if (row) files.add(row); if (status.ok) for (const row of status.stdout.split('\0')) if (row.length > 3) files.add(row.slice(3)); return [...files].sort(); } /** * 清理 worktree 目录 + 临时分支。失败返回结果并记日志,不抛—— * 清理残留可由用户随时 `git worktree remove` / `git branch -D` 手动处理。 */ export async function removeAgentWorktree( path: string, branch: string, gitRoot: string, forceDiscard = false, ): Promise<{ ok: boolean; error?: string }> { if (!forceDiscard) { // Git may consider a tree with ignored local outputs clean. Never silently // erase those during automatic cleanup after applying or finishing a task. const ignored = await runGit(['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory', '--no-empty-directory'], path); if (!ignored.ok || ignored.stdout) return { ok: false, error: `无法确认没有被忽略的本地文件;已保留 ${path} 和 ${branch}` }; } const rm = await runGit(['worktree', 'remove', ...(forceDiscard ? ['--force'] : []), path], gitRoot); if (!rm.ok) { dlog('agent', 'worktree remove 失败', { path, err: rm.stderr }); return { ok: false, error: rm.stderr || 'worktree remove 失败' }; } // 官方经验:remove 后立即 branch -D 偶发撞锁,等 100ms 释放 await new Promise((r) => setTimeout(r, 100)); const del = await runGit(['branch', '-D', branch], gitRoot); if (!del.ok) dlog('agent', 'worktree 分支删除失败', { branch, err: del.stderr }); return del.ok ? { ok: true } : { ok: false, error: `目录已移除,分支清理失败:${del.stderr}` }; } export interface AgentWorktreeDiff { id: string; branch: string; baseSha: string; diff: string; changedFiles: string[]; } async function resolveManagedWorktree(cwd: string, id: string): Promise { if (!validateSlug(id)) return { ok: false, error: '非法的子任务 ID' }; const root = await runGit(['rev-parse', '--show-toplevel'], cwd); if (!root.ok || !root.stdout) return { ok: false, error: '当前目录不是 Git 仓库' }; const path = join(root.stdout, WORKTREES_DIR, id); const branch = `agent/${id}`; const base = await runGit(['merge-base', branch, 'HEAD'], root.stdout); if (!base.ok || !base.stdout) return { ok: false, error: '未找到该隔离子任务' }; return { ok: true, path, branch, baseSha: base.stdout, gitRoot: root.stdout }; } export async function inspectAgentWorktree(cwd: string, id: string): Promise { const wt = await resolveManagedWorktree(cwd, id); if (!wt.ok) return { error: wt.error }; const diff = await runGit(['diff', '--binary', wt.baseSha, wt.branch], wt.gitRoot); if (!diff.ok) return { error: diff.stderr || '读取差异失败' }; const status = await worktreeStatus(wt.path); const pending = status.ok && status.stdout ? `\n\n尚未提交的隔离工作区改动(不会自动应用):\n${status.stdout.split('\0').filter(Boolean).join('\n')}` : ''; return { id, branch: wt.branch, baseSha: wt.baseSha, diff: `${diff.stdout}${pending}`.trim(), changedFiles: await worktreeChangedFiles(wt.path, wt.baseSha), }; } export async function applyAgentWorktree(cwd: string, id: string): Promise<{ ok: boolean; error?: string; warning?: string }> { const wt = await resolveManagedWorktree(cwd, id); if (!wt.ok) return wt; const status = await worktreeStatus(wt.path); if (!status.ok) return { ok: false, error: '无法确认隔离工作区状态,已停止自动应用' }; if (status.stdout) { return { ok: false, error: '隔离工作区仍有未提交改动(可能包含被安全策略拒绝提交的文件),为防止丢失,不能自动应用或清理', }; } const head = await runGit(['rev-parse', 'HEAD'], wt.gitRoot); if (!head.ok || head.stdout !== wt.baseSha) return { ok: false, error: '当前 HEAD 已变化,不能安全应用;请先人工审阅和同步分支' }; const patchLocation = await runGit(['rev-parse', '--git-path', `minimal-agent-${randomUUID()}.patch`], wt.gitRoot); if (!patchLocation.ok) return { ok: false, error: '无法定位 Git 补丁临时目录' }; const patchFile = resolve(wt.gitRoot, patchLocation.stdout); let createdPatch = false; try { // Have Git write the bytes directly: terminal decoding, trimming and output // size limits must never change the patch that will be applied. await writeFile(patchFile, '', { mode: 0o600, flag: 'wx' }); createdPatch = true; const diff = await runGit(['diff', '--binary', '--no-ext-diff', '--no-textconv', '--no-color', `--output=${patchFile}`, wt.baseSha, wt.branch], wt.gitRoot); if (!diff.ok) return { ok: false, error: diff.stderr || '生成差异失败' }; if ((await stat(patchFile)).size === 0) { const cleanup = await removeAgentWorktree(wt.path, wt.branch, wt.gitRoot); return { ok: true, ...(cleanup.ok ? {} : { warning: cleanup.error }) }; } const check = await runGit(['apply', '--check', patchFile], wt.gitRoot); if (!check.ok) return { ok: false, error: `变更检查失败:${check.stderr || check.stdout}` }; const apply = await runGit(['apply', patchFile], wt.gitRoot); if (!apply.ok) return { ok: false, error: `应用变更失败:${apply.stderr || apply.stdout}` }; const cleanup = await removeAgentWorktree(wt.path, wt.branch, wt.gitRoot); return { ok: true, ...(cleanup.ok ? {} : { warning: cleanup.error }) }; } finally { if (createdPatch) await unlink(patchFile).catch(() => {}); } } export async function discardAgentWorktree(cwd: string, id: string): Promise<{ ok: boolean; error?: string }> { const wt = await resolveManagedWorktree(cwd, id); if (!wt.ok) return wt; return removeAgentWorktree(wt.path, wt.branch, wt.gitRoot, true); }