{"version":3,"file":"worktree.d.ts","sourceRoot":"","sources":["../../src/core/worktree.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,eAAO,MAAM,aAAa,QAA4B,CAAC;AAMvD,MAAM,WAAW,QAAQ;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IACjC,kFAAkF;IAClF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,yEAAyE;IACzE,YAAY,EAAE,MAAM,CAAC;IACrB,yFAAyF;IACzF,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,WAAW;IAC3B,EAAE,EAAE,OAAO,CAAC;IACZ,oDAAoD;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAeD,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAEjE;AAkBD,mFAAmF;AACnF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,SAAS,GAAG,QAAQ,CAUvF;AAYD;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,WAAW,CA0DvE;AAED,mFAAmF;AACnF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI,CAajE","sourcesContent":["/**\n * Git worktree isolation for parallel sub-agents.\n *\n * Each parallel agent gets its own worktree under `.phi/worktrees/<id>` so its\n * writes never touch the main working tree. After the agent finishes, its diff\n * (against the base ref) is applied back onto the main working tree with\n * explicit conflict detection: when the main tree has moved on the same files\n * (typically because another agent was merged first), the merge returns a\n * conflict report containing BOTH diffs instead of silently overwriting.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nexport const WORKTREE_ROOT = join(\".phi\", \"worktrees\");\n/** Same root as git prints it (always forward slashes, also on Windows). */\nconst WORKTREE_ROOT_GIT_PREFIX = \".phi/worktrees/\";\n/** File in the worktree's private git dir recording the commit it was created from. */\nconst BASE_MARKER = \"phi-base-ref\";\n\nexport interface Worktree {\n\tid: string;\n\tpath: string;\n\tbaseRef: string;\n}\n\nexport interface MergeConflictInfo {\n\t/** Files touched by both the incoming worktree diff and the current main tree. */\n\tfiles: string[];\n\t/** The diff produced by the worktree being merged (incoming changes). */\n\tincomingDiff: string;\n\t/** The diff of the main working tree against the same base (already-applied changes). */\n\tcurrentDiff: string;\n}\n\nexport interface MergeResult {\n\tok: boolean;\n\t/** The incoming diff, when applied successfully. */\n\tapplied?: string;\n\tconflict?: MergeConflictInfo;\n}\n\nfunction git(cwd: string, args: string[], input?: string): string {\n\treturn execFileSync(\"git\", [\"-C\", cwd, ...args], {\n\t\tencoding: \"utf-8\",\n\t\t...(input !== undefined ? { input } : {}),\n\t}).toString();\n}\n\nfunction sanitizeId(id: string): string {\n\tconst safe = id.replace(/[^\\w.-]/g, \"-\");\n\tif (!safe) throw new Error(\"worktree id must contain at least one safe character\");\n\treturn safe;\n}\n\nexport function worktreePath(repoRoot: string, id: string): string {\n\treturn join(repoRoot, WORKTREE_ROOT, sanitizeId(id));\n}\n\nfunction worktreeGitDir(path: string): string {\n\tconst gitDir = git(path, [\"rev-parse\", \"--git-dir\"]).trim();\n\treturn isAbsolute(gitDir) ? gitDir : join(path, gitDir);\n}\n\n/** Commit the worktree was created from (falls back to HEAD for worktrees made before the marker). */\nfunction worktreeBase(path: string): string {\n\ttry {\n\t\tconst recorded = readFileSync(join(worktreeGitDir(path), BASE_MARKER), \"utf-8\").trim();\n\t\tif (recorded) return recorded;\n\t} catch {\n\t\t// No marker: worktree created by an older version.\n\t}\n\treturn git(path, [\"rev-parse\", \"HEAD\"]).trim();\n}\n\n/** Create a detached worktree for `id` under .phi/worktrees/, based on baseRef. */\nexport function createWorktree(repoRoot: string, id: string, baseRef = \"HEAD\"): Worktree {\n\tconst safeId = sanitizeId(id);\n\tconst path = join(repoRoot, WORKTREE_ROOT, safeId);\n\tmkdirSync(dirname(path), { recursive: true });\n\tconst baseCommit = git(repoRoot, [\"rev-parse\", \"--verify\", `${baseRef}^{commit}`]).trim();\n\tgit(repoRoot, [\"worktree\", \"add\", \"--detach\", path, baseCommit]);\n\t// Remember the base: if the sub-agent commits inside its worktree, HEAD moves and\n\t// diffing against HEAD would silently drop those commits from the merge.\n\twriteFileSync(join(worktreeGitDir(path), BASE_MARKER), baseCommit);\n\treturn { id: safeId, path, baseRef: baseCommit };\n}\n\nfunction changedFiles(cwd: string, baseRef: string): string[] {\n\tconst out = git(cwd, [\"diff\", \"--name-only\", baseRef]).trim();\n\treturn out ? out.split(\"\\n\").filter(Boolean) : [];\n}\n\nfunction untrackedFiles(cwd: string): string[] {\n\tconst out = git(cwd, [\"ls-files\", \"--others\", \"--exclude-standard\"]).trim();\n\treturn out ? out.split(\"\\n\").filter(Boolean) : [];\n}\n\n/**\n * Merge a worktree's changes back onto the main working tree.\n *\n * Checks the worktree diff (tracked files, including commits made inside the\n * worktree) with `git apply --check` and every new untracked file BEFORE writing\n * anything, then applies them. A conflict therefore never leaves the main tree\n * half-merged: it returns an explicit report with both diffs. Never throws on\n * conflict; throws only on unexpected git failures.\n */\nexport function mergeWorktree(repoRoot: string, id: string): MergeResult {\n\tconst path = worktreePath(repoRoot, id);\n\tif (!existsSync(path)) throw new Error(`worktree ${id} not found at ${path}`);\n\tconst baseRef = worktreeBase(path);\n\t// base..working tree: commits made in the worktree plus uncommitted edits.\n\tconst incomingDiff = git(path, [\"diff\", baseRef]);\n\tconst incomingUntracked = untrackedFiles(path).filter((f) => !f.startsWith(WORKTREE_ROOT_GIT_PREFIX));\n\n\tif (!incomingDiff.trim() && incomingUntracked.length === 0) {\n\t\treturn { ok: true, applied: \"\" };\n\t}\n\n\tif (incomingDiff.trim()) {\n\t\ttry {\n\t\t\tgit(repoRoot, [\"apply\", \"--check\", \"--whitespace=nowarn\"], incomingDiff);\n\t\t} catch {\n\t\t\tconst incomingFiles = changedFiles(path, baseRef);\n\t\t\tconst currentFiles = new Set(changedFiles(repoRoot, baseRef));\n\t\t\tconst overlap = incomingFiles.filter((f) => currentFiles.has(f));\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tconflict: {\n\t\t\t\t\tfiles: overlap.length > 0 ? overlap : incomingFiles,\n\t\t\t\t\tincomingDiff,\n\t\t\t\t\tcurrentDiff: git(repoRoot, [\"diff\", baseRef]),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// An existing file with different content is a conflict.\n\tconst newFiles: Array<{ dest: string; content: Buffer }> = [];\n\tfor (const rel of incomingUntracked) {\n\t\tconst content = readFileSync(join(path, rel));\n\t\tconst dest = join(repoRoot, rel);\n\t\tif (existsSync(dest)) {\n\t\t\tif (!readFileSync(dest).equals(content)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tconflict: {\n\t\t\t\t\t\tfiles: [rel],\n\t\t\t\t\t\tincomingDiff: `new file in worktree ${id}: ${rel}\\n${content.toString(\"utf-8\")}`,\n\t\t\t\t\t\tcurrentDiff: `existing file in main tree: ${rel}\\n${readFileSync(dest).toString(\"utf-8\")}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tnewFiles.push({ dest, content });\n\t}\n\n\tif (incomingDiff.trim()) git(repoRoot, [\"apply\", \"--whitespace=nowarn\"], incomingDiff);\n\tfor (const { dest, content } of newFiles) {\n\t\tmkdirSync(dirname(dest), { recursive: true });\n\t\twriteFileSync(dest, content);\n\t}\n\n\treturn { ok: true, applied: incomingDiff };\n}\n\n/** Remove a worktree and its directory (forced: pending changes are discarded). */\nexport function removeWorktree(repoRoot: string, id: string): void {\n\tconst path = worktreePath(repoRoot, id);\n\tif (!existsSync(path)) return;\n\ttry {\n\t\tgit(repoRoot, [\"worktree\", \"remove\", \"--force\", path]);\n\t} catch {\n\t\trmSync(path, { recursive: true, force: true });\n\t\ttry {\n\t\t\tgit(repoRoot, [\"worktree\", \"prune\"]);\n\t\t} catch {\n\t\t\t/* best effort */\n\t\t}\n\t}\n}\n"]}