@agimon-ai/doompi-git 0.0.1-alpha.4 → 0.0.1-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/adapters/hub/hubClient.cjs +1 -1
  2. package/dist/adapters/hub/hubClient.cjs.map +1 -1
  3. package/dist/adapters/hub/hubClient.mjs +1 -1
  4. package/dist/adapters/hub/hubClient.mjs.map +1 -1
  5. package/dist/adapters/pi/extensions/runWorktreeTool.cjs +2 -2
  6. package/dist/adapters/pi/extensions/runWorktreeTool.cjs.map +1 -1
  7. package/dist/adapters/pi/extensions/runWorktreeTool.mjs +2 -2
  8. package/dist/adapters/pi/extensions/runWorktreeTool.mjs.map +1 -1
  9. package/dist/adapters/web/worktreesChannel.cjs +1 -1
  10. package/dist/adapters/web/worktreesChannel.cjs.map +1 -1
  11. package/dist/adapters/web/worktreesChannel.d.cts.map +1 -1
  12. package/dist/adapters/web/worktreesChannel.d.mts.map +1 -1
  13. package/dist/adapters/web/worktreesChannel.mjs +1 -1
  14. package/dist/adapters/web/worktreesChannel.mjs.map +1 -1
  15. package/dist/adapters/worktree/compositionMirror.cjs +2 -0
  16. package/dist/adapters/worktree/compositionMirror.cjs.map +1 -0
  17. package/dist/adapters/worktree/compositionMirror.mjs +2 -0
  18. package/dist/adapters/worktree/compositionMirror.mjs.map +1 -0
  19. package/dist/adapters/worktree/gitCli.cjs +1 -1
  20. package/dist/adapters/worktree/gitCli.cjs.map +1 -1
  21. package/dist/adapters/worktree/gitCli.mjs +1 -1
  22. package/dist/adapters/worktree/gitCli.mjs.map +1 -1
  23. package/dist/adapters/worktree/worktreeOperations.cjs +1 -1
  24. package/dist/adapters/worktree/worktreeOperations.cjs.map +1 -1
  25. package/dist/adapters/worktree/worktreeOperations.d.cts +8 -2
  26. package/dist/adapters/worktree/worktreeOperations.d.cts.map +1 -1
  27. package/dist/adapters/worktree/worktreeOperations.d.mts +8 -2
  28. package/dist/adapters/worktree/worktreeOperations.d.mts.map +1 -1
  29. package/dist/adapters/worktree/worktreeOperations.mjs +1 -1
  30. package/dist/adapters/worktree/worktreeOperations.mjs.map +1 -1
  31. package/dist/services/support/errors.cjs.map +1 -1
  32. package/dist/services/support/errors.mjs.map +1 -1
  33. package/dist/services/worktreeNaming.cjs +1 -1
  34. package/dist/services/worktreeNaming.cjs.map +1 -1
  35. package/dist/services/worktreeNaming.d.cts +7 -0
  36. package/dist/services/worktreeNaming.d.cts.map +1 -1
  37. package/dist/services/worktreeNaming.d.mts +7 -0
  38. package/dist/services/worktreeNaming.d.mts.map +1 -1
  39. package/dist/services/worktreeNaming.mjs +1 -1
  40. package/dist/services/worktreeNaming.mjs.map +1 -1
  41. package/package.json +5 -5
  42. package/src/prompts/doompi-use-git/SKILL.md +5 -2
  43. package/src/types/worktreeRegistry.ts +9 -0
  44. package/src/web/components/RunWorktreeToolMessage.tsx +20 -12
  45. package/src/web/components/WorktreesActivitySection.tsx +24 -9
  46. package/src/web/components/WorktreesPanel.tsx +94 -45
  47. package/dist/adapters/worktree/dependencyInstall.cjs +0 -2
  48. package/dist/adapters/worktree/dependencyInstall.cjs.map +0 -1
  49. package/dist/adapters/worktree/dependencyInstall.mjs +0 -2
  50. package/dist/adapters/worktree/dependencyInstall.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:child_process"),n=require("node:fs");n=e.__toESM(n,1);const r=3e4;function i(e,n,r){return new Promise(i=>{(0,t.execFile)(`git`,[...n],{cwd:e,timeout:r,maxBuffer:1e6,env:{...process.env,LC_ALL:`C`}},(e,t,n)=>{i({code:e&&typeof e.code==`number`?e.code:+!!e,stdout:String(t),stderr:String(n)})})})}function a(e,t){return Error(`git ${e} failed (exit ${String(t.code)}, ${String(t.stderr.length)} bytes of stderr)`)}function o(e){let t=e.toLowerCase();return t.includes(`is not a working tree`)||t.includes(`cannot remove working tree`)}function s(){let e=async e=>{await i(e,[`worktree`,`prune`],15e3)};return{async addWorktree({repositoryRoot:e,path:t,branch:n,baseRef:r}){let o=await i(e,[`worktree`,`add`,`-b`,n,t,r],3e5);if(o.code!==0)throw a(`worktree add`,o)},async removeWorktree({repositoryRoot:t,path:r,force:s}){let c=await i(t,[`worktree`,`remove`,...s?[`--force`]:[],r],3e5);if(c.code!==0){if(o(c.stderr)&&!n.default.existsSync(r)){await e(t);return}throw a(`worktree remove`,c)}},pruneWorktrees:e,async listWorktreePaths(e){let t=await i(e,[`worktree`,`list`,`--porcelain`],r);return t.code===0?t.stdout.split(`
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:child_process"),n=require("node:fs");n=e.__toESM(n,1);const r=3e4;function i(e,n,r){return new Promise(i=>{(0,t.execFile)(`git`,[...n],{cwd:e,timeout:r,maxBuffer:1e6,env:{...process.env,LC_ALL:`C`}},(e,t,n)=>{i({code:e&&typeof e.code==`number`?e.code:+!!e,stdout:String(t),stderr:String(n)})})})}function a(e,t){return Error(`git ${e} failed (exit ${String(t.code)}, ${String(t.stderr.length)} bytes of stderr)`)}function o(e){let t=e.toLowerCase();return t.includes(`is not a working tree`)||t.includes(`cannot remove working tree`)}function s(){let e=async e=>{await i(e,[`worktree`,`prune`],15e3)};return{async addWorktree({repositoryRoot:e,path:t,branch:n,baseRef:r}){let o=await i(e,[`worktree`,`add`,`-b`,n,t,r],3e5);if(o.code!==0)throw a(`worktree add`,o)},async removeWorktree({repositoryRoot:t,path:r,force:s}){let c=await i(t,[`worktree`,`remove`,...s?[`--force`]:[],r],3e5);if(c.code!==0){if(o(c.stderr)&&!n.default.existsSync(r)){await e(t);return}throw a(`worktree remove`,c)}},async deleteBranch({repositoryRoot:e,branch:t}){return(await i(e,[`branch`,`-d`,t],r)).code===0},pruneWorktrees:e,async listWorktreePaths(e){let t=await i(e,[`worktree`,`list`,`--porcelain`],r);return t.code===0?t.stdout.split(`
2
2
  `).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).trim()).filter(e=>e!==``):[]},async dirtyFiles(e){let t=await i(e,[`status`,`--porcelain`],r);return t.code===0?t.stdout.split(`
3
3
  `).map(e=>e.slice(3).trim()).filter(e=>e!==``):[]},async repositoryRoot(e){let t=await i(e,[`rev-parse`,`--show-toplevel`],r);if(t.code!==0)return;let n=t.stdout.trim();return n===``?void 0:n},async currentBranch(e){let t=await i(e,[`rev-parse`,`--abbrev-ref`,`HEAD`],r);if(t.code!==0)return;let n=t.stdout.trim();return n===``?void 0:n},async mergeBranch({repositoryRoot:e,branch:t,message:n}){let o=await i(e,[`merge`,`--no-ff`,...n===void 0?[]:[`-m`,n],t],r);if(o.code!==0)throw a(`merge`,o)}}}exports.createWorktreeGit=s;
4
4
  //# sourceMappingURL=gitCli.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"gitCli.cjs","names":["fs"],"sources":["../../../src/adapters/worktree/gitCli.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport type { WorktreeGit } from '../../types/worktreeRegistry.ts';\n\n/**\n * Git, as this package needs it.\n *\n * The timeouts are not uniform because the operations are not comparable. A\n * read answers in milliseconds; `worktree add` copies an entire checkout and\n * `worktree remove` deletes one, both bounded by the filesystem rather than by\n * git, and both minutes rather than seconds on a large repository or on\n * Windows. A single timeout would either fail honest work or hang on a wedged\n * one.\n */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Runs git and reports the outcome without ever throwing on a non-zero exit.\n *\n * LC_ALL is pinned because two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The message a failed git call is allowed to surface.\n *\n * Raw stderr never travels: it can carry a remote URL with a token in it, and\n * this text ends up in a tool result the model reads and may repeat.\n */\nfunction failure(operation: string, result: GitResult): Error {\n return new Error(\n `git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`,\n );\n}\n\n/** Git's own words for \"that worktree is not there any more\". */\nfunction missingWorktree(stderr: string): boolean {\n const normalized = stderr.toLowerCase();\n return normalized.includes('is not a working tree') || normalized.includes('cannot remove working tree');\n}\n\nexport function createWorktreeGit(): WorktreeGit {\n const prune = async (repositoryRoot: string): Promise<void> => {\n await git(repositoryRoot, ['worktree', 'prune'], PRUNE_TIMEOUT_MS);\n };\n\n return {\n async addWorktree({ repositoryRoot, path, branch, baseRef }) {\n const result = await git(repositoryRoot, ['worktree', 'add', '-b', branch, path, baseRef], ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async removeWorktree({ repositoryRoot, path, force }) {\n const args = ['worktree', 'remove', ...(force ? ['--force'] : []), path];\n const result = await git(repositoryRoot, args, REMOVE_TIMEOUT_MS);\n if (result.code === 0) return;\n // A directory deleted behind git's back leaves an administrative entry\n // that makes a later `worktree add` at the same path refuse. Treating\n // \"already gone\" as success and pruning is what keeps that path reusable,\n // and it makes remove idempotent for a caller retrying after a crash.\n if (missingWorktree(result.stderr) && !fs.existsSync(path)) {\n await prune(repositoryRoot);\n return;\n }\n throw failure('worktree remove', result);\n },\n\n pruneWorktrees: prune,\n\n async listWorktreePaths(repositoryRoot) {\n const result = await git(repositoryRoot, ['worktree', 'list', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .filter((line) => line.startsWith('worktree '))\n .map((line) => line.slice('worktree '.length).trim())\n .filter((line) => line !== '');\n },\n\n async dirtyFiles(path) {\n const result = await git(path, ['status', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .map((line) => line.slice(3).trim())\n .filter((line) => line !== '');\n },\n\n async repositoryRoot(cwd) {\n const result = await git(cwd, ['rev-parse', '--show-toplevel'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const root = result.stdout.trim();\n return root === '' ? undefined : root;\n },\n\n async currentBranch(cwd) {\n const result = await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const branch = result.stdout.trim();\n return branch === '' ? undefined : branch;\n },\n\n async mergeBranch({ repositoryRoot, branch, message }) {\n // --no-ff so the worktree's work stays identifiable as a unit after the\n // fact. A fast-forward would erase the fact that it was ever separate,\n // which is the one thing worth keeping about a worktree.\n const args = ['merge', '--no-ff', ...(message === undefined ? [] : ['-m', message]), branch];\n const result = await git(repositoryRoot, args, READ_TIMEOUT_MS);\n if (result.code === 0) return;\n // A conflicted merge leaves the parent mid-merge, which is a state the\n // person has to resolve; aborting for them would throw away the conflict\n // markers they need to see.\n throw failure('merge', result);\n },\n };\n}\n"],"mappings":"kIAcA,MAAM,EAAkB,IAmBxB,SAAS,EAAI,EAAa,EAAyB,EAAqC,CACtF,OAAO,IAAI,QAAS,GAAY,EAC9B,EAAA,EAAA,SAAA,CACE,MACA,CAAC,GAAG,CAAI,EACR,CAAE,MAAK,UAAS,UAAW,IAAkB,IAAK,CAAE,GAAG,QAAQ,IAAK,OAAQ,GAAI,CAAE,GACjF,EAAO,EAAQ,IAAW,CAEzB,EAAQ,CAAE,KADG,GAAS,OAAO,EAAM,MAAS,SAAW,EAAM,KAAO,KACpD,OAAQ,OAAO,CAAM,EAAG,OAAQ,OAAO,CAAM,CAAE,CAAC,CAClE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C,CAAC,KAAK,CAAC,CAAC,CACpD,OAAQ,GAAS,IAAS,EAAE,EALD,CAAC,CAMjC,EAEA,MAAM,WAAW,EAAM,CACrB,IAAM,EAAS,MAAM,EAAI,EAAM,CAAC,SAAU,aAAa,EAAG,CAAe,EAEzE,OADI,EAAO,OAAS,EACb,EAAO,OACX,MAAM;CAAI,CAAC,CACX,IAAK,GAAS,EAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CACnC,OAAQ,GAAS,IAAS,EAAE,EAJD,CAAC,CAKjC,EAEA,MAAM,eAAe,EAAK,CACxB,IAAM,EAAS,MAAM,EAAI,EAAK,CAAC,YAAa,iBAAiB,EAAG,CAAe,EAC/E,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAO,EAAO,OAAO,KAAK,EAChC,OAAO,IAAS,GAAK,IAAA,GAAY,CACnC,EAEA,MAAM,cAAc,EAAK,CACvB,IAAM,EAAS,MAAM,EAAI,EAAK,CAAC,YAAa,eAAgB,MAAM,EAAG,CAAe,EACpF,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAS,EAAO,OAAO,KAAK,EAClC,OAAO,IAAW,GAAK,IAAA,GAAY,CACrC,EAEA,MAAM,YAAY,CAAE,iBAAgB,SAAQ,WAAW,CAKrD,IAAM,EAAS,MAAM,EAAI,EAAgB,CAD3B,QAAS,UAAW,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,KAAM,CAAO,EAAI,CACzC,EAAG,CAAe,EAC1D,KAAO,OAAS,EAIpB,MAAM,EAAQ,QAAS,CAAM,CAC/B,CACF,CACF"}
1
+ {"version":3,"file":"gitCli.cjs","names":["fs"],"sources":["../../../src/adapters/worktree/gitCli.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport type { WorktreeGit } from '../../types/worktreeRegistry.ts';\n\n/**\n * Git, as this package needs it.\n *\n * The timeouts are not uniform because the operations are not comparable. A\n * read answers in milliseconds; `worktree add` copies an entire checkout and\n * `worktree remove` deletes one, both bounded by the filesystem rather than by\n * git, and both minutes rather than seconds on a large repository or on\n * Windows. A single timeout would either fail honest work or hang on a wedged\n * one.\n */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Runs git and reports the outcome without ever throwing on a non-zero exit.\n *\n * LC_ALL is pinned because two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The message a failed git call is allowed to surface.\n *\n * Raw stderr never travels: it can carry a remote URL with a token in it, and\n * this text ends up in a tool result the model reads and may repeat.\n */\nfunction failure(operation: string, result: GitResult): Error {\n return new Error(\n `git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`,\n );\n}\n\n/** Git's own words for \"that worktree is not there any more\". */\nfunction missingWorktree(stderr: string): boolean {\n const normalized = stderr.toLowerCase();\n return normalized.includes('is not a working tree') || normalized.includes('cannot remove working tree');\n}\n\nexport function createWorktreeGit(): WorktreeGit {\n const prune = async (repositoryRoot: string): Promise<void> => {\n await git(repositoryRoot, ['worktree', 'prune'], PRUNE_TIMEOUT_MS);\n };\n\n return {\n async addWorktree({ repositoryRoot, path, branch, baseRef }) {\n const result = await git(repositoryRoot, ['worktree', 'add', '-b', branch, path, baseRef], ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async removeWorktree({ repositoryRoot, path, force }) {\n const args = ['worktree', 'remove', ...(force ? ['--force'] : []), path];\n const result = await git(repositoryRoot, args, REMOVE_TIMEOUT_MS);\n if (result.code === 0) return;\n // A directory deleted behind git's back leaves an administrative entry\n // that makes a later `worktree add` at the same path refuse. Treating\n // \"already gone\" as success and pruning is what keeps that path reusable,\n // and it makes remove idempotent for a caller retrying after a crash.\n if (missingWorktree(result.stderr) && !fs.existsSync(path)) {\n await prune(repositoryRoot);\n return;\n }\n throw failure('worktree remove', result);\n },\n\n async deleteBranch({ repositoryRoot, branch }) {\n // -d, never -D: git refuses a branch that still holds unmerged commits,\n // and that refusal is the whole safety property. A rollback that could\n // throw away work someone committed in the worktree is worse than a\n // branch left behind.\n const result = await git(repositoryRoot, ['branch', '-d', branch], READ_TIMEOUT_MS);\n return result.code === 0;\n },\n pruneWorktrees: prune,\n\n async listWorktreePaths(repositoryRoot) {\n const result = await git(repositoryRoot, ['worktree', 'list', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .filter((line) => line.startsWith('worktree '))\n .map((line) => line.slice('worktree '.length).trim())\n .filter((line) => line !== '');\n },\n\n async dirtyFiles(path) {\n const result = await git(path, ['status', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .map((line) => line.slice(3).trim())\n .filter((line) => line !== '');\n },\n\n async repositoryRoot(cwd) {\n const result = await git(cwd, ['rev-parse', '--show-toplevel'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const root = result.stdout.trim();\n return root === '' ? undefined : root;\n },\n\n async currentBranch(cwd) {\n const result = await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const branch = result.stdout.trim();\n return branch === '' ? undefined : branch;\n },\n\n async mergeBranch({ repositoryRoot, branch, message }) {\n // --no-ff so the worktree's work stays identifiable as a unit after the\n // fact. A fast-forward would erase the fact that it was ever separate,\n // which is the one thing worth keeping about a worktree.\n const args = ['merge', '--no-ff', ...(message === undefined ? [] : ['-m', message]), branch];\n const result = await git(repositoryRoot, args, READ_TIMEOUT_MS);\n if (result.code === 0) return;\n // A conflicted merge leaves the parent mid-merge, which is a state the\n // person has to resolve; aborting for them would throw away the conflict\n // markers they need to see.\n throw failure('merge', result);\n },\n };\n}\n"],"mappings":"kIAcA,MAAM,EAAkB,IAmBxB,SAAS,EAAI,EAAa,EAAyB,EAAqC,CACtF,OAAO,IAAI,QAAS,GAAY,EAC9B,EAAA,EAAA,SAAA,CACE,MACA,CAAC,GAAG,CAAI,EACR,CAAE,MAAK,UAAS,UAAW,IAAkB,IAAK,CAAE,GAAG,QAAQ,IAAK,OAAQ,GAAI,CAAE,GACjF,EAAO,EAAQ,IAAW,CAEzB,EAAQ,CAAE,KADG,GAAS,OAAO,EAAM,MAAS,SAAW,EAAM,KAAO,KACpD,OAAQ,OAAO,CAAM,EAAG,OAAQ,OAAO,CAAM,CAAE,CAAC,CAClE,CACF,CACF,CAAC,CACH,CAQA,SAAS,EAAQ,EAAmB,EAA0B,CAC5D,OAAW,MACT,OAAO,EAAU,gBAAgB,OAAO,EAAO,IAAI,EAAE,IAAI,OAAO,EAAO,OAAO,MAAM,EAAE,kBACxF,CACF,CAGA,SAAS,EAAgB,EAAyB,CAChD,IAAM,EAAa,EAAO,YAAY,EACtC,OAAO,EAAW,SAAS,uBAAuB,GAAK,EAAW,SAAS,4BAA4B,CACzG,CAEA,SAAgB,GAAiC,CAC/C,IAAM,EAAQ,KAAO,IAA0C,CAC7D,MAAM,EAAI,EAAgB,CAAC,WAAY,OAAO,EAAG,IAAgB,CACnE,EAEA,MAAO,CACL,MAAM,YAAY,CAAE,iBAAgB,OAAM,SAAQ,WAAW,CAC3D,IAAM,EAAS,MAAM,EAAI,EAAgB,CAAC,WAAY,MAAO,KAAM,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AC,YAAa,iBAAiB,EAAG,CAAe,EAC/E,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAO,EAAO,OAAO,KAAK,EAChC,OAAO,IAAS,GAAK,IAAA,GAAY,CACnC,EAEA,MAAM,cAAc,EAAK,CACvB,IAAM,EAAS,MAAM,EAAI,EAAK,CAAC,YAAa,eAAgB,MAAM,EAAG,CAAe,EACpF,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAS,EAAO,OAAO,KAAK,EAClC,OAAO,IAAW,GAAK,IAAA,GAAY,CACrC,EAEA,MAAM,YAAY,CAAE,iBAAgB,SAAQ,WAAW,CAKrD,IAAM,EAAS,MAAM,EAAI,EAAgB,CAD3B,QAAS,UAAW,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,KAAM,CAAO,EAAI,CACzC,EAAG,CAAe,EAC1D,KAAO,OAAS,EAIpB,MAAM,EAAQ,QAAS,CAAM,CAC/B,CACF,CACF"}
@@ -1,4 +1,4 @@
1
- import{execFile as e}from"node:child_process";import t from"node:fs";const n=3e4;function r(t,n,r){return new Promise(i=>{e(`git`,[...n],{cwd:t,timeout:r,maxBuffer:1e6,env:{...process.env,LC_ALL:`C`}},(e,t,n)=>{i({code:e&&typeof e.code==`number`?e.code:+!!e,stdout:String(t),stderr:String(n)})})})}function i(e,t){return Error(`git ${e} failed (exit ${String(t.code)}, ${String(t.stderr.length)} bytes of stderr)`)}function a(e){let t=e.toLowerCase();return t.includes(`is not a working tree`)||t.includes(`cannot remove working tree`)}function o(){let e=async e=>{await r(e,[`worktree`,`prune`],15e3)};return{async addWorktree({repositoryRoot:e,path:t,branch:n,baseRef:a}){let o=await r(e,[`worktree`,`add`,`-b`,n,t,a],3e5);if(o.code!==0)throw i(`worktree add`,o)},async removeWorktree({repositoryRoot:n,path:o,force:s}){let c=await r(n,[`worktree`,`remove`,...s?[`--force`]:[],o],3e5);if(c.code!==0){if(a(c.stderr)&&!t.existsSync(o)){await e(n);return}throw i(`worktree remove`,c)}},pruneWorktrees:e,async listWorktreePaths(e){let t=await r(e,[`worktree`,`list`,`--porcelain`],n);return t.code===0?t.stdout.split(`
1
+ import{execFile as e}from"node:child_process";import t from"node:fs";const n=3e4;function r(t,n,r){return new Promise(i=>{e(`git`,[...n],{cwd:t,timeout:r,maxBuffer:1e6,env:{...process.env,LC_ALL:`C`}},(e,t,n)=>{i({code:e&&typeof e.code==`number`?e.code:+!!e,stdout:String(t),stderr:String(n)})})})}function i(e,t){return Error(`git ${e} failed (exit ${String(t.code)}, ${String(t.stderr.length)} bytes of stderr)`)}function a(e){let t=e.toLowerCase();return t.includes(`is not a working tree`)||t.includes(`cannot remove working tree`)}function o(){let e=async e=>{await r(e,[`worktree`,`prune`],15e3)};return{async addWorktree({repositoryRoot:e,path:t,branch:n,baseRef:a}){let o=await r(e,[`worktree`,`add`,`-b`,n,t,a],3e5);if(o.code!==0)throw i(`worktree add`,o)},async removeWorktree({repositoryRoot:n,path:o,force:s}){let c=await r(n,[`worktree`,`remove`,...s?[`--force`]:[],o],3e5);if(c.code!==0){if(a(c.stderr)&&!t.existsSync(o)){await e(n);return}throw i(`worktree remove`,c)}},async deleteBranch({repositoryRoot:e,branch:t}){return(await r(e,[`branch`,`-d`,t],n)).code===0},pruneWorktrees:e,async listWorktreePaths(e){let t=await r(e,[`worktree`,`list`,`--porcelain`],n);return t.code===0?t.stdout.split(`
2
2
  `).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).trim()).filter(e=>e!==``):[]},async dirtyFiles(e){let t=await r(e,[`status`,`--porcelain`],n);return t.code===0?t.stdout.split(`
3
3
  `).map(e=>e.slice(3).trim()).filter(e=>e!==``):[]},async repositoryRoot(e){let t=await r(e,[`rev-parse`,`--show-toplevel`],n);if(t.code!==0)return;let i=t.stdout.trim();return i===``?void 0:i},async currentBranch(e){let t=await r(e,[`rev-parse`,`--abbrev-ref`,`HEAD`],n);if(t.code!==0)return;let i=t.stdout.trim();return i===``?void 0:i},async mergeBranch({repositoryRoot:e,branch:t,message:a}){let o=await r(e,[`merge`,`--no-ff`,...a===void 0?[]:[`-m`,a],t],n);if(o.code!==0)throw i(`merge`,o)}}}export{o as createWorktreeGit};
4
4
  //# sourceMappingURL=gitCli.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"gitCli.mjs","names":[],"sources":["../../../src/adapters/worktree/gitCli.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport type { WorktreeGit } from '../../types/worktreeRegistry.ts';\n\n/**\n * Git, as this package needs it.\n *\n * The timeouts are not uniform because the operations are not comparable. A\n * read answers in milliseconds; `worktree add` copies an entire checkout and\n * `worktree remove` deletes one, both bounded by the filesystem rather than by\n * git, and both minutes rather than seconds on a large repository or on\n * Windows. A single timeout would either fail honest work or hang on a wedged\n * one.\n */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Runs git and reports the outcome without ever throwing on a non-zero exit.\n *\n * LC_ALL is pinned because two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The message a failed git call is allowed to surface.\n *\n * Raw stderr never travels: it can carry a remote URL with a token in it, and\n * this text ends up in a tool result the model reads and may repeat.\n */\nfunction failure(operation: string, result: GitResult): Error {\n return new Error(\n `git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`,\n );\n}\n\n/** Git's own words for \"that worktree is not there any more\". */\nfunction missingWorktree(stderr: string): boolean {\n const normalized = stderr.toLowerCase();\n return normalized.includes('is not a working tree') || normalized.includes('cannot remove working tree');\n}\n\nexport function createWorktreeGit(): WorktreeGit {\n const prune = async (repositoryRoot: string): Promise<void> => {\n await git(repositoryRoot, ['worktree', 'prune'], PRUNE_TIMEOUT_MS);\n };\n\n return {\n async addWorktree({ repositoryRoot, path, branch, baseRef }) {\n const result = await git(repositoryRoot, ['worktree', 'add', '-b', branch, path, baseRef], ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async removeWorktree({ repositoryRoot, path, force }) {\n const args = ['worktree', 'remove', ...(force ? ['--force'] : []), path];\n const result = await git(repositoryRoot, args, REMOVE_TIMEOUT_MS);\n if (result.code === 0) return;\n // A directory deleted behind git's back leaves an administrative entry\n // that makes a later `worktree add` at the same path refuse. Treating\n // \"already gone\" as success and pruning is what keeps that path reusable,\n // and it makes remove idempotent for a caller retrying after a crash.\n if (missingWorktree(result.stderr) && !fs.existsSync(path)) {\n await prune(repositoryRoot);\n return;\n }\n throw failure('worktree remove', result);\n },\n\n pruneWorktrees: prune,\n\n async listWorktreePaths(repositoryRoot) {\n const result = await git(repositoryRoot, ['worktree', 'list', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .filter((line) => line.startsWith('worktree '))\n .map((line) => line.slice('worktree '.length).trim())\n .filter((line) => line !== '');\n },\n\n async dirtyFiles(path) {\n const result = await git(path, ['status', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .map((line) => line.slice(3).trim())\n .filter((line) => line !== '');\n },\n\n async repositoryRoot(cwd) {\n const result = await git(cwd, ['rev-parse', '--show-toplevel'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const root = result.stdout.trim();\n return root === '' ? undefined : root;\n },\n\n async currentBranch(cwd) {\n const result = await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const branch = result.stdout.trim();\n return branch === '' ? undefined : branch;\n },\n\n async mergeBranch({ repositoryRoot, branch, message }) {\n // --no-ff so the worktree's work stays identifiable as a unit after the\n // fact. A fast-forward would erase the fact that it was ever separate,\n // which is the one thing worth keeping about a worktree.\n const args = ['merge', '--no-ff', ...(message === undefined ? [] : ['-m', message]), branch];\n const result = await git(repositoryRoot, args, READ_TIMEOUT_MS);\n if (result.code === 0) return;\n // A conflicted merge leaves the parent mid-merge, which is a state the\n // person has to resolve; aborting for them would throw away the conflict\n // markers they need to see.\n throw failure('merge', result);\n },\n };\n}\n"],"mappings":"qEAcA,MAAM,EAAkB,IAmBxB,SAAS,EAAI,EAAa,EAAyB,EAAqC,CACtF,OAAO,IAAI,QAAS,GAAY,CAC9B,EACE,MACA,CAAC,GAAG,CAAI,EACR,CAAE,MAAK,UAAS,UAAW,IAAkB,IAAK,CAAE,GAAG,QAAQ,IAAK,OAAQ,GAAI,CAAE,GACjF,EAAO,EAAQ,IAAW,CAEzB,EAAQ,CAAE,KADG,GAAS,OAAO,EAAM,MAAS,SAAW,EAAM,KAAO,KACpD,OAAQ,OAAO,CAAM,EAAG,OAAQ,OAAO,CAAM,CAAE,CAAC,CAClE,CACF,CACF,CAAC,CACH,CAQA,SAAS,EAAQ,EAAmB,EAA0B,CAC5D,OAAW,MACT,OAAO,EAAU,gBAAgB,OAAO,EAAO,IAAI,EAAE,IAAI,OAAO,EAAO,OAAO,MAAM,EAAE,kBACxF,CACF,CAGA,SAAS,EAAgB,EAAyB,CAChD,IAAM,EAAa,EAAO,YAAY,EACtC,OAAO,EAAW,SAAS,uBAAuB,GAAK,EAAW,SAAS,4BAA4B,CACzG,CAEA,SAAgB,GAAiC,CAC/C,IAAM,EAAQ,KAAO,IAA0C,CAC7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Ae,EAAK,CACxB,IAAM,EAAS,MAAM,EAAI,EAAK,CAAC,YAAa,iBAAiB,EAAG,CAAe,EAC/E,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAO,EAAO,OAAO,KAAK,EAChC,OAAO,IAAS,GAAK,IAAA,GAAY,CACnC,EAEA,MAAM,cAAc,EAAK,CACvB,IAAM,EAAS,MAAM,EAAI,EAAK,CAAC,YAAa,eAAgB,MAAM,EAAG,CAAe,EACpF,GAAI,EAAO,OAAS,EAAG,OACvB,IAAM,EAAS,EAAO,OAAO,KAAK,EAClC,OAAO,IAAW,GAAK,IAAA,GAAY,CACrC,EAEA,MAAM,YAAY,CAAE,iBAAgB,SAAQ,WAAW,CAKrD,IAAM,EAAS,MAAM,EAAI,EAAgB,CAD3B,QAAS,UAAW,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,KAAM,CAAO,EAAI,CACzC,EAAG,CAAe,EAC1D,KAAO,OAAS,EAIpB,MAAM,EAAQ,QAAS,CAAM,CAC/B,CACF,CACF"}
1
+ {"version":3,"file":"gitCli.mjs","names":[],"sources":["../../../src/adapters/worktree/gitCli.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport type { WorktreeGit } from '../../types/worktreeRegistry.ts';\n\n/**\n * Git, as this package needs it.\n *\n * The timeouts are not uniform because the operations are not comparable. A\n * read answers in milliseconds; `worktree add` copies an entire checkout and\n * `worktree remove` deletes one, both bounded by the filesystem rather than by\n * git, and both minutes rather than seconds on a large repository or on\n * Windows. A single timeout would either fail honest work or hang on a wedged\n * one.\n */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Runs git and reports the outcome without ever throwing on a non-zero exit.\n *\n * LC_ALL is pinned because two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The message a failed git call is allowed to surface.\n *\n * Raw stderr never travels: it can carry a remote URL with a token in it, and\n * this text ends up in a tool result the model reads and may repeat.\n */\nfunction failure(operation: string, result: GitResult): Error {\n return new Error(\n `git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`,\n );\n}\n\n/** Git's own words for \"that worktree is not there any more\". */\nfunction missingWorktree(stderr: string): boolean {\n const normalized = stderr.toLowerCase();\n return normalized.includes('is not a working tree') || normalized.includes('cannot remove working tree');\n}\n\nexport function createWorktreeGit(): WorktreeGit {\n const prune = async (repositoryRoot: string): Promise<void> => {\n await git(repositoryRoot, ['worktree', 'prune'], PRUNE_TIMEOUT_MS);\n };\n\n return {\n async addWorktree({ repositoryRoot, path, branch, baseRef }) {\n const result = await git(repositoryRoot, ['worktree', 'add', '-b', branch, path, baseRef], ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async removeWorktree({ repositoryRoot, path, force }) {\n const args = ['worktree', 'remove', ...(force ? ['--force'] : []), path];\n const result = await git(repositoryRoot, args, REMOVE_TIMEOUT_MS);\n if (result.code === 0) return;\n // A directory deleted behind git's back leaves an administrative entry\n // that makes a later `worktree add` at the same path refuse. Treating\n // \"already gone\" as success and pruning is what keeps that path reusable,\n // and it makes remove idempotent for a caller retrying after a crash.\n if (missingWorktree(result.stderr) && !fs.existsSync(path)) {\n await prune(repositoryRoot);\n return;\n }\n throw failure('worktree remove', result);\n },\n\n async deleteBranch({ repositoryRoot, branch }) {\n // -d, never -D: git refuses a branch that still holds unmerged commits,\n // and that refusal is the whole safety property. A rollback that could\n // throw away work someone committed in the worktree is worse than a\n // branch left behind.\n const result = await git(repositoryRoot, ['branch', '-d', branch], READ_TIMEOUT_MS);\n return result.code === 0;\n },\n pruneWorktrees: prune,\n\n async listWorktreePaths(repositoryRoot) {\n const result = await git(repositoryRoot, ['worktree', 'list', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .filter((line) => line.startsWith('worktree '))\n .map((line) => line.slice('worktree '.length).trim())\n .filter((line) => line !== '');\n },\n\n async dirtyFiles(path) {\n const result = await git(path, ['status', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .map((line) => line.slice(3).trim())\n .filter((line) => line !== '');\n },\n\n async repositoryRoot(cwd) {\n const result = await git(cwd, ['rev-parse', '--show-toplevel'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const root = result.stdout.trim();\n return root === '' ? undefined : root;\n },\n\n async currentBranch(cwd) {\n const result = await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const branch = result.stdout.trim();\n return branch === '' ? undefined : branch;\n },\n\n async mergeBranch({ repositoryRoot, branch, message }) {\n // --no-ff so the worktree's work stays identifiable as a unit after the\n // fact. A fast-forward would erase the fact that it was ever separate,\n // which is the one thing worth keeping about a worktree.\n const args = ['merge', '--no-ff', ...(message === undefined ? [] : ['-m', message]), branch];\n const result = await git(repositoryRoot, args, READ_TIMEOUT_MS);\n if (result.code === 0) return;\n // A conflicted merge leaves the parent mid-merge, which is a state the\n // person has to resolve; aborting for them would throw away the conflict\n // markers they need to see.\n throw failure('merge', result);\n },\n };\n}\n"],"mappings":"qEAcA,MAAM,EAAkB,IAmBxB,SAAS,EAAI,EAAa,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,WAAW,CAKrD,IAAM,EAAS,MAAM,EAAI,EAAgB,CAD3B,QAAS,UAAW,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,KAAM,CAAO,EAAI,CACzC,EAAG,CAAe,EAC1D,KAAO,OAAS,EAIpB,MAAM,EAAQ,QAAS,CAAM,CAC/B,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./dependencyInstall.cjs"),n=require("../hub/hubClient.cjs"),r=require("./repositoryIdentity.cjs"),i=require("../filesystem/paths.cjs"),a=require("../channel/worktreeChannel.cjs"),o=require("./worktreeRegistry.cjs"),s=require("../../services/worktreeNaming.cjs"),c=require("../../services/support/errors.cjs");let l=require("node:fs");l=e.__toESM(l,1);let u=require("node:crypto");function d(e){let{git:d}=e,f=e.createSession??n.createWorktreeSession,p=e.install??t.installDependencies,m=e.stopSession??n.stopWorktreeSession,h=e.isSessionLive??n.sessionIsLive,g=e.registryDir??i.hubRegistryDir(),_=e.now??(()=>new Date),v={alive:e=>h(g,e.sessionId),exists:e=>l.default.existsSync(e)},y=async t=>{let n=await d.repositoryRoot(t.cwd);if(n===void 0)throw new c.DoomGitExpectedError(`not_a_repository`,`${t.cwd} is not inside a git repository.`,!1,`Run this from a repository checkout.`);let r=o.createWorktreeRegistry(i.registryFile(n,e.homeDir));return{root:n,store:r,records:r.list()}},b=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw new c.DoomGitExpectedError(`worktree_not_found`,`No worktree with id ${t}.`,!1,`Call list to see the current ids.`);return n},x=(e,t,n)=>{if(t.parentSessionId!==e.sessionId&&h(g,t.parentSessionId))throw new c.DoomGitExpectedError(`worktree_not_owned`,`Worktree ${t.id} belongs to another session.`,!1,`Ask the session that created it to ${n} it, or close that session first.`)};return{async spawn(t,a){let{root:o,store:l,records:m}=await y(t),h=s.refuseSpawn({branch:a.branch,existing:m});if(h!==void 0)throw new c.DoomGitExpectedError(`worktree_exists`,h,!1,`Pick another branch name, or close it.`);let v=a.baseRef??await d.currentBranch(o)??`HEAD`,b=r.shortId((0,u.randomUUID)()),x=s.worktreeDirectory({worktreesRoot:i.worktreesRoot(e.homeDir),repositoryLabel:r.repositoryLabel(o),repositoryId:r.repositoryId(o),branch:a.branch,shortId:b});await d.addWorktree({repositoryRoot:o,path:x,branch:a.branch,baseRef:v});let S=await p(x);if(S.kind===`failed`)throw await d.removeWorktree({repositoryRoot:o,path:x,force:!0}).catch(()=>void 0),new c.DoomGitExpectedError(`install_failed`,`${S.command} install failed in the new worktree (exit ${String(S.code??`unknown`)}).`,!0,`Run the install by hand in the repository to see what it reports, then try again.`);let C;try{C=await f({cwd:x,name:a.name??a.branch,parentSessionId:t.sessionId,registryDir:g})}catch(e){throw await d.removeWorktree({repositoryRoot:o,path:x,force:!0}).catch(()=>void 0),e instanceof n.HubUnavailableError?new c.DoomGitExpectedError(`hub_unavailable`,e.message,!0,`Start the cockpit and try again.`):e}let w={version:1,id:b,branch:a.branch,baseRef:v,path:x,repositoryRoot:o,sessionId:C,parentSessionId:t.sessionId,status:`running`,createdAt:_().toISOString()};return l.replace([...m,w]),w},async close(e,t,n){let{root:r,store:i,records:a}=await y(e),o=b(a,t);x(e,o,`close`);let u=l.default.existsSync(o.path)?await d.dirtyFiles(o.path):[],f=s.refuseClose({record:o,dirtyFiles:u,force:n});if(f!==void 0)throw new c.DoomGitExpectedError(`worktree_dirty`,f,!1,`Commit the work, or pass force: true.`);return await m(g,o.sessionId),await d.removeWorktree({repositoryRoot:r,path:o.path,force:n}),i.replace(a.filter(e=>e.id!==t)),o},async list(e){let{store:t,records:n}=await y(e),r=s.reconcile(n,v);return r.changed.length>0&&t.replace(r.records),r.records},async status(e,t){let{records:n}=await y(e),r=b(n,t);return{record:r,dirtyFiles:l.default.existsSync(r.path)?await d.dirtyFiles(r.path):[]}},async merge(e,t,n){let{root:r,records:i}=await y(e),a=b(i,t);x(e,a,`merge`);let o=await d.dirtyFiles(r);if(o.length>0)throw new c.DoomGitExpectedError(`worktree_dirty`,`The parent checkout has ${String(o.length)} uncommitted file(s): ${o.slice(0,10).join(`, `)}.`,!1,`Commit or stash the parent checkout first.`);return await d.mergeBranch({repositoryRoot:r,branch:a.branch,...n===void 0?{}:{message:n}}),a},async send(t,n,r){let{records:o}=await y(t),s=b(o,n),c=t.sessionId===s.sessionId?`parent`:`child`;a.createWorktreeChannel(i.channelRoot(s.id,e.homeDir)).send(c,r)},async messages(t,n){let{records:r}=await y(t),o=b(r,n),s=a.createWorktreeChannel(i.channelRoot(o.id,e.homeDir));s.sweep();let c=t.sessionId===o.sessionId?`child`:`parent`;return s.receive(c)},async prune(t,n){let{root:r,store:a,records:o}=await y(t),c=s.reconcile(o,v),u=await d.listWorktreePaths(r),f=new Map;for(let e of c.records)e.status===`orphaned`&&l.default.existsSync(e.path)&&f.set(e.path,await d.dirtyFiles(e.path));let p=s.planPrune({records:c.records,gitPaths:u,worktreesRoot:i.worktreesRoot(e.homeDir),dirtyByPath:f});if(n)return a.replace(c.records),p;for(let e of p.remove)await d.removeWorktree({repositoryRoot:r,path:e.path,force:!1});let m=new Set([...p.remove,...p.forget].map(e=>e.id));return a.replace(c.records.filter(e=>!m.has(e.id))),p}}}exports.createWorktreeOperations=d;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./compositionMirror.cjs"),n=require("../hub/hubClient.cjs"),r=require("./repositoryIdentity.cjs"),i=require("../filesystem/paths.cjs"),a=require("../channel/worktreeChannel.cjs"),o=require("./worktreeRegistry.cjs"),s=require("../../services/worktreeNaming.cjs"),c=require("../../services/support/errors.cjs");let l=require("node:fs");l=e.__toESM(l,1);let u=require("node:crypto");function d(e){let{git:d}=e,f=e.createSession??n.createWorktreeSession,p=e.stopSession??n.stopWorktreeSession,m=e.mirror??t.mirrorComposition,h=e.isSessionLive??n.sessionIsLive,g=e.registryDir??i.hubRegistryDir(),_=e.now??(()=>new Date),v={alive:e=>h(g,e.sessionId),exists:e=>l.default.existsSync(e)},y=async t=>{let n=await d.repositoryRoot(t.cwd);if(n===void 0)throw new c.DoomGitExpectedError(`not_a_repository`,`${t.cwd} is not inside a git repository.`,!1,`Run this from a repository checkout.`);let r=o.createWorktreeRegistry(i.registryFile(n,e.homeDir));return{root:n,store:r,records:r.list()}},b=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw new c.DoomGitExpectedError(`worktree_not_found`,`No worktree with id ${t}.`,!1,`Call list to see the current ids.`);return n},x=(e,t,n)=>{if(t.parentSessionId!==e.sessionId&&h(g,t.parentSessionId))throw new c.DoomGitExpectedError(`worktree_not_owned`,`Worktree ${t.id} belongs to another session.`,!1,`Ask the session that created it to ${n} it, or close that session first.`)};return{async spawn(t,a,o){let{root:l,store:h,records:v}=await y(t),b=s.refuseSpawn({branch:a.branch,existing:v});if(b!==void 0)throw new c.DoomGitExpectedError(`worktree_exists`,b,!1,`Pick another branch name, or close it.`);let x=a.baseRef??await d.currentBranch(l)??`HEAD`,S=r.shortId((0,u.randomUUID)()),C=s.worktreeDirectory({worktreesRoot:i.worktreesRoot(e.homeDir),repositoryLabel:r.repositoryLabel(l),repositoryId:r.repositoryId(l),branch:a.branch,shortId:S}),w=()=>o?.signal?.aborted===!0,T=async()=>(await d.removeWorktree({repositoryRoot:l,path:C,force:!0}).catch(()=>void 0),await d.deleteBranch({repositoryRoot:l,branch:a.branch}).catch(()=>!1)?``:` The branch ${a.branch} has work on it and was kept.`);if(o?.onProgress?.(`creating branch ${a.branch}\u2026`),await d.addWorktree({repositoryRoot:l,path:C,branch:a.branch,baseRef:x}),w()){let e=await T();throw new c.DoomGitExpectedError(`spawn_cancelled`,`Cancelled before the session started.${e}`,!1,`The worktree was removed; run it again when you are ready.`)}o?.onProgress?.(`mirroring build output…`),m(l,C),o?.onProgress?.(`starting session…`);let E;try{E=await f({cwd:C,name:a.name??a.branch,parentSessionId:t.sessionId,registryDir:g,...o?.signal===void 0?{}:{signal:o.signal}})}catch(e){let t=await T();throw w()?new c.DoomGitExpectedError(`spawn_cancelled`,`Cancelled while the session was starting.${t}`,!1,`The worktree was removed; run it again when you are ready.`):e instanceof n.HubUnavailableError?new c.DoomGitExpectedError(`hub_unavailable`,`${e.message}${t}`,!0,`Start the cockpit and try again.`):e}let D={version:1,id:S,branch:a.branch,baseRef:x,path:C,repositoryRoot:l,sessionId:E,parentSessionId:t.sessionId,status:`running`,createdAt:_().toISOString()};try{h.replace([...v,D])}catch(e){await p(g,E).catch(()=>void 0);let t=await T();throw new c.DoomGitExpectedError(`registry_write_failed`,`The worktree was created but the registry could not be written (${e.message}).${t}`,!0,`Check the registry file for permissions or free space, then try again.`)}return D},async close(e,t,n){let{root:r,store:i,records:a}=await y(e),o=b(a,t);x(e,o,`close`);let u=l.default.existsSync(o.path)?await d.dirtyFiles(o.path):[],f=s.refuseClose({record:o,dirtyFiles:u,force:n});if(f!==void 0)throw new c.DoomGitExpectedError(`worktree_dirty`,f,!1,`Commit the work, or pass force: true.`);return await p(g,o.sessionId),await d.removeWorktree({repositoryRoot:r,path:o.path,force:n}),i.replace(a.filter(e=>e.id!==t)),o},async list(e){let{store:t,records:n}=await y(e),r=s.reconcile(n,v);return r.changed.length>0&&t.replace(r.records),r.records},async status(e,t){let{records:n}=await y(e),r=b(n,t);return{record:r,dirtyFiles:l.default.existsSync(r.path)?await d.dirtyFiles(r.path):[]}},async merge(e,t,n){let{root:r,records:i}=await y(e),a=b(i,t);x(e,a,`merge`);let o=await d.dirtyFiles(r);if(o.length>0)throw new c.DoomGitExpectedError(`worktree_dirty`,`The parent checkout has ${String(o.length)} uncommitted file(s): ${o.slice(0,10).join(`, `)}.`,!1,`Commit or stash the parent checkout first.`);return await d.mergeBranch({repositoryRoot:r,branch:a.branch,...n===void 0?{}:{message:n}}),a},async send(t,n,r){let{records:o}=await y(t),s=b(o,n),c=t.sessionId===s.sessionId?`parent`:`child`;a.createWorktreeChannel(i.channelRoot(s.id,e.homeDir)).send(c,r)},async messages(t,n){let{records:r}=await y(t),o=b(r,n),s=a.createWorktreeChannel(i.channelRoot(o.id,e.homeDir));s.sweep();let c=t.sessionId===o.sessionId?`child`:`parent`;return s.receive(c)},async prune(t,n){let{root:r,store:a,records:o}=await y(t),c=s.reconcile(o,v),u=await d.listWorktreePaths(r),f=new Map;for(let e of c.records)e.status===`orphaned`&&l.default.existsSync(e.path)&&f.set(e.path,await d.dirtyFiles(e.path));let p=s.planPrune({records:c.records,gitPaths:u,worktreesRoot:i.worktreesRoot(e.homeDir),dirtyByPath:f});if(n)return a.replace(c.records),p;for(let e of p.remove)await d.removeWorktree({repositoryRoot:r,path:e.path,force:!1});for(let e of[...p.remove,...p.forget])await d.deleteBranch({repositoryRoot:r,branch:e.branch}).catch(()=>!1)||p.keptBranches.push(e.branch);let m=new Set([...p.remove,...p.forget].map(e=>e.id));return a.replace(c.records.filter(e=>!m.has(e.id))),p}}}exports.createWorktreeOperations=d;
2
2
  //# sourceMappingURL=worktreeOperations.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeOperations.cjs","names":["createWorktreeSession","installDependencies","stopWorktreeSession","sessionIsLive","hubRegistryDir","fs","DoomGitExpectedError","createWorktreeRegistry","registryFile","require","refuseSpawn","shortId","randomUUID","worktreeDirectory","worktreesRoot","repositoryLabel","repositoryId","HubUnavailableError","refuseClose","reconcile","channelRoot","createWorktreeChannel","planPrune"],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { installDependencies } from './dependencyInstall.ts';\nimport { createWorktreeSession, HubUnavailableError, sessionIsLive, stopWorktreeSession } from '../hub/hubClient.ts';\nimport { channelRoot, hubRegistryDir, registryFile, worktreesRoot } from '../filesystem/paths.ts';\nimport { repositoryId, repositoryLabel, shortId } from './repositoryIdentity.ts';\nimport { createWorktreeChannel } from '../channel/worktreeChannel.ts';\nimport type { ChannelMessage, ChannelParty } from '../channel/worktreeChannel.ts';\nimport { createWorktreeRegistry } from './worktreeRegistry.ts';\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry.ts';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry.ts';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../../services/worktreeNaming.ts';\nimport { DoomGitExpectedError } from '../../services/support/errors.ts';\n\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: string;\n name?: string;\n}\n\nexport interface WorktreeOperations {\n spawn(context: WorktreeContext, request: SpawnWorktreeRequest): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;\n list(context: WorktreeContext): Promise<WorktreeRecord[]>;\n status(context: WorktreeContext, id: string): Promise<{ record: WorktreeRecord; dirtyFiles: string[] }>;\n merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;\n prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;\n send(context: WorktreeContext, id: string, message: string): Promise<void>;\n messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** Injected so tests never reach the network. */\n createSession?: typeof createWorktreeSession;\n /** Injected so tests never run a package manager. */\n install?: typeof installDependencies;\n stopSession?: typeof stopWorktreeSession;\n isSessionLive?: typeof sessionIsLive;\n homeDir?: string;\n registryDir?: string;\n /** Injected so a record's createdAt is reproducible in a test. */\n now?: () => Date;\n}\n\nexport function createWorktreeOperations(deps: WorktreeOperationsDeps): WorktreeOperations {\n const { git } = deps;\n const createSession = deps.createSession ?? createWorktreeSession;\n const install = deps.install ?? installDependencies;\n const stopSession = deps.stopSession ?? stopWorktreeSession;\n const isSessionLive = deps.isSessionLive ?? sessionIsLive;\n const registryDir = deps.registryDir ?? hubRegistryDir();\n const now = deps.now ?? (() => new Date());\n const probe = {\n alive: (record: WorktreeRecord) => isSessionLive(registryDir, record.sessionId),\n exists: (path: string) => fs.existsSync(path),\n };\n\n /**\n * Everything an action needs about the repository it is acting on.\n *\n * Resolved per call rather than cached: a session's cwd is stable, but the\n * registry file is shared with the cockpit panel and another process may\n * have written it since the last call.\n */\n const resolve = async (context: WorktreeContext) => {\n const root = await git.repositoryRoot(context.cwd);\n if (root === undefined) {\n throw new DoomGitExpectedError(\n 'not_a_repository',\n `${context.cwd} is not inside a git repository.`,\n false,\n 'Run this from a repository checkout.',\n );\n }\n const store = createWorktreeRegistry(registryFile(root, deps.homeDir));\n return { root, store, records: store.list() };\n };\n\n const require = (records: readonly WorktreeRecord[], id: string): WorktreeRecord => {\n const record = records.find((entry) => entry.id === id);\n if (record === undefined) {\n throw new DoomGitExpectedError(\n 'worktree_not_found',\n `No worktree with id ${id}.`,\n false,\n 'Call list to see the current ids.',\n );\n }\n return record;\n };\n\n /**\n * Refuses to destroy or merge a worktree another live session is using.\n *\n * `parentSessionId` records who asked for the worktree. Two sessions in one\n * checkout share this registry, so without the check either could close the\n * other's work in progress by id.\n *\n * Once that session is gone there is no owner left to protect, and refusing\n * would strand the worktree: nothing else could ever close it.\n */\n const requireOwner = (context: WorktreeContext, record: WorktreeRecord, action: string): void => {\n if (record.parentSessionId === context.sessionId) return;\n if (!isSessionLive(registryDir, record.parentSessionId)) return;\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n `Ask the session that created it to ${action} it, or close that session first.`,\n );\n };\n\n return {\n async spawn(context, request) {\n const { root, store, records } = await resolve(context);\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const baseRef = request.baseRef ?? (await git.currentBranch(root)) ?? 'HEAD';\n const id = shortId(randomUUID());\n const path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n\n await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\n\n // Before the session, not after. The session resolves this repository's\n // composition, and every workspace package path in it points at a\n // directory that exists only once dependencies are linked. Starting the\n // session first makes it fall back to the global bundle and quietly lose\n // the repository's own packages.\n const installed = await install(path);\n if (installed.kind === 'failed') {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n throw new DoomGitExpectedError(\n 'install_failed',\n `${installed.command} install failed in the new worktree (exit ${String(installed.code ?? 'unknown')}).`,\n true,\n 'Run the install by hand in the repository to see what it reports, then try again.',\n );\n }\n\n // The worktree exists from here on, so every later failure has to leave\n // it removed or recorded. An unrecorded directory on disk is the one\n // outcome with no way back: nothing would ever list it again.\n let sessionId: string;\n try {\n sessionId = await createSession({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n registryDir,\n });\n } catch (error) {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n if (error instanceof HubUnavailableError) {\n throw new DoomGitExpectedError('hub_unavailable', error.message, true, 'Start the cockpit and try again.');\n }\n throw error;\n }\n\n const record: WorktreeRecord = {\n version: WORKTREE_RECORD_VERSION,\n id,\n branch: request.branch,\n baseRef,\n path,\n repositoryRoot: root,\n sessionId,\n parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n store.replace([...records, record]);\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_dirty', refusal, false, 'Commit the work, or pass force: true.');\n }\n // The session is stopped before the directory goes. Removing a checkout\n // while a process still holds files open in it is how a half-removed\n // worktree and a stale git administrative entry are made.\n await stopSession(registryDir, record.sessionId);\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n store.replace(records.filter((entry) => entry.id !== id));\n return record;\n },\n\n async list(context) {\n const { store, records } = await resolve(context);\n const outcome = reconcile(records, probe);\n if (outcome.changed.length > 0) store.replace(outcome.records);\n return outcome.records;\n },\n\n async status(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n return { record, dirtyFiles };\n },\n\n async merge(context, id, message) {\n const { root, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'merge');\n // The merge lands in the parent, so the parent is what must be clean. A\n // dirty parent would mix the person's in-flight edits into a merge commit\n // they did not intend to make.\n const parentDirty = await git.dirtyFiles(root);\n if (parentDirty.length > 0) {\n throw new DoomGitExpectedError(\n 'worktree_dirty',\n `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(', ')}.`,\n false,\n 'Commit or stash the parent checkout first.',\n );\n }\n await git.mergeBranch({\n repositoryRoot: root,\n branch: record.branch,\n ...(message === undefined ? {} : { message }),\n });\n return record;\n },\n\n /**\n * Which side of the channel the caller is.\n *\n * A worktree session is the child of the record it belongs to, and the\n * parent for everything else. Deciding from the session id rather than a\n * flag means neither side can address itself by mistake.\n */\n async send(context, id, message) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const party: ChannelParty = context.sessionId === record.sessionId ? 'parent' : 'child';\n createWorktreeChannel(channelRoot(record.id, deps.homeDir)).send(party, message);\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const channel = createWorktreeChannel(channelRoot(record.id, deps.homeDir));\n channel.sweep();\n const party: ChannelParty = context.sessionId === record.sessionId ? 'child' : 'parent';\n return channel.receive(party);\n },\n\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(record.path)) {\n dirtyByPath.set(record.path, await git.dirtyFiles(record.path));\n }\n }\n const plan = planPrune({\n records: reconciled.records,\n gitPaths,\n worktreesRoot: worktreesRoot(deps.homeDir),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));\n return plan;\n },\n };\n}\n"],"mappings":"+bAoDA,SAAgB,EAAyB,EAAkD,CACzF,GAAM,CAAE,OAAQ,EACV,EAAgB,EAAK,eAAiBA,EAAAA,sBACtC,EAAU,EAAK,SAAWC,EAAAA,oBAC1B,EAAc,EAAK,aAAeC,EAAAA,oBAClC,EAAgB,EAAK,eAAiBC,EAAAA,cACtC,EAAc,EAAK,aAAeC,EAAAA,eAAe,EACjD,EAAM,EAAK,UAAc,IAAI,MAC7B,EAAQ,CACZ,MAAQ,GAA2B,EAAc,EAAa,EAAO,SAAS,EAC9E,OAAS,GAAiBC,EAAAA,QAAG,WAAW,CAAI,CAC9C,EASM,EAAU,KAAO,IAA6B,CAClD,IAAM,EAAO,MAAM,EAAI,eAAe,EAAQ,GAAG,EACjD,GAAI,IAAS,IAAA,GACX,MAAM,IAAIC,EAAAA,qBACR,mBACA,GAAG,EAAQ,IAAI,kCACf,GACA,sCACF,EAEF,IAAM,EAAQC,EAAAA,uBAAuBC,EAAAA,aAAa,EAAM,EAAK,OAAO,CAAC,EACrE,MAAO,CAAE,OAAM,QAAO,QAAS,EAAM,KAAK,CAAE,CAC9C,EAEMC,GAAW,EAAoC,IAA+B,CAClF,IAAM,EAAS,EAAQ,KAAM,GAAU,EAAM,KAAO,CAAE,EACtD,GAAI,IAAW,IAAA,GACb,MAAM,IAAIH,EAAAA,qBACR,qBACA,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,CAAC,EAC1E,EAAQ,MAAM,EACd,IAAM,EAAsB,EAAQ,YAAc,EAAO,UAAY,QAAU,SAC/E,OAAO,EAAQ,QAAQ,CAAK,CAC9B,EAEA,MAAM,MAAM,EAAS,EAAQ,CAC3B,GAAM,CAAE,OAAM,QAAO,WAAY,MAAM,EAAQ,CAAO,EAChD,EAAaD,EAAAA,UAAU,EAAS,CAAK,EACrC,EAAW,MAAM,EAAI,kBAAkB,CAAI,EAC3C,EAAc,IAAI,IACxB,IAAK,IAAM,KAAU,EAAW,QAC1B,EAAO,SAAW,YAAcd,EAAAA,QAAG,WAAW,EAAO,IAAI,GAC3D,EAAY,IAAI,EAAO,KAAM,MAAM,EAAI,WAAW,EAAO,IAAI,CAAC,EAGlE,IAAM,EAAOiB,EAAAA,UAAU,CACrB,QAAS,EAAW,QACpB,WACA,cAAeR,EAAAA,cAAc,EAAK,OAAO,EACzC,aACF,CAAC,EACD,GAAI,EAEF,OADA,EAAM,QAAQ,EAAW,OAAO,EACzB,EAET,IAAK,IAAM,KAAU,EAAK,OACxB,MAAM,EAAI,eAAe,CAAE,eAAgB,EAAM,KAAM,EAAO,KAAM,MAAO,EAAM,CAAC,EAEpF,IAAM,EAAU,IAAI,IAAI,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,CAAC,CAAC,IAAK,GAAW,EAAO,EAAE,CAAC,EAEnF,OADA,EAAM,QAAQ,EAAW,QAAQ,OAAQ,GAAW,CAAC,EAAQ,IAAI,EAAO,EAAE,CAAC,CAAC,EACrE,CACT,CACF,CACF"}
1
+ {"version":3,"file":"worktreeOperations.cjs","names":["createWorktreeSession","stopWorktreeSession","mirrorComposition","sessionIsLive","hubRegistryDir","fs","DoomGitExpectedError","createWorktreeRegistry","registryFile","require","refuseSpawn","shortId","randomUUID","worktreeDirectory","worktreesRoot","repositoryLabel","repositoryId","HubUnavailableError","refuseClose","reconcile","channelRoot","createWorktreeChannel","planPrune"],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { mirrorComposition } from './compositionMirror.ts';\nimport { createWorktreeSession, HubUnavailableError, sessionIsLive, stopWorktreeSession } from '../hub/hubClient.ts';\nimport { channelRoot, hubRegistryDir, registryFile, worktreesRoot } from '../filesystem/paths.ts';\nimport { repositoryId, repositoryLabel, shortId } from './repositoryIdentity.ts';\nimport { createWorktreeChannel } from '../channel/worktreeChannel.ts';\nimport type { ChannelMessage, ChannelParty } from '../channel/worktreeChannel.ts';\nimport { createWorktreeRegistry } from './worktreeRegistry.ts';\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry.ts';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry.ts';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../../services/worktreeNaming.ts';\nimport { DoomGitExpectedError } from '../../services/support/errors.ts';\n\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: string;\n name?: string;\n}\n\nexport interface SpawnOptions {\n /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */\n signal?: AbortSignal;\n /** Phase labels, for a caller that can show them while the work runs. */\n onProgress?: (label: string) => void;\n}\n\nexport interface WorktreeOperations {\n spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;\n list(context: WorktreeContext): Promise<WorktreeRecord[]>;\n status(context: WorktreeContext, id: string): Promise<{ record: WorktreeRecord; dirtyFiles: string[] }>;\n merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;\n prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;\n send(context: WorktreeContext, id: string, message: string): Promise<void>;\n messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** Injected so tests never reach the network. */\n createSession?: typeof createWorktreeSession;\n stopSession?: typeof stopWorktreeSession;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n isSessionLive?: typeof sessionIsLive;\n homeDir?: string;\n registryDir?: string;\n /** Injected so a record's createdAt is reproducible in a test. */\n now?: () => Date;\n}\n\nexport function createWorktreeOperations(deps: WorktreeOperationsDeps): WorktreeOperations {\n const { git } = deps;\n const createSession = deps.createSession ?? createWorktreeSession;\n const stopSession = deps.stopSession ?? stopWorktreeSession;\n const mirror = deps.mirror ?? mirrorComposition;\n const isSessionLive = deps.isSessionLive ?? sessionIsLive;\n const registryDir = deps.registryDir ?? hubRegistryDir();\n const now = deps.now ?? (() => new Date());\n const probe = {\n alive: (record: WorktreeRecord) => isSessionLive(registryDir, record.sessionId),\n exists: (path: string) => fs.existsSync(path),\n };\n\n /**\n * Everything an action needs about the repository it is acting on.\n *\n * Resolved per call rather than cached: a session's cwd is stable, but the\n * registry file is shared with the cockpit panel and another process may\n * have written it since the last call.\n */\n const resolve = async (context: WorktreeContext) => {\n const root = await git.repositoryRoot(context.cwd);\n if (root === undefined) {\n throw new DoomGitExpectedError(\n 'not_a_repository',\n `${context.cwd} is not inside a git repository.`,\n false,\n 'Run this from a repository checkout.',\n );\n }\n const store = createWorktreeRegistry(registryFile(root, deps.homeDir));\n return { root, store, records: store.list() };\n };\n\n const require = (records: readonly WorktreeRecord[], id: string): WorktreeRecord => {\n const record = records.find((entry) => entry.id === id);\n if (record === undefined) {\n throw new DoomGitExpectedError(\n 'worktree_not_found',\n `No worktree with id ${id}.`,\n false,\n 'Call list to see the current ids.',\n );\n }\n return record;\n };\n\n /**\n * Refuses to destroy or merge a worktree another live session is using.\n *\n * `parentSessionId` records who asked for the worktree. Two sessions in one\n * checkout share this registry, so without the check either could close the\n * other's work in progress by id.\n *\n * Once that session is gone there is no owner left to protect, and refusing\n * would strand the worktree: nothing else could ever close it.\n */\n const requireOwner = (context: WorktreeContext, record: WorktreeRecord, action: string): void => {\n if (record.parentSessionId === context.sessionId) return;\n if (!isSessionLive(registryDir, record.parentSessionId)) return;\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n `Ask the session that created it to ${action} it, or close that session first.`,\n );\n };\n\n return {\n async spawn(context, request, options) {\n const { root, store, records } = await resolve(context);\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const baseRef = request.baseRef ?? (await git.currentBranch(root)) ?? 'HEAD';\n const id = shortId(randomUUID());\n const path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n\n // The worktree and the branch are made by one command, so they are undone\n // by one too. `worktree remove` leaves the branch behind, and a branch\n // nobody asked for is what a failed spawn used to leave on the floor.\n const cancelled = (): boolean => options?.signal?.aborted === true;\n const rollback = async (): Promise<string> => {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: request.branch }).catch(() => false);\n return deleted ? '' : ` The branch ${request.branch} has work on it and was kept.`;\n };\n\n options?.onProgress?.(`creating branch ${request.branch}\\u2026`);\n await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\n\n // Checked here rather than only inside the session call: this is the\n // point where a checkout exists that nothing has recorded yet, which is\n // exactly the state an interrupted spawn used to leave behind.\n if (cancelled()) {\n const kept = await rollback();\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n `Cancelled before the session started.${kept}`,\n false,\n 'The worktree was removed; run it again when you are ready.',\n );\n }\n\n // Before the session, because the session composes the extensions this\n // repository's config names and those live in build output git does not\n // track. A worktree without it starts and dies on the first package it\n // cannot resolve. Nothing here can fail the spawn: a repository with no\n // build output to mirror simply has none.\n options?.onProgress?.('mirroring build output\\u2026');\n mirror(root, path);\n\n // The worktree exists from here on, so every later failure has to leave\n // it removed or recorded. An unrecorded directory on disk is the one\n // outcome with no way back: nothing would ever list it again.\n options?.onProgress?.('starting session\\u2026');\n let sessionId: string;\n try {\n sessionId = await createSession({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n registryDir,\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n } catch (error) {\n const kept = await rollback();\n if (cancelled()) {\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n `Cancelled while the session was starting.${kept}`,\n false,\n 'The worktree was removed; run it again when you are ready.',\n );\n }\n if (error instanceof HubUnavailableError) {\n throw new DoomGitExpectedError(\n 'hub_unavailable',\n `${error.message}${kept}`,\n true,\n 'Start the cockpit and try again.',\n );\n }\n throw error;\n }\n\n const record: WorktreeRecord = {\n version: WORKTREE_RECORD_VERSION,\n id,\n branch: request.branch,\n baseRef,\n path,\n repositoryRoot: root,\n sessionId,\n parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n try {\n store.replace([...records, record]);\n } catch (error) {\n // A live session with no record is the worst outcome available here:\n // it runs, and no id anything can name points at it. The session goes\n // back too, rather than being left for someone to find by hand.\n await stopSession(registryDir, sessionId).catch(() => undefined);\n const kept = await rollback();\n throw new DoomGitExpectedError(\n 'registry_write_failed',\n `The worktree was created but the registry could not be written (${(error as Error).message}).${kept}`,\n true,\n 'Check the registry file for permissions or free space, then try again.',\n );\n }\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_dirty', refusal, false, 'Commit the work, or pass force: true.');\n }\n // The session is stopped before the directory goes. Removing a checkout\n // while a process still holds files open in it is how a half-removed\n // worktree and a stale git administrative entry are made.\n await stopSession(registryDir, record.sessionId);\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n store.replace(records.filter((entry) => entry.id !== id));\n return record;\n },\n\n async list(context) {\n const { store, records } = await resolve(context);\n const outcome = reconcile(records, probe);\n if (outcome.changed.length > 0) store.replace(outcome.records);\n return outcome.records;\n },\n\n async status(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n return { record, dirtyFiles };\n },\n\n async merge(context, id, message) {\n const { root, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'merge');\n // The merge lands in the parent, so the parent is what must be clean. A\n // dirty parent would mix the person's in-flight edits into a merge commit\n // they did not intend to make.\n const parentDirty = await git.dirtyFiles(root);\n if (parentDirty.length > 0) {\n throw new DoomGitExpectedError(\n 'worktree_dirty',\n `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(', ')}.`,\n false,\n 'Commit or stash the parent checkout first.',\n );\n }\n await git.mergeBranch({\n repositoryRoot: root,\n branch: record.branch,\n ...(message === undefined ? {} : { message }),\n });\n return record;\n },\n\n /**\n * Which side of the channel the caller is.\n *\n * A worktree session is the child of the record it belongs to, and the\n * parent for everything else. Deciding from the session id rather than a\n * flag means neither side can address itself by mistake.\n */\n async send(context, id, message) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const party: ChannelParty = context.sessionId === record.sessionId ? 'parent' : 'child';\n createWorktreeChannel(channelRoot(record.id, deps.homeDir)).send(party, message);\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const channel = createWorktreeChannel(channelRoot(record.id, deps.homeDir));\n channel.sweep();\n const party: ChannelParty = context.sessionId === record.sessionId ? 'child' : 'parent';\n return channel.receive(party);\n },\n\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(record.path)) {\n dirtyByPath.set(record.path, await git.dirtyFiles(record.path));\n }\n }\n const plan = planPrune({\n records: reconciled.records,\n gitPaths,\n worktreesRoot: worktreesRoot(deps.homeDir),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n }\n // The checkout goes, so the branch it was made for goes with it. Safe\n // delete only: git keeps anything holding commits, and the plan says\n // which ones it kept rather than leaving the reader to notice later.\n for (const record of [...plan.remove, ...plan.forget]) {\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: record.branch }).catch(() => false);\n if (!deleted) plan.keptBranches.push(record.branch);\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));\n return plan;\n },\n };\n}\n"],"mappings":"+bA2DA,SAAgB,EAAyB,EAAkD,CACzF,GAAM,CAAE,OAAQ,EACV,EAAgB,EAAK,eAAiBA,EAAAA,sBACtC,EAAc,EAAK,aAAeC,EAAAA,oBAClC,EAAS,EAAK,QAAUC,EAAAA,kBACxB,EAAgB,EAAK,eAAiBC,EAAAA,cACtC,EAAc,EAAK,aAAeC,EAAAA,eAAe,EACjD,EAAM,EAAK,UAAc,IAAI,MAC7B,EAAQ,CACZ,MAAQ,GAA2B,EAAc,EAAa,EAAO,SAAS,EAC9E,OAAS,GAAiBC,EAAAA,QAAG,WAAW,CAAI,CAC9C,EASM,EAAU,KAAO,IAA6B,CAClD,IAAM,EAAO,MAAM,EAAI,eAAe,EAAQ,GAAG,EACjD,GAAI,IAAS,IAAA,GACX,MAAM,IAAIC,EAAAA,qBACR,mBACA,GAAG,EAAQ,IAAI,kCACf,GACA,sC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AAO,KAAM,MAAM,EAAI,WAAW,EAAO,IAAI,CAAC,EAGlE,IAAM,EAAOiB,EAAAA,UAAU,CACrB,QAAS,EAAW,QACpB,WACA,cAAeR,EAAAA,cAAc,EAAK,OAAO,EACzC,aACF,CAAC,EACD,GAAI,EAEF,OADA,EAAM,QAAQ,EAAW,OAAO,EACzB,EAET,IAAK,IAAM,KAAU,EAAK,OACxB,MAAM,EAAI,eAAe,CAAE,eAAgB,EAAM,KAAM,EAAO,KAAM,MAAO,EAAM,CAAC,EAKpF,IAAK,IAAM,IAAU,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,EAE7C,MADiB,EAAI,aAAa,CAAE,eAAgB,EAAM,OAAQ,EAAO,MAAO,CAAC,CAAC,CAAC,UAAY,EAAK,GAC3F,EAAK,aAAa,KAAK,EAAO,MAAM,EAEpD,IAAM,EAAU,IAAI,IAAI,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,CAAC,CAAC,IAAK,GAAW,EAAO,EAAE,CAAC,EAEnF,OADA,EAAM,QAAQ,EAAW,QAAQ,OAAQ,GAAW,CAAC,EAAQ,IAAI,EAAO,EAAE,CAAC,CAAC,EACrE,CACT,CACF,CACF"}
@@ -14,8 +14,14 @@ interface SpawnWorktreeRequest {
14
14
  baseRef?: string;
15
15
  name?: string;
16
16
  }
17
+ interface SpawnOptions {
18
+ /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */
19
+ signal?: AbortSignal;
20
+ /** Phase labels, for a caller that can show them while the work runs. */
21
+ onProgress?: (label: string) => void;
22
+ }
17
23
  interface WorktreeOperations {
18
- spawn(context: WorktreeContext, request: SpawnWorktreeRequest): Promise<WorktreeRecord>;
24
+ spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;
19
25
  close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;
20
26
  list(context: WorktreeContext): Promise<WorktreeRecord[]>;
21
27
  status(context: WorktreeContext, id: string): Promise<{
@@ -28,5 +34,5 @@ interface WorktreeOperations {
28
34
  messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;
29
35
  }
30
36
  //#endregion
31
- export { SpawnWorktreeRequest, WorktreeContext, WorktreeOperations };
37
+ export { SpawnOptions, SpawnWorktreeRequest, WorktreeContext, WorktreeOperations };
32
38
  //# sourceMappingURL=worktreeOperations.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeOperations.d.cts","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"mappings":";;;;;UAciB;;EAEf;;EAEA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,MAAM,SAAS,iBAAiB,SAAS,uBAAuB,QAAQ;EACxE,MAAM,SAAS,iBAAiB,YAAY,iBAAiB,QAAQ;EACrE,KAAK,SAAS,kBAAkB,QAAQ;EACxC,OAAO,SAAS,iBAAiB,aAAa;IAAU,QAAQ;IAAgB;;EAChF,MAAM,SAAS,iBAAiB,YAAY,mBAAmB,QAAQ;EACvE,MAAM,SAAS,iBAAiB,kBAAkB,QAAQ,kBAAkB;EAC5E,KAAK,SAAS,iBAAiB,YAAY,kBAAkB;EAC7D,SAAS,SAAS,iBAAiB,aAAa,QAAQ"}
1
+ {"version":3,"file":"worktreeOperations.d.cts","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"mappings":";;;;;UAciB;;EAEf;;EAEA;;UAGe;EACf;EACA;EACA;;UAGe;;EAEf,SAAS;;EAET,cAAc;;UAGC;EACf,MAAM,SAAS,iBAAiB,SAAS,sBAAsB,UAAU,eAAe,QAAQ;EAChG,MAAM,SAAS,iBAAiB,YAAY,iBAAiB,QAAQ;EACrE,KAAK,SAAS,kBAAkB,QAAQ;EACxC,OAAO,SAAS,iBAAiB,aAAa;IAAU,QAAQ;IAAgB;;EAChF,MAAM,SAAS,iBAAiB,YAAY,mBAAmB,QAAQ;EACvE,MAAM,SAAS,iBAAiB,kBAAkB,QAAQ,kBAAkB;EAC5E,KAAK,SAAS,iBAAiB,YAAY,kBAAkB;EAC7D,SAAS,SAAS,iBAAiB,aAAa,QAAQ"}
@@ -14,8 +14,14 @@ interface SpawnWorktreeRequest {
14
14
  baseRef?: string;
15
15
  name?: string;
16
16
  }
17
+ interface SpawnOptions {
18
+ /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */
19
+ signal?: AbortSignal;
20
+ /** Phase labels, for a caller that can show them while the work runs. */
21
+ onProgress?: (label: string) => void;
22
+ }
17
23
  interface WorktreeOperations {
18
- spawn(context: WorktreeContext, request: SpawnWorktreeRequest): Promise<WorktreeRecord>;
24
+ spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;
19
25
  close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;
20
26
  list(context: WorktreeContext): Promise<WorktreeRecord[]>;
21
27
  status(context: WorktreeContext, id: string): Promise<{
@@ -28,5 +34,5 @@ interface WorktreeOperations {
28
34
  messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;
29
35
  }
30
36
  //#endregion
31
- export { SpawnWorktreeRequest, WorktreeContext, WorktreeOperations };
37
+ export { SpawnOptions, SpawnWorktreeRequest, WorktreeContext, WorktreeOperations };
32
38
  //# sourceMappingURL=worktreeOperations.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeOperations.d.mts","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"mappings":";;;;;UAciB;;EAEf;;EAEA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,MAAM,SAAS,iBAAiB,SAAS,uBAAuB,QAAQ;EACxE,MAAM,SAAS,iBAAiB,YAAY,iBAAiB,QAAQ;EACrE,KAAK,SAAS,kBAAkB,QAAQ;EACxC,OAAO,SAAS,iBAAiB,aAAa;IAAU,QAAQ;IAAgB;;EAChF,MAAM,SAAS,iBAAiB,YAAY,mBAAmB,QAAQ;EACvE,MAAM,SAAS,iBAAiB,kBAAkB,QAAQ,kBAAkB;EAC5E,KAAK,SAAS,iBAAiB,YAAY,kBAAkB;EAC7D,SAAS,SAAS,iBAAiB,aAAa,QAAQ"}
1
+ {"version":3,"file":"worktreeOperations.d.mts","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"mappings":";;;;;UAciB;;EAEf;;EAEA;;UAGe;EACf;EACA;EACA;;UAGe;;EAEf,SAAS;;EAET,cAAc;;UAGC;EACf,MAAM,SAAS,iBAAiB,SAAS,sBAAsB,UAAU,eAAe,QAAQ;EAChG,MAAM,SAAS,iBAAiB,YAAY,iBAAiB,QAAQ;EACrE,KAAK,SAAS,kBAAkB,QAAQ;EACxC,OAAO,SAAS,iBAAiB,aAAa;IAAU,QAAQ;IAAgB;;EAChF,MAAM,SAAS,iBAAiB,YAAY,mBAAmB,QAAQ;EACvE,MAAM,SAAS,iBAAiB,kBAAkB,QAAQ,kBAAkB;EAC5E,KAAK,SAAS,iBAAiB,YAAY,kBAAkB;EAC7D,SAAS,SAAS,iBAAiB,aAAa,QAAQ"}
@@ -1,2 +1,2 @@
1
- import{installDependencies as e}from"./dependencyInstall.mjs";import{HubUnavailableError as t,createWorktreeSession as n,sessionIsLive as r,stopWorktreeSession as i}from"../hub/hubClient.mjs";import{repositoryId as a,repositoryLabel as o,shortId as s}from"./repositoryIdentity.mjs";import{channelRoot as c,hubRegistryDir as l,registryFile as u,worktreesRoot as d}from"../filesystem/paths.mjs";import{createWorktreeChannel as f}from"../channel/worktreeChannel.mjs";import{createWorktreeRegistry as p}from"./worktreeRegistry.mjs";import{planPrune as m,reconcile as h,refuseClose as g,refuseSpawn as _,worktreeDirectory as v}from"../../services/worktreeNaming.mjs";import{DoomGitExpectedError as y}from"../../services/support/errors.mjs";import b from"node:fs";import{randomUUID as x}from"node:crypto";function S(S){let{git:C}=S,w=S.createSession??n,T=S.install??e,E=S.stopSession??i,D=S.isSessionLive??r,O=S.registryDir??l(),k=S.now??(()=>new Date),A={alive:e=>D(O,e.sessionId),exists:e=>b.existsSync(e)},j=async e=>{let t=await C.repositoryRoot(e.cwd);if(t===void 0)throw new y(`not_a_repository`,`${e.cwd} is not inside a git repository.`,!1,`Run this from a repository checkout.`);let n=p(u(t,S.homeDir));return{root:t,store:n,records:n.list()}},M=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw new y(`worktree_not_found`,`No worktree with id ${t}.`,!1,`Call list to see the current ids.`);return n},N=(e,t,n)=>{if(t.parentSessionId!==e.sessionId&&D(O,t.parentSessionId))throw new y(`worktree_not_owned`,`Worktree ${t.id} belongs to another session.`,!1,`Ask the session that created it to ${n} it, or close that session first.`)};return{async spawn(e,n){let{root:r,store:i,records:c}=await j(e),l=_({branch:n.branch,existing:c});if(l!==void 0)throw new y(`worktree_exists`,l,!1,`Pick another branch name, or close it.`);let u=n.baseRef??await C.currentBranch(r)??`HEAD`,f=s(x()),p=v({worktreesRoot:d(S.homeDir),repositoryLabel:o(r),repositoryId:a(r),branch:n.branch,shortId:f});await C.addWorktree({repositoryRoot:r,path:p,branch:n.branch,baseRef:u});let m=await T(p);if(m.kind===`failed`)throw await C.removeWorktree({repositoryRoot:r,path:p,force:!0}).catch(()=>void 0),new y(`install_failed`,`${m.command} install failed in the new worktree (exit ${String(m.code??`unknown`)}).`,!0,`Run the install by hand in the repository to see what it reports, then try again.`);let h;try{h=await w({cwd:p,name:n.name??n.branch,parentSessionId:e.sessionId,registryDir:O})}catch(e){throw await C.removeWorktree({repositoryRoot:r,path:p,force:!0}).catch(()=>void 0),e instanceof t?new y(`hub_unavailable`,e.message,!0,`Start the cockpit and try again.`):e}let g={version:1,id:f,branch:n.branch,baseRef:u,path:p,repositoryRoot:r,sessionId:h,parentSessionId:e.sessionId,status:`running`,createdAt:k().toISOString()};return i.replace([...c,g]),g},async close(e,t,n){let{root:r,store:i,records:a}=await j(e),o=M(a,t);N(e,o,`close`);let s=b.existsSync(o.path)?await C.dirtyFiles(o.path):[],c=g({record:o,dirtyFiles:s,force:n});if(c!==void 0)throw new y(`worktree_dirty`,c,!1,`Commit the work, or pass force: true.`);return await E(O,o.sessionId),await C.removeWorktree({repositoryRoot:r,path:o.path,force:n}),i.replace(a.filter(e=>e.id!==t)),o},async list(e){let{store:t,records:n}=await j(e),r=h(n,A);return r.changed.length>0&&t.replace(r.records),r.records},async status(e,t){let{records:n}=await j(e),r=M(n,t);return{record:r,dirtyFiles:b.existsSync(r.path)?await C.dirtyFiles(r.path):[]}},async merge(e,t,n){let{root:r,records:i}=await j(e),a=M(i,t);N(e,a,`merge`);let o=await C.dirtyFiles(r);if(o.length>0)throw new y(`worktree_dirty`,`The parent checkout has ${String(o.length)} uncommitted file(s): ${o.slice(0,10).join(`, `)}.`,!1,`Commit or stash the parent checkout first.`);return await C.mergeBranch({repositoryRoot:r,branch:a.branch,...n===void 0?{}:{message:n}}),a},async send(e,t,n){let{records:r}=await j(e),i=M(r,t),a=e.sessionId===i.sessionId?`parent`:`child`;f(c(i.id,S.homeDir)).send(a,n)},async messages(e,t){let{records:n}=await j(e),r=M(n,t),i=f(c(r.id,S.homeDir));i.sweep();let a=e.sessionId===r.sessionId?`child`:`parent`;return i.receive(a)},async prune(e,t){let{root:n,store:r,records:i}=await j(e),a=h(i,A),o=await C.listWorktreePaths(n),s=new Map;for(let e of a.records)e.status===`orphaned`&&b.existsSync(e.path)&&s.set(e.path,await C.dirtyFiles(e.path));let c=m({records:a.records,gitPaths:o,worktreesRoot:d(S.homeDir),dirtyByPath:s});if(t)return r.replace(a.records),c;for(let e of c.remove)await C.removeWorktree({repositoryRoot:n,path:e.path,force:!1});let l=new Set([...c.remove,...c.forget].map(e=>e.id));return r.replace(a.records.filter(e=>!l.has(e.id))),c}}}export{S as createWorktreeOperations};
1
+ import{mirrorComposition as e}from"./compositionMirror.mjs";import{HubUnavailableError as t,createWorktreeSession as n,sessionIsLive as r,stopWorktreeSession as i}from"../hub/hubClient.mjs";import{repositoryId as a,repositoryLabel as o,shortId as s}from"./repositoryIdentity.mjs";import{channelRoot as c,hubRegistryDir as l,registryFile as u,worktreesRoot as d}from"../filesystem/paths.mjs";import{createWorktreeChannel as f}from"../channel/worktreeChannel.mjs";import{createWorktreeRegistry as p}from"./worktreeRegistry.mjs";import{planPrune as m,reconcile as h,refuseClose as g,refuseSpawn as _,worktreeDirectory as v}from"../../services/worktreeNaming.mjs";import{DoomGitExpectedError as y}from"../../services/support/errors.mjs";import b from"node:fs";import{randomUUID as x}from"node:crypto";function S(S){let{git:C}=S,w=S.createSession??n,T=S.stopSession??i,E=S.mirror??e,D=S.isSessionLive??r,O=S.registryDir??l(),k=S.now??(()=>new Date),A={alive:e=>D(O,e.sessionId),exists:e=>b.existsSync(e)},j=async e=>{let t=await C.repositoryRoot(e.cwd);if(t===void 0)throw new y(`not_a_repository`,`${e.cwd} is not inside a git repository.`,!1,`Run this from a repository checkout.`);let n=p(u(t,S.homeDir));return{root:t,store:n,records:n.list()}},M=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw new y(`worktree_not_found`,`No worktree with id ${t}.`,!1,`Call list to see the current ids.`);return n},N=(e,t,n)=>{if(t.parentSessionId!==e.sessionId&&D(O,t.parentSessionId))throw new y(`worktree_not_owned`,`Worktree ${t.id} belongs to another session.`,!1,`Ask the session that created it to ${n} it, or close that session first.`)};return{async spawn(e,n,r){let{root:i,store:c,records:l}=await j(e),u=_({branch:n.branch,existing:l});if(u!==void 0)throw new y(`worktree_exists`,u,!1,`Pick another branch name, or close it.`);let f=n.baseRef??await C.currentBranch(i)??`HEAD`,p=s(x()),m=v({worktreesRoot:d(S.homeDir),repositoryLabel:o(i),repositoryId:a(i),branch:n.branch,shortId:p}),h=()=>r?.signal?.aborted===!0,g=async()=>(await C.removeWorktree({repositoryRoot:i,path:m,force:!0}).catch(()=>void 0),await C.deleteBranch({repositoryRoot:i,branch:n.branch}).catch(()=>!1)?``:` The branch ${n.branch} has work on it and was kept.`);if(r?.onProgress?.(`creating branch ${n.branch}\u2026`),await C.addWorktree({repositoryRoot:i,path:m,branch:n.branch,baseRef:f}),h()){let e=await g();throw new y(`spawn_cancelled`,`Cancelled before the session started.${e}`,!1,`The worktree was removed; run it again when you are ready.`)}r?.onProgress?.(`mirroring build output…`),E(i,m),r?.onProgress?.(`starting session…`);let b;try{b=await w({cwd:m,name:n.name??n.branch,parentSessionId:e.sessionId,registryDir:O,...r?.signal===void 0?{}:{signal:r.signal}})}catch(e){let n=await g();throw h()?new y(`spawn_cancelled`,`Cancelled while the session was starting.${n}`,!1,`The worktree was removed; run it again when you are ready.`):e instanceof t?new y(`hub_unavailable`,`${e.message}${n}`,!0,`Start the cockpit and try again.`):e}let D={version:1,id:p,branch:n.branch,baseRef:f,path:m,repositoryRoot:i,sessionId:b,parentSessionId:e.sessionId,status:`running`,createdAt:k().toISOString()};try{c.replace([...l,D])}catch(e){await T(O,b).catch(()=>void 0);let t=await g();throw new y(`registry_write_failed`,`The worktree was created but the registry could not be written (${e.message}).${t}`,!0,`Check the registry file for permissions or free space, then try again.`)}return D},async close(e,t,n){let{root:r,store:i,records:a}=await j(e),o=M(a,t);N(e,o,`close`);let s=b.existsSync(o.path)?await C.dirtyFiles(o.path):[],c=g({record:o,dirtyFiles:s,force:n});if(c!==void 0)throw new y(`worktree_dirty`,c,!1,`Commit the work, or pass force: true.`);return await T(O,o.sessionId),await C.removeWorktree({repositoryRoot:r,path:o.path,force:n}),i.replace(a.filter(e=>e.id!==t)),o},async list(e){let{store:t,records:n}=await j(e),r=h(n,A);return r.changed.length>0&&t.replace(r.records),r.records},async status(e,t){let{records:n}=await j(e),r=M(n,t);return{record:r,dirtyFiles:b.existsSync(r.path)?await C.dirtyFiles(r.path):[]}},async merge(e,t,n){let{root:r,records:i}=await j(e),a=M(i,t);N(e,a,`merge`);let o=await C.dirtyFiles(r);if(o.length>0)throw new y(`worktree_dirty`,`The parent checkout has ${String(o.length)} uncommitted file(s): ${o.slice(0,10).join(`, `)}.`,!1,`Commit or stash the parent checkout first.`);return await C.mergeBranch({repositoryRoot:r,branch:a.branch,...n===void 0?{}:{message:n}}),a},async send(e,t,n){let{records:r}=await j(e),i=M(r,t),a=e.sessionId===i.sessionId?`parent`:`child`;f(c(i.id,S.homeDir)).send(a,n)},async messages(e,t){let{records:n}=await j(e),r=M(n,t),i=f(c(r.id,S.homeDir));i.sweep();let a=e.sessionId===r.sessionId?`child`:`parent`;return i.receive(a)},async prune(e,t){let{root:n,store:r,records:i}=await j(e),a=h(i,A),o=await C.listWorktreePaths(n),s=new Map;for(let e of a.records)e.status===`orphaned`&&b.existsSync(e.path)&&s.set(e.path,await C.dirtyFiles(e.path));let c=m({records:a.records,gitPaths:o,worktreesRoot:d(S.homeDir),dirtyByPath:s});if(t)return r.replace(a.records),c;for(let e of c.remove)await C.removeWorktree({repositoryRoot:n,path:e.path,force:!1});for(let e of[...c.remove,...c.forget])await C.deleteBranch({repositoryRoot:n,branch:e.branch}).catch(()=>!1)||c.keptBranches.push(e.branch);let l=new Set([...c.remove,...c.forget].map(e=>e.id));return r.replace(a.records.filter(e=>!l.has(e.id))),c}}}export{S as createWorktreeOperations};
2
2
  //# sourceMappingURL=worktreeOperations.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeOperations.mjs","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { installDependencies } from './dependencyInstall.ts';\nimport { createWorktreeSession, HubUnavailableError, sessionIsLive, stopWorktreeSession } from '../hub/hubClient.ts';\nimport { channelRoot, hubRegistryDir, registryFile, worktreesRoot } from '../filesystem/paths.ts';\nimport { repositoryId, repositoryLabel, shortId } from './repositoryIdentity.ts';\nimport { createWorktreeChannel } from '../channel/worktreeChannel.ts';\nimport type { ChannelMessage, ChannelParty } from '../channel/worktreeChannel.ts';\nimport { createWorktreeRegistry } from './worktreeRegistry.ts';\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry.ts';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry.ts';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../../services/worktreeNaming.ts';\nimport { DoomGitExpectedError } from '../../services/support/errors.ts';\n\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: string;\n name?: string;\n}\n\nexport interface WorktreeOperations {\n spawn(context: WorktreeContext, request: SpawnWorktreeRequest): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;\n list(context: WorktreeContext): Promise<WorktreeRecord[]>;\n status(context: WorktreeContext, id: string): Promise<{ record: WorktreeRecord; dirtyFiles: string[] }>;\n merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;\n prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;\n send(context: WorktreeContext, id: string, message: string): Promise<void>;\n messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** Injected so tests never reach the network. */\n createSession?: typeof createWorktreeSession;\n /** Injected so tests never run a package manager. */\n install?: typeof installDependencies;\n stopSession?: typeof stopWorktreeSession;\n isSessionLive?: typeof sessionIsLive;\n homeDir?: string;\n registryDir?: string;\n /** Injected so a record's createdAt is reproducible in a test. */\n now?: () => Date;\n}\n\nexport function createWorktreeOperations(deps: WorktreeOperationsDeps): WorktreeOperations {\n const { git } = deps;\n const createSession = deps.createSession ?? createWorktreeSession;\n const install = deps.install ?? installDependencies;\n const stopSession = deps.stopSession ?? stopWorktreeSession;\n const isSessionLive = deps.isSessionLive ?? sessionIsLive;\n const registryDir = deps.registryDir ?? hubRegistryDir();\n const now = deps.now ?? (() => new Date());\n const probe = {\n alive: (record: WorktreeRecord) => isSessionLive(registryDir, record.sessionId),\n exists: (path: string) => fs.existsSync(path),\n };\n\n /**\n * Everything an action needs about the repository it is acting on.\n *\n * Resolved per call rather than cached: a session's cwd is stable, but the\n * registry file is shared with the cockpit panel and another process may\n * have written it since the last call.\n */\n const resolve = async (context: WorktreeContext) => {\n const root = await git.repositoryRoot(context.cwd);\n if (root === undefined) {\n throw new DoomGitExpectedError(\n 'not_a_repository',\n `${context.cwd} is not inside a git repository.`,\n false,\n 'Run this from a repository checkout.',\n );\n }\n const store = createWorktreeRegistry(registryFile(root, deps.homeDir));\n return { root, store, records: store.list() };\n };\n\n const require = (records: readonly WorktreeRecord[], id: string): WorktreeRecord => {\n const record = records.find((entry) => entry.id === id);\n if (record === undefined) {\n throw new DoomGitExpectedError(\n 'worktree_not_found',\n `No worktree with id ${id}.`,\n false,\n 'Call list to see the current ids.',\n );\n }\n return record;\n };\n\n /**\n * Refuses to destroy or merge a worktree another live session is using.\n *\n * `parentSessionId` records who asked for the worktree. Two sessions in one\n * checkout share this registry, so without the check either could close the\n * other's work in progress by id.\n *\n * Once that session is gone there is no owner left to protect, and refusing\n * would strand the worktree: nothing else could ever close it.\n */\n const requireOwner = (context: WorktreeContext, record: WorktreeRecord, action: string): void => {\n if (record.parentSessionId === context.sessionId) return;\n if (!isSessionLive(registryDir, record.parentSessionId)) return;\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n `Ask the session that created it to ${action} it, or close that session first.`,\n );\n };\n\n return {\n async spawn(context, request) {\n const { root, store, records } = await resolve(context);\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const baseRef = request.baseRef ?? (await git.currentBranch(root)) ?? 'HEAD';\n const id = shortId(randomUUID());\n const path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n\n await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\n\n // Before the session, not after. The session resolves this repository's\n // composition, and every workspace package path in it points at a\n // directory that exists only once dependencies are linked. Starting the\n // session first makes it fall back to the global bundle and quietly lose\n // the repository's own packages.\n const installed = await install(path);\n if (installed.kind === 'failed') {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n throw new DoomGitExpectedError(\n 'install_failed',\n `${installed.command} install failed in the new worktree (exit ${String(installed.code ?? 'unknown')}).`,\n true,\n 'Run the install by hand in the repository to see what it reports, then try again.',\n );\n }\n\n // The worktree exists from here on, so every later failure has to leave\n // it removed or recorded. An unrecorded directory on disk is the one\n // outcome with no way back: nothing would ever list it again.\n let sessionId: string;\n try {\n sessionId = await createSession({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n registryDir,\n });\n } catch (error) {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n if (error instanceof HubUnavailableError) {\n throw new DoomGitExpectedError('hub_unavailable', error.message, true, 'Start the cockpit and try again.');\n }\n throw error;\n }\n\n const record: WorktreeRecord = {\n version: WORKTREE_RECORD_VERSION,\n id,\n branch: request.branch,\n baseRef,\n path,\n repositoryRoot: root,\n sessionId,\n parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n store.replace([...records, record]);\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_dirty', refusal, false, 'Commit the work, or pass force: true.');\n }\n // The session is stopped before the directory goes. Removing a checkout\n // while a process still holds files open in it is how a half-removed\n // worktree and a stale git administrative entry are made.\n await stopSession(registryDir, record.sessionId);\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n store.replace(records.filter((entry) => entry.id !== id));\n return record;\n },\n\n async list(context) {\n const { store, records } = await resolve(context);\n const outcome = reconcile(records, probe);\n if (outcome.changed.length > 0) store.replace(outcome.records);\n return outcome.records;\n },\n\n async status(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n return { record, dirtyFiles };\n },\n\n async merge(context, id, message) {\n const { root, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'merge');\n // The merge lands in the parent, so the parent is what must be clean. A\n // dirty parent would mix the person's in-flight edits into a merge commit\n // they did not intend to make.\n const parentDirty = await git.dirtyFiles(root);\n if (parentDirty.length > 0) {\n throw new DoomGitExpectedError(\n 'worktree_dirty',\n `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(', ')}.`,\n false,\n 'Commit or stash the parent checkout first.',\n );\n }\n await git.mergeBranch({\n repositoryRoot: root,\n branch: record.branch,\n ...(message === undefined ? {} : { message }),\n });\n return record;\n },\n\n /**\n * Which side of the channel the caller is.\n *\n * A worktree session is the child of the record it belongs to, and the\n * parent for everything else. Deciding from the session id rather than a\n * flag means neither side can address itself by mistake.\n */\n async send(context, id, message) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const party: ChannelParty = context.sessionId === record.sessionId ? 'parent' : 'child';\n createWorktreeChannel(channelRoot(record.id, deps.homeDir)).send(party, message);\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const channel = createWorktreeChannel(channelRoot(record.id, deps.homeDir));\n channel.sweep();\n const party: ChannelParty = context.sessionId === record.sessionId ? 'child' : 'parent';\n return channel.receive(party);\n },\n\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(record.path)) {\n dirtyByPath.set(record.path, await git.dirtyFiles(record.path));\n }\n }\n const plan = planPrune({\n records: reconciled.records,\n gitPaths,\n worktreesRoot: worktreesRoot(deps.homeDir),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));\n return plan;\n },\n };\n}\n"],"mappings":"+xBAoDA,SAAgB,EAAyB,EAAkD,CACzF,GAAM,CAAE,OAAQ,EACV,EAAgB,EAAK,eAAiB,EACtC,EAAU,EAAK,SAAW,EAC1B,EAAc,EAAK,aAAe,EAClC,EAAgB,EAAK,eAAiB,EACtC,EAAc,EAAK,aAAe,EAAe,EACjD,EAAM,EAAK,UAAc,IAAI,MAC7B,EAAQ,CACZ,MAAQ,GAA2B,EAAc,EAAa,EAAO,SAAS,EAC9E,OAAS,GAAiB,EAAG,WAAW,CAAI,CAC9C,EASM,EAAU,KAAO,IAA6B,CAClD,IAAM,EAAO,MAAM,EAAI,eAAe,EAAQ,GAAG,EACjD,GAAI,IAAS,IAAA,GACX,MAAM,IAAI,EACR,mBACA,GAAG,EAAQ,IAAI,kCACf,GACA,sCACF,EAEF,IAAM,EAAQ,EAAuB,EAAa,EAAM,EAAK,OAAO,CAAC,EACrE,MAAO,CAAE,OAAM,QAAO,QAAS,EAAM,KAAK,CAAE,CAC9C,EAEM,GAAW,EAAoC,IAA+B,CAClF,IAAM,EAAS,EAAQ,KAAM,GAAU,EAAM,KAAO,CAAE,EACtD,GAAI,IAAW,IAAA,GACb,MAAM,IAAI,EACR,qBACA,uBAAuB,EAAG,GAC1B,GACA,mCACF,EAEF,OAAO,CACT,EAYM,GAAgB,EAA0B,EAAwB,IAAyB,CAC3F,KAAO,kBAAoB,EAAQ,WAClC,EAAc,EAAa,EAAO,eAAe,EACtD,MAAM,IAAI,EACR,qBACA,YAAY,EAAO,GAAG,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MAAM,EAAI,WAAW,EAAO,IAAI,CAAC,EAGlE,IAAM,EAAO,EAAU,CACrB,QAAS,EAAW,QACpB,WACA,cAAe,EAAc,EAAK,OAAO,EACzC,aACF,CAAC,EACD,GAAI,EAEF,OADA,EAAM,QAAQ,EAAW,OAAO,EACzB,EAET,IAAK,IAAM,KAAU,EAAK,OACxB,MAAM,EAAI,eAAe,CAAE,eAAgB,EAAM,KAAM,EAAO,KAAM,MAAO,EAAM,CAAC,EAEpF,IAAM,EAAU,IAAI,IAAI,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,CAAC,CAAC,IAAK,GAAW,EAAO,EAAE,CAAC,EAEnF,OADA,EAAM,QAAQ,EAAW,QAAQ,OAAQ,GAAW,CAAC,EAAQ,IAAI,EAAO,EAAE,CAAC,CAAC,EACrE,CACT,CACF,CACF"}
1
+ {"version":3,"file":"worktreeOperations.mjs","names":[],"sources":["../../../src/adapters/worktree/worktreeOperations.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { mirrorComposition } from './compositionMirror.ts';\nimport { createWorktreeSession, HubUnavailableError, sessionIsLive, stopWorktreeSession } from '../hub/hubClient.ts';\nimport { channelRoot, hubRegistryDir, registryFile, worktreesRoot } from '../filesystem/paths.ts';\nimport { repositoryId, repositoryLabel, shortId } from './repositoryIdentity.ts';\nimport { createWorktreeChannel } from '../channel/worktreeChannel.ts';\nimport type { ChannelMessage, ChannelParty } from '../channel/worktreeChannel.ts';\nimport { createWorktreeRegistry } from './worktreeRegistry.ts';\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry.ts';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry.ts';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../../services/worktreeNaming.ts';\nimport { DoomGitExpectedError } from '../../services/support/errors.ts';\n\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: string;\n name?: string;\n}\n\nexport interface SpawnOptions {\n /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */\n signal?: AbortSignal;\n /** Phase labels, for a caller that can show them while the work runs. */\n onProgress?: (label: string) => void;\n}\n\nexport interface WorktreeOperations {\n spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;\n list(context: WorktreeContext): Promise<WorktreeRecord[]>;\n status(context: WorktreeContext, id: string): Promise<{ record: WorktreeRecord; dirtyFiles: string[] }>;\n merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;\n prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;\n send(context: WorktreeContext, id: string, message: string): Promise<void>;\n messages(context: WorktreeContext, id: string): Promise<ChannelMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** Injected so tests never reach the network. */\n createSession?: typeof createWorktreeSession;\n stopSession?: typeof stopWorktreeSession;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n isSessionLive?: typeof sessionIsLive;\n homeDir?: string;\n registryDir?: string;\n /** Injected so a record's createdAt is reproducible in a test. */\n now?: () => Date;\n}\n\nexport function createWorktreeOperations(deps: WorktreeOperationsDeps): WorktreeOperations {\n const { git } = deps;\n const createSession = deps.createSession ?? createWorktreeSession;\n const stopSession = deps.stopSession ?? stopWorktreeSession;\n const mirror = deps.mirror ?? mirrorComposition;\n const isSessionLive = deps.isSessionLive ?? sessionIsLive;\n const registryDir = deps.registryDir ?? hubRegistryDir();\n const now = deps.now ?? (() => new Date());\n const probe = {\n alive: (record: WorktreeRecord) => isSessionLive(registryDir, record.sessionId),\n exists: (path: string) => fs.existsSync(path),\n };\n\n /**\n * Everything an action needs about the repository it is acting on.\n *\n * Resolved per call rather than cached: a session's cwd is stable, but the\n * registry file is shared with the cockpit panel and another process may\n * have written it since the last call.\n */\n const resolve = async (context: WorktreeContext) => {\n const root = await git.repositoryRoot(context.cwd);\n if (root === undefined) {\n throw new DoomGitExpectedError(\n 'not_a_repository',\n `${context.cwd} is not inside a git repository.`,\n false,\n 'Run this from a repository checkout.',\n );\n }\n const store = createWorktreeRegistry(registryFile(root, deps.homeDir));\n return { root, store, records: store.list() };\n };\n\n const require = (records: readonly WorktreeRecord[], id: string): WorktreeRecord => {\n const record = records.find((entry) => entry.id === id);\n if (record === undefined) {\n throw new DoomGitExpectedError(\n 'worktree_not_found',\n `No worktree with id ${id}.`,\n false,\n 'Call list to see the current ids.',\n );\n }\n return record;\n };\n\n /**\n * Refuses to destroy or merge a worktree another live session is using.\n *\n * `parentSessionId` records who asked for the worktree. Two sessions in one\n * checkout share this registry, so without the check either could close the\n * other's work in progress by id.\n *\n * Once that session is gone there is no owner left to protect, and refusing\n * would strand the worktree: nothing else could ever close it.\n */\n const requireOwner = (context: WorktreeContext, record: WorktreeRecord, action: string): void => {\n if (record.parentSessionId === context.sessionId) return;\n if (!isSessionLive(registryDir, record.parentSessionId)) return;\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n `Ask the session that created it to ${action} it, or close that session first.`,\n );\n };\n\n return {\n async spawn(context, request, options) {\n const { root, store, records } = await resolve(context);\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const baseRef = request.baseRef ?? (await git.currentBranch(root)) ?? 'HEAD';\n const id = shortId(randomUUID());\n const path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n\n // The worktree and the branch are made by one command, so they are undone\n // by one too. `worktree remove` leaves the branch behind, and a branch\n // nobody asked for is what a failed spawn used to leave on the floor.\n const cancelled = (): boolean => options?.signal?.aborted === true;\n const rollback = async (): Promise<string> => {\n await git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: request.branch }).catch(() => false);\n return deleted ? '' : ` The branch ${request.branch} has work on it and was kept.`;\n };\n\n options?.onProgress?.(`creating branch ${request.branch}\\u2026`);\n await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\n\n // Checked here rather than only inside the session call: this is the\n // point where a checkout exists that nothing has recorded yet, which is\n // exactly the state an interrupted spawn used to leave behind.\n if (cancelled()) {\n const kept = await rollback();\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n `Cancelled before the session started.${kept}`,\n false,\n 'The worktree was removed; run it again when you are ready.',\n );\n }\n\n // Before the session, because the session composes the extensions this\n // repository's config names and those live in build output git does not\n // track. A worktree without it starts and dies on the first package it\n // cannot resolve. Nothing here can fail the spawn: a repository with no\n // build output to mirror simply has none.\n options?.onProgress?.('mirroring build output\\u2026');\n mirror(root, path);\n\n // The worktree exists from here on, so every later failure has to leave\n // it removed or recorded. An unrecorded directory on disk is the one\n // outcome with no way back: nothing would ever list it again.\n options?.onProgress?.('starting session\\u2026');\n let sessionId: string;\n try {\n sessionId = await createSession({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n registryDir,\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n } catch (error) {\n const kept = await rollback();\n if (cancelled()) {\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n `Cancelled while the session was starting.${kept}`,\n false,\n 'The worktree was removed; run it again when you are ready.',\n );\n }\n if (error instanceof HubUnavailableError) {\n throw new DoomGitExpectedError(\n 'hub_unavailable',\n `${error.message}${kept}`,\n true,\n 'Start the cockpit and try again.',\n );\n }\n throw error;\n }\n\n const record: WorktreeRecord = {\n version: WORKTREE_RECORD_VERSION,\n id,\n branch: request.branch,\n baseRef,\n path,\n repositoryRoot: root,\n sessionId,\n parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n try {\n store.replace([...records, record]);\n } catch (error) {\n // A live session with no record is the worst outcome available here:\n // it runs, and no id anything can name points at it. The session goes\n // back too, rather than being left for someone to find by hand.\n await stopSession(registryDir, sessionId).catch(() => undefined);\n const kept = await rollback();\n throw new DoomGitExpectedError(\n 'registry_write_failed',\n `The worktree was created but the registry could not be written (${(error as Error).message}).${kept}`,\n true,\n 'Check the registry file for permissions or free space, then try again.',\n );\n }\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_dirty', refusal, false, 'Commit the work, or pass force: true.');\n }\n // The session is stopped before the directory goes. Removing a checkout\n // while a process still holds files open in it is how a half-removed\n // worktree and a stale git administrative entry are made.\n await stopSession(registryDir, record.sessionId);\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n store.replace(records.filter((entry) => entry.id !== id));\n return record;\n },\n\n async list(context) {\n const { store, records } = await resolve(context);\n const outcome = reconcile(records, probe);\n if (outcome.changed.length > 0) store.replace(outcome.records);\n return outcome.records;\n },\n\n async status(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n return { record, dirtyFiles };\n },\n\n async merge(context, id, message) {\n const { root, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'merge');\n // The merge lands in the parent, so the parent is what must be clean. A\n // dirty parent would mix the person's in-flight edits into a merge commit\n // they did not intend to make.\n const parentDirty = await git.dirtyFiles(root);\n if (parentDirty.length > 0) {\n throw new DoomGitExpectedError(\n 'worktree_dirty',\n `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(', ')}.`,\n false,\n 'Commit or stash the parent checkout first.',\n );\n }\n await git.mergeBranch({\n repositoryRoot: root,\n branch: record.branch,\n ...(message === undefined ? {} : { message }),\n });\n return record;\n },\n\n /**\n * Which side of the channel the caller is.\n *\n * A worktree session is the child of the record it belongs to, and the\n * parent for everything else. Deciding from the session id rather than a\n * flag means neither side can address itself by mistake.\n */\n async send(context, id, message) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const party: ChannelParty = context.sessionId === record.sessionId ? 'parent' : 'child';\n createWorktreeChannel(channelRoot(record.id, deps.homeDir)).send(party, message);\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const channel = createWorktreeChannel(channelRoot(record.id, deps.homeDir));\n channel.sweep();\n const party: ChannelParty = context.sessionId === record.sessionId ? 'child' : 'parent';\n return channel.receive(party);\n },\n\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(record.path)) {\n dirtyByPath.set(record.path, await git.dirtyFiles(record.path));\n }\n }\n const plan = planPrune({\n records: reconciled.records,\n gitPaths,\n worktreesRoot: worktreesRoot(deps.homeDir),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n }\n // The checkout goes, so the branch it was made for goes with it. Safe\n // delete only: git keeps anything holding commits, and the plan says\n // which ones it kept rather than leaving the reader to notice later.\n for (const record of [...plan.remove, ...plan.forget]) {\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: record.branch }).catch(() => false);\n if (!deleted) plan.keptBranches.push(record.branch);\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n store.replace(reconciled.records.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,EAAQ,CAC3B,GAAM,CAAE,OAAM,QAAO,WAAY,MAAM,EAAQ,CAAO,EAChD,EAAa,EAAU,EAAS,CAAK,EACrC,EAAW,MAAM,EAAI,kBAAkB,CAAI,EAC3C,EAAc,IAAI,IACxB,IAAK,IAAM,KAAU,EAAW,QAC1B,EAAO,SAAW,YAAc,EAAG,WAAW,EAAO,IAAI,GAC3D,EAAY,IAAI,EAAO,KAAM,MAAM,EAAI,WAAW,EAAO,IAAI,CAAC,EAGlE,IAAM,EAAO,EAAU,CACrB,QAAS,EAAW,QACpB,WACA,cAAe,EAAc,EAAK,OAAO,EACzC,aACF,CAAC,EACD,GAAI,EAEF,OADA,EAAM,QAAQ,EAAW,OAAO,EACzB,EAET,IAAK,IAAM,KAAU,EAAK,OACxB,MAAM,EAAI,eAAe,CAAE,eAAgB,EAAM,KAAM,EAAO,KAAM,MAAO,EAAM,CAAC,EAKpF,IAAK,IAAM,IAAU,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,EAE7C,MADiB,EAAI,aAAa,CAAE,eAAgB,EAAM,OAAQ,EAAO,MAAO,CAAC,CAAC,CAAC,UAAY,EAAK,GAC3F,EAAK,aAAa,KAAK,EAAO,MAAM,EAEpD,IAAM,EAAU,IAAI,IAAI,CAAC,GAAG,EAAK,OAAQ,GAAG,EAAK,MAAM,CAAC,CAAC,IAAK,GAAW,EAAO,EAAE,CAAC,EAEnF,OADA,EAAM,QAAQ,EAAW,QAAQ,OAAQ,GAAW,CAAC,EAAQ,IAAI,EAAO,EAAE,CAAC,CAAC,EACrE,CACT,CACF,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","names":[],"sources":["../../../src/services/support/errors.ts"],"sourcesContent":["/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-extension-contracts` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-team's shape rather than\n * reaching across a layer boundary for it. The duplication is deliberate and\n * small; a shared helper would be the better answer only once a third package\n * needs one.\n */\n\nexport type DoomGitErrorCode =\n | 'invalid_request'\n | 'not_a_repository'\n | 'worktree_exists'\n | 'worktree_not_found'\n | 'worktree_not_owned'\n | 'worktree_dirty'\n | 'hub_unavailable'\n | 'install_failed'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\n message: string,\n readonly retryable: boolean,\n readonly recovery: string,\n ) {\n // The recovery line rides in the message because a tool result is read as\n // text: an error the model cannot act on costs a turn to rediscover.\n super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n this.name = 'DoomGitExpectedError';\n }\n}\n\nexport function invalidRequest(message: string, recovery: string): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n"],"mappings":"AAqBA,IAAa,EAAb,cAA0C,KAAM,CAEnC,KAEA,UACA,SAJX,YACE,EACA,EACA,EACA,EACA,CAGA,MAAM,IAAI,EAAK,IAAI,EAAQ,cAAc,GAAU,EAP1C,KAAA,KAAA,EAEA,KAAA,UAAA,EACA,KAAA,SAAA,EAKT,KAAK,KAAO,sBACd,CACF,EAEA,SAAgB,EAAe,EAAiB,EAAwC,CACtF,OAAO,IAAI,EAAqB,kBAAmB,EAAS,GAAO,CAAQ,CAC7E"}
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../../../src/services/support/errors.ts"],"sourcesContent":["/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-extension-contracts` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-team's shape rather than\n * reaching across a layer boundary for it. The duplication is deliberate and\n * small; a shared helper would be the better answer only once a third package\n * needs one.\n */\n\nexport type DoomGitErrorCode =\n | 'invalid_request'\n | 'not_a_repository'\n | 'worktree_exists'\n | 'worktree_not_found'\n | 'worktree_not_owned'\n | 'worktree_dirty'\n | 'hub_unavailable'\n | 'spawn_cancelled'\n | 'registry_write_failed'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\n message: string,\n readonly retryable: boolean,\n readonly recovery: string,\n ) {\n // The recovery line rides in the message because a tool result is read as\n // text: an error the model cannot act on costs a turn to rediscover.\n super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n this.name = 'DoomGitExpectedError';\n }\n}\n\nexport function invalidRequest(message: string, recovery: string): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n"],"mappings":"AAsBA,IAAa,EAAb,cAA0C,KAAM,CAEnC,KAEA,UACA,SAJX,YACE,EACA,EACA,EACA,EACA,CAGA,MAAM,IAAI,EAAK,IAAI,EAAQ,cAAc,GAAU,EAP1C,KAAA,KAAA,EAEA,KAAA,UAAA,EACA,KAAA,SAAA,EAKT,KAAK,KAAO,sBACd,CACF,EAEA,SAAgB,EAAe,EAAiB,EAAwC,CACtF,OAAO,IAAI,EAAqB,kBAAmB,EAAS,GAAO,CAAQ,CAC7E"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../../src/services/support/errors.ts"],"sourcesContent":["/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-extension-contracts` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-team's shape rather than\n * reaching across a layer boundary for it. The duplication is deliberate and\n * small; a shared helper would be the better answer only once a third package\n * needs one.\n */\n\nexport type DoomGitErrorCode =\n | 'invalid_request'\n | 'not_a_repository'\n | 'worktree_exists'\n | 'worktree_not_found'\n | 'worktree_not_owned'\n | 'worktree_dirty'\n | 'hub_unavailable'\n | 'install_failed'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\n message: string,\n readonly retryable: boolean,\n readonly recovery: string,\n ) {\n // The recovery line rides in the message because a tool result is read as\n // text: an error the model cannot act on costs a turn to rediscover.\n super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n this.name = 'DoomGitExpectedError';\n }\n}\n\nexport function invalidRequest(message: string, recovery: string): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n"],"mappings":"AAqBA,IAAa,EAAb,cAA0C,KAAM,CAEnC,KAEA,UACA,SAJX,YACE,EACA,EACA,EACA,EACA,CAGA,MAAM,IAAI,EAAK,IAAI,EAAQ,cAAc,GAAU,EAP1C,KAAA,KAAA,EAEA,KAAA,UAAA,EACA,KAAA,SAAA,EAKT,KAAK,KAAO,sBACd,CACF,EAEA,SAAgB,EAAe,EAAiB,EAAwC,CACtF,OAAO,IAAI,EAAqB,kBAAmB,EAAS,GAAO,CAAQ,CAC7E"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../../src/services/support/errors.ts"],"sourcesContent":["/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-extension-contracts` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-team's shape rather than\n * reaching across a layer boundary for it. The duplication is deliberate and\n * small; a shared helper would be the better answer only once a third package\n * needs one.\n */\n\nexport type DoomGitErrorCode =\n | 'invalid_request'\n | 'not_a_repository'\n | 'worktree_exists'\n | 'worktree_not_found'\n | 'worktree_not_owned'\n | 'worktree_dirty'\n | 'hub_unavailable'\n | 'spawn_cancelled'\n | 'registry_write_failed'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\n message: string,\n readonly retryable: boolean,\n readonly recovery: string,\n ) {\n // The recovery line rides in the message because a tool result is read as\n // text: an error the model cannot act on costs a turn to rediscover.\n super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n this.name = 'DoomGitExpectedError';\n }\n}\n\nexport function invalidRequest(message: string, recovery: string): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n"],"mappings":"AAsBA,IAAa,EAAb,cAA0C,KAAM,CAEnC,KAEA,UACA,SAJX,YACE,EACA,EACA,EACA,EACA,CAGA,MAAM,IAAI,EAAK,IAAI,EAAQ,cAAc,GAAU,EAP1C,KAAA,KAAA,EAEA,KAAA,UAAA,EACA,KAAA,SAAA,EAKT,KAAK,KAAO,sBACd,CACF,EAEA,SAAgB,EAAe,EAAiB,EAAwC,CACtF,OAAO,IAAI,EAAqB,kBAAmB,EAAS,GAAO,CAAQ,CAC7E"}
@@ -1,2 +1,2 @@
1
- function e(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/gu,`-`).replace(/^-+|-+$/gu,``).slice(0,64).replace(/-+$/gu,``);return t===``?`worktree`:t}function t(t){let n=`${t.repositoryLabel}--${t.repositoryId}`;return`${t.worktreesRoot}/${n}/${e(t.branch)}--${t.shortId}`}function n(e){if(e.branch.trim()===``)return`A branch name is required.`;let t=e.existing.find(t=>t.branch===e.branch&&t.status!==`orphaned`);if(t)return`Branch ${e.branch} already has a worktree (${t.id}).`}function r(e){if(!e.record)return`No worktree with that id. Call list to see the current ids.`;if(e.dirtyFiles.length===0||e.force)return;let t=e.dirtyFiles.slice(0,10).join(`, `),n=e.dirtyFiles.length>10?`, and ${String(e.dirtyFiles.length-10)} more`:``;return`${String(e.dirtyFiles.length)} uncommitted file(s): ${t}${n}. Pass force: true to discard them.`}function i(e,t){let n=[];return{records:e.map(e=>e.status===`orphaned`||t.exists(e.path)&&t.alive(e)?e:(n.push(e.id),{...e,status:`orphaned`})),changed:n}}function a(e){let t={remove:[],forget:[],untracked:[],keptDirty:[]},n=new Set(e.records.map(e=>e.path)),r=new Set(e.gitPaths);for(let n of e.records)if(n.status===`orphaned`){if(!r.has(n.path)){t.forget.push(n);continue}if((e.dirtyByPath.get(n.path)??[]).length>0){t.keptDirty.push(n);continue}t.remove.push(n)}for(let r of e.gitPaths)r.startsWith(`${e.worktreesRoot}/`)&&!n.has(r)&&t.untracked.push(r);return t}exports.branchSlug=e,exports.planPrune=a,exports.reconcile=i,exports.refuseClose=r,exports.refuseSpawn=n,exports.worktreeDirectory=t;
1
+ function e(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/gu,`-`).replace(/^-+|-+$/gu,``).slice(0,64).replace(/-+$/gu,``);return t===``?`worktree`:t}function t(t){let n=`${t.repositoryLabel}--${t.repositoryId}`;return`${t.worktreesRoot}/${n}/${e(t.branch)}--${t.shortId}`}function n(e){if(e.branch.trim()===``)return`A branch name is required.`;let t=e.existing.find(t=>t.branch===e.branch&&t.status!==`orphaned`);if(t)return`Branch ${e.branch} already has a worktree (${t.id}).`}function r(e){if(!e.record)return`No worktree with that id. Call list to see the current ids.`;if(e.dirtyFiles.length===0||e.force)return;let t=e.dirtyFiles.slice(0,10).join(`, `),n=e.dirtyFiles.length>10?`, and ${String(e.dirtyFiles.length-10)} more`:``;return`${String(e.dirtyFiles.length)} uncommitted file(s): ${t}${n}. Pass force: true to discard them.`}function i(e,t){let n=[];return{records:e.map(e=>e.status===`orphaned`||t.exists(e.path)&&t.alive(e)?e:(n.push(e.id),{...e,status:`orphaned`})),changed:n}}function a(e){let t={remove:[],forget:[],untracked:[],keptDirty:[],keptBranches:[]},n=new Set(e.records.map(e=>e.path)),r=new Set(e.gitPaths);for(let n of e.records)if(n.status===`orphaned`){if(!r.has(n.path)){t.forget.push(n);continue}if((e.dirtyByPath.get(n.path)??[]).length>0){t.keptDirty.push(n);continue}t.remove.push(n)}for(let r of e.gitPaths)r.startsWith(`${e.worktreesRoot}/`)&&!n.has(r)&&t.untracked.push(r);return t}exports.branchSlug=e,exports.planPrune=a,exports.reconcile=i,exports.refuseClose=r,exports.refuseSpawn=n,exports.worktreeDirectory=t;
2
2
  //# sourceMappingURL=worktreeNaming.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeNaming.cjs","names":[],"sources":["../../src/services/worktreeNaming.ts"],"sourcesContent":["/**\n * Naming and reconciliation rules for worktrees, as pure functions.\n *\n * Everything here is a function of its arguments so the interesting decisions,\n * which are the ones about destroying work, can be tested without a repository\n * or a filesystem.\n */\n\nimport type { WorktreeRecord } from '../types/worktreeRegistry.ts';\n\nconst MAX_SLUG_LENGTH = 64;\n\n/**\n * A branch name reduced to one safe path segment.\n *\n * Slashes are the point: `wt/fix-auth` is a perfectly good branch and a\n * terrible directory name, because the nested directory it implies is not the\n * one the worktree lives in.\n */\nexport function branchSlug(branch: string): string {\n const slug = branch\n .toLowerCase()\n .replace(/[^a-z0-9]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n .slice(0, MAX_SLUG_LENGTH)\n .replace(/-+$/gu, '');\n return slug === '' ? 'worktree' : slug;\n}\n\n/**\n * The directory for one worktree.\n *\n * The short id disambiguates two branches whose slugs collide, such as\n * `feature/x` and `feature_x`, which would otherwise want the same directory.\n */\nexport function worktreeDirectory(input: {\n worktreesRoot: string;\n repositoryLabel: string;\n repositoryId: string;\n branch: string;\n shortId: string;\n}): string {\n const repository = `${input.repositoryLabel}--${input.repositoryId}`;\n return `${input.worktreesRoot}/${repository}/${branchSlug(input.branch)}--${input.shortId}`;\n}\n\n/** Why a worktree cannot be created, or undefined when it can. */\nexport function refuseSpawn(input: { branch: string; existing: readonly WorktreeRecord[] }): string | undefined {\n if (input.branch.trim() === '') return 'A branch name is required.';\n // Git refuses a second worktree on one branch, but its message names a path\n // the caller never chose, so this says it in the caller's own terms first.\n const live = input.existing.find((record) => record.branch === input.branch && record.status !== 'orphaned');\n if (live) return `Branch ${input.branch} already has a worktree (${live.id}).`;\n return undefined;\n}\n\n/** Why a worktree cannot be closed, or undefined when it can. */\nexport function refuseClose(input: {\n record: WorktreeRecord | undefined;\n dirtyFiles: readonly string[];\n force: boolean;\n}): string | undefined {\n if (!input.record) return 'No worktree with that id. Call list to see the current ids.';\n if (input.dirtyFiles.length === 0 || input.force) return undefined;\n // Naming the files is the point: \"the tree is dirty\" sends the reader to go\n // look, and the answer is usually a file they forgot rather than one they\n // meant to keep.\n const names = input.dirtyFiles.slice(0, 10).join(', ');\n const more = input.dirtyFiles.length > 10 ? `, and ${String(input.dirtyFiles.length - 10)} more` : '';\n return `${String(input.dirtyFiles.length)} uncommitted file(s): ${names}${more}. Pass force: true to discard them.`;\n}\n\nexport interface Reconciliation {\n records: WorktreeRecord[];\n /** Ids whose status changed, so a caller can report what it noticed. */\n changed: string[];\n}\n\n/**\n * Marks records whose process or directory is gone as orphaned.\n *\n * Nothing is deleted here. A doompi-git orphan owns a directory that may hold\n * uncommitted work, so losing the record would lose the only pointer to it.\n * Deletion is always a separate, named decision.\n */\nexport function reconcile(\n records: readonly WorktreeRecord[],\n probe: { alive: (record: WorktreeRecord) => boolean; exists: (path: string) => boolean },\n): Reconciliation {\n const changed: string[] = [];\n const next = records.map((record) => {\n if (record.status === 'orphaned') return record;\n const gone = !probe.exists(record.path) || !probe.alive(record);\n if (!gone) return record;\n changed.push(record.id);\n return { ...record, status: 'orphaned' as const };\n });\n return { records: next, changed };\n}\n\nexport interface PrunePlan {\n /** Orphans whose directory git still lists, safe to remove. */\n remove: WorktreeRecord[];\n /** Orphans whose directory is already gone; drop the record only. */\n forget: WorktreeRecord[];\n /** Paths git lists under our root that we have no record of; report, never touch. */\n untracked: string[];\n /** Orphans left alone because they still hold uncommitted work. */\n keptDirty: WorktreeRecord[];\n}\n\n/**\n * What a prune would do, decided before anything is destroyed.\n *\n * Separating the plan from the execution is what makes dryRun honest and lets\n * the destructive half be reviewed on its own.\n */\nexport function planPrune(input: {\n records: readonly WorktreeRecord[];\n gitPaths: readonly string[];\n worktreesRoot: string;\n dirtyByPath: ReadonlyMap<string, readonly string[]>;\n}): PrunePlan {\n const plan: PrunePlan = { remove: [], forget: [], untracked: [], keptDirty: [] };\n const known = new Set(input.records.map((record) => record.path));\n const listed = new Set(input.gitPaths);\n for (const record of input.records) {\n if (record.status !== 'orphaned') continue;\n if (!listed.has(record.path)) {\n plan.forget.push(record);\n continue;\n }\n if ((input.dirtyByPath.get(record.path) ?? []).length > 0) {\n plan.keptDirty.push(record);\n continue;\n }\n plan.remove.push(record);\n }\n for (const path of input.gitPaths) {\n // Only ever inside our own root: a worktree the user made by hand is none\n // of this package's business, even when it looks abandoned.\n if (path.startsWith(`${input.worktreesRoot}/`) && !known.has(path)) plan.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OAAQ,UAAoB,EAE7B,EAAG,SAAQ,CAClC,CAmBA,SAAgB,EAAU,EAKZ,CACZ,IAAM,EAAkB,CAAE,OAAQ,CAAC,EAAG,OAAQ,CAAC,EAAG,UAAW,CAAC,EAAG,UAAW,CAAC,CAAE,EACzE,EAAQ,IAAI,IAAI,EAAM,QAAQ,IAAK,GAAW,EAAO,IAAI,CAAC,EAC1D,EAAS,IAAI,IAAI,EAAM,QAAQ,EACrC,IAAK,IAAM,KAAU,EAAM,QACrB,KAAO,SAAW,WACtB,IAAI,CAAC,EAAO,IAAI,EAAO,IAAI,EAAG,CAC5B,EAAK,OAAO,KAAK,CAAM,EACvB,QACF,CACA,IAAK,EAAM,YAAY,IAAI,EAAO,IAAI,GAAK,CAAC,EAAA,CAAG,OAAS,EAAG,CACzD,EAAK,UAAU,KAAK,CAAM,EAC1B,QACF,CACA,EAAK,OAAO,KAAK,CAAM,CALvB,CAOF,IAAK,IAAM,KAAQ,EAAM,SAGnB,EAAK,WAAW,GAAG,EAAM,cAAc,EAAE,GAAK,CAAC,EAAM,IAAI,CAAI,GAAG,EAAK,UAAU,KAAK,CAAI,EAE9F,OAAO,CACT"}
1
+ {"version":3,"file":"worktreeNaming.cjs","names":[],"sources":["../../src/services/worktreeNaming.ts"],"sourcesContent":["/**\n * Naming and reconciliation rules for worktrees, as pure functions.\n *\n * Everything here is a function of its arguments so the interesting decisions,\n * which are the ones about destroying work, can be tested without a repository\n * or a filesystem.\n */\n\nimport type { WorktreeRecord } from '../types/worktreeRegistry.ts';\n\nconst MAX_SLUG_LENGTH = 64;\n\n/**\n * A branch name reduced to one safe path segment.\n *\n * Slashes are the point: `wt/fix-auth` is a perfectly good branch and a\n * terrible directory name, because the nested directory it implies is not the\n * one the worktree lives in.\n */\nexport function branchSlug(branch: string): string {\n const slug = branch\n .toLowerCase()\n .replace(/[^a-z0-9]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n .slice(0, MAX_SLUG_LENGTH)\n .replace(/-+$/gu, '');\n return slug === '' ? 'worktree' : slug;\n}\n\n/**\n * The directory for one worktree.\n *\n * The short id disambiguates two branches whose slugs collide, such as\n * `feature/x` and `feature_x`, which would otherwise want the same directory.\n */\nexport function worktreeDirectory(input: {\n worktreesRoot: string;\n repositoryLabel: string;\n repositoryId: string;\n branch: string;\n shortId: string;\n}): string {\n const repository = `${input.repositoryLabel}--${input.repositoryId}`;\n return `${input.worktreesRoot}/${repository}/${branchSlug(input.branch)}--${input.shortId}`;\n}\n\n/** Why a worktree cannot be created, or undefined when it can. */\nexport function refuseSpawn(input: { branch: string; existing: readonly WorktreeRecord[] }): string | undefined {\n if (input.branch.trim() === '') return 'A branch name is required.';\n // Git refuses a second worktree on one branch, but its message names a path\n // the caller never chose, so this says it in the caller's own terms first.\n const live = input.existing.find((record) => record.branch === input.branch && record.status !== 'orphaned');\n if (live) return `Branch ${input.branch} already has a worktree (${live.id}).`;\n return undefined;\n}\n\n/** Why a worktree cannot be closed, or undefined when it can. */\nexport function refuseClose(input: {\n record: WorktreeRecord | undefined;\n dirtyFiles: readonly string[];\n force: boolean;\n}): string | undefined {\n if (!input.record) return 'No worktree with that id. Call list to see the current ids.';\n if (input.dirtyFiles.length === 0 || input.force) return undefined;\n // Naming the files is the point: \"the tree is dirty\" sends the reader to go\n // look, and the answer is usually a file they forgot rather than one they\n // meant to keep.\n const names = input.dirtyFiles.slice(0, 10).join(', ');\n const more = input.dirtyFiles.length > 10 ? `, and ${String(input.dirtyFiles.length - 10)} more` : '';\n return `${String(input.dirtyFiles.length)} uncommitted file(s): ${names}${more}. Pass force: true to discard them.`;\n}\n\nexport interface Reconciliation {\n records: WorktreeRecord[];\n /** Ids whose status changed, so a caller can report what it noticed. */\n changed: string[];\n}\n\n/**\n * Marks records whose process or directory is gone as orphaned.\n *\n * Nothing is deleted here. A doompi-git orphan owns a directory that may hold\n * uncommitted work, so losing the record would lose the only pointer to it.\n * Deletion is always a separate, named decision.\n */\nexport function reconcile(\n records: readonly WorktreeRecord[],\n probe: { alive: (record: WorktreeRecord) => boolean; exists: (path: string) => boolean },\n): Reconciliation {\n const changed: string[] = [];\n const next = records.map((record) => {\n if (record.status === 'orphaned') return record;\n const gone = !probe.exists(record.path) || !probe.alive(record);\n if (!gone) return record;\n changed.push(record.id);\n return { ...record, status: 'orphaned' as const };\n });\n return { records: next, changed };\n}\n\nexport interface PrunePlan {\n /** Orphans whose directory git still lists, safe to remove. */\n remove: WorktreeRecord[];\n /** Orphans whose directory is already gone; drop the record only. */\n forget: WorktreeRecord[];\n /** Paths git lists under our root that we have no record of; report, never touch. */\n untracked: string[];\n /** Orphans left alone because they still hold uncommitted work. */\n keptDirty: WorktreeRecord[];\n /**\n * Branches git refused to delete because they hold commits.\n *\n * Filled by the prune itself, not by the plan: a dry run destroys nothing, so\n * it has nothing to report here and leaves it empty.\n */\n keptBranches: string[];\n}\n\n/**\n * What a prune would do, decided before anything is destroyed.\n *\n * Separating the plan from the execution is what makes dryRun honest and lets\n * the destructive half be reviewed on its own.\n */\nexport function planPrune(input: {\n records: readonly WorktreeRecord[];\n gitPaths: readonly string[];\n worktreesRoot: string;\n dirtyByPath: ReadonlyMap<string, readonly string[]>;\n}): PrunePlan {\n const plan: PrunePlan = { remove: [], forget: [], untracked: [], keptDirty: [], keptBranches: [] };\n const known = new Set(input.records.map((record) => record.path));\n const listed = new Set(input.gitPaths);\n for (const record of input.records) {\n if (record.status !== 'orphaned') continue;\n if (!listed.has(record.path)) {\n plan.forget.push(record);\n continue;\n }\n if ((input.dirtyByPath.get(record.path) ?? []).length > 0) {\n plan.keptDirty.push(record);\n continue;\n }\n plan.remove.push(record);\n }\n for (const path of input.gitPaths) {\n // Only ever inside our own root: a worktree the user made by hand is none\n // of this package's business, even when it looks abandoned.\n if (path.startsWith(`${input.worktreesRoot}/`) && !known.has(path)) plan.untracked.push(path);\n }\n return plan;\n}\n"],"mappings":"AAmBA,SAAgB,EAAW,EAAwB,CACjD,IAAM,EAAO,EACV,YAAY,CAAC,CACb,QA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,EAAG,OAAQ,CAAC,EAAG,UAAW,CAAC,EAAG,UAAW,CAAC,EAAG,aAAc,CAAC,CAAE,EAC3F,EAAQ,IAAI,IAAI,EAAM,QAAQ,IAAK,GAAW,EAAO,IAAI,CAAC,EAC1D,EAAS,IAAI,IAAI,EAAM,QAAQ,EACrC,IAAK,IAAM,KAAU,EAAM,QACrB,KAAO,SAAW,WACtB,IAAI,CAAC,EAAO,IAAI,EAAO,IAAI,EAAG,CAC5B,EAAK,OAAO,KAAK,CAAM,EACvB,QACF,CACA,IAAK,EAAM,YAAY,IAAI,EAAO,IAAI,GAAK,CAAC,EAAA,CAAG,OAAS,EAAG,CACzD,EAAK,UAAU,KAAK,CAAM,EAC1B,QACF,CACA,EAAK,OAAO,KAAK,CAAM,CALvB,CAOF,IAAK,IAAM,KAAQ,EAAM,SAGnB,EAAK,WAAW,GAAG,EAAM,cAAc,EAAE,GAAK,CAAC,EAAM,IAAI,CAAI,GAAG,EAAK,UAAU,KAAK,CAAI,EAE9F,OAAO,CACT"}
@@ -9,6 +9,13 @@ interface PrunePlan {
9
9
  untracked: string[];
10
10
  /** Orphans left alone because they still hold uncommitted work. */
11
11
  keptDirty: WorktreeRecord[];
12
+ /**
13
+ * Branches git refused to delete because they hold commits.
14
+ *
15
+ * Filled by the prune itself, not by the plan: a dry run destroys nothing, so
16
+ * it has nothing to report here and leaves it empty.
17
+ */
18
+ keptBranches: string[];
12
19
  }
13
20
  /**
14
21
  * What a prune would do, decided before anything is destroyed.
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeNaming.d.cts","names":[],"sources":["../../src/services/worktreeNaming.ts"],"mappings":";;UAoGiB;;EAEf,QAAQ;;EAER,QAAQ;;EAER;;EAEA,WAAW;;;;;;;;iBASG,UAAU;EACxB,kBAAkB;EAClB;EACA;EACA,aAAa;IACX"}
1
+ {"version":3,"file":"worktreeNaming.d.cts","names":[],"sources":["../../src/services/worktreeNaming.ts"],"mappings":";;UAoGiB;;EAEf,QAAQ;;EAER,QAAQ;;EAER;;EAEA,WAAW;;;;;;;EAOX;;;;;;;;iBASc,UAAU;EACxB,kBAAkB;EAClB;EACA;EACA,aAAa;IACX"}
@@ -9,6 +9,13 @@ interface PrunePlan {
9
9
  untracked: string[];
10
10
  /** Orphans left alone because they still hold uncommitted work. */
11
11
  keptDirty: WorktreeRecord[];
12
+ /**
13
+ * Branches git refused to delete because they hold commits.
14
+ *
15
+ * Filled by the prune itself, not by the plan: a dry run destroys nothing, so
16
+ * it has nothing to report here and leaves it empty.
17
+ */
18
+ keptBranches: string[];
12
19
  }
13
20
  /**
14
21
  * What a prune would do, decided before anything is destroyed.
@@ -1 +1 @@
1
- {"version":3,"file":"worktreeNaming.d.mts","names":[],"sources":["../../src/services/worktreeNaming.ts"],"mappings":";;UAoGiB;;EAEf,QAAQ;;EAER,QAAQ;;EAER;;EAEA,WAAW;;;;;;;;iBASG,UAAU;EACxB,kBAAkB;EAClB;EACA;EACA,aAAa;IACX"}
1
+ {"version":3,"file":"worktreeNaming.d.mts","names":[],"sources":["../../src/services/worktreeNaming.ts"],"mappings":";;UAoGiB;;EAEf,QAAQ;;EAER,QAAQ;;EAER;;EAEA,WAAW;;;;;;;EAOX;;;;;;;;iBASc,UAAU;EACxB,kBAAkB;EAClB;EACA;EACA,aAAa;IACX"}
@@ -1,2 +1,2 @@
1
- function e(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/gu,`-`).replace(/^-+|-+$/gu,``).slice(0,64).replace(/-+$/gu,``);return t===``?`worktree`:t}function t(t){let n=`${t.repositoryLabel}--${t.repositoryId}`;return`${t.worktreesRoot}/${n}/${e(t.branch)}--${t.shortId}`}function n(e){if(e.branch.trim()===``)return`A branch name is required.`;let t=e.existing.find(t=>t.branch===e.branch&&t.status!==`orphaned`);if(t)return`Branch ${e.branch} already has a worktree (${t.id}).`}function r(e){if(!e.record)return`No worktree with that id. Call list to see the current ids.`;if(e.dirtyFiles.length===0||e.force)return;let t=e.dirtyFiles.slice(0,10).join(`, `),n=e.dirtyFiles.length>10?`, and ${String(e.dirtyFiles.length-10)} more`:``;return`${String(e.dirtyFiles.length)} uncommitted file(s): ${t}${n}. Pass force: true to discard them.`}function i(e,t){let n=[];return{records:e.map(e=>e.status===`orphaned`||t.exists(e.path)&&t.alive(e)?e:(n.push(e.id),{...e,status:`orphaned`})),changed:n}}function a(e){let t={remove:[],forget:[],untracked:[],keptDirty:[]},n=new Set(e.records.map(e=>e.path)),r=new Set(e.gitPaths);for(let n of e.records)if(n.status===`orphaned`){if(!r.has(n.path)){t.forget.push(n);continue}if((e.dirtyByPath.get(n.path)??[]).length>0){t.keptDirty.push(n);continue}t.remove.push(n)}for(let r of e.gitPaths)r.startsWith(`${e.worktreesRoot}/`)&&!n.has(r)&&t.untracked.push(r);return t}export{e as branchSlug,a as planPrune,i as reconcile,r as refuseClose,n as refuseSpawn,t as worktreeDirectory};
1
+ function e(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/gu,`-`).replace(/^-+|-+$/gu,``).slice(0,64).replace(/-+$/gu,``);return t===``?`worktree`:t}function t(t){let n=`${t.repositoryLabel}--${t.repositoryId}`;return`${t.worktreesRoot}/${n}/${e(t.branch)}--${t.shortId}`}function n(e){if(e.branch.trim()===``)return`A branch name is required.`;let t=e.existing.find(t=>t.branch===e.branch&&t.status!==`orphaned`);if(t)return`Branch ${e.branch} already has a worktree (${t.id}).`}function r(e){if(!e.record)return`No worktree with that id. Call list to see the current ids.`;if(e.dirtyFiles.length===0||e.force)return;let t=e.dirtyFiles.slice(0,10).join(`, `),n=e.dirtyFiles.length>10?`, and ${String(e.dirtyFiles.length-10)} more`:``;return`${String(e.dirtyFiles.length)} uncommitted file(s): ${t}${n}. Pass force: true to discard them.`}function i(e,t){let n=[];return{records:e.map(e=>e.status===`orphaned`||t.exists(e.path)&&t.alive(e)?e:(n.push(e.id),{...e,status:`orphaned`})),changed:n}}function a(e){let t={remove:[],forget:[],untracked:[],keptDirty:[],keptBranches:[]},n=new Set(e.records.map(e=>e.path)),r=new Set(e.gitPaths);for(let n of e.records)if(n.status===`orphaned`){if(!r.has(n.path)){t.forget.push(n);continue}if((e.dirtyByPath.get(n.path)??[]).length>0){t.keptDirty.push(n);continue}t.remove.push(n)}for(let r of e.gitPaths)r.startsWith(`${e.worktreesRoot}/`)&&!n.has(r)&&t.untracked.push(r);return t}export{e as branchSlug,a as planPrune,i as reconcile,r as refuseClose,n as refuseSpawn,t as worktreeDirectory};
2
2
  //# sourceMappingURL=worktreeNaming.mjs.map