@agimon-ai/doompi-git 0.0.1-alpha.11 → 0.0.1-alpha.13

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 (213) hide show
  1. package/README.md +1 -1
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/api-contracts.cjs +7 -0
  4. package/dist/api-contracts.d.cts +2 -0
  5. package/dist/api-contracts.d.mts +2 -0
  6. package/dist/api-contracts.mjs +2 -0
  7. package/dist/extensions/pi.cjs +39 -0
  8. package/dist/extensions/pi.cjs.map +1 -0
  9. package/dist/extensions/pi.d.cts +7 -0
  10. package/dist/extensions/pi.d.cts.map +1 -0
  11. package/dist/extensions/pi.d.mts +7 -0
  12. package/dist/extensions/pi.d.mts.map +1 -0
  13. package/dist/extensions/pi.mjs +34 -0
  14. package/dist/extensions/pi.mjs.map +1 -0
  15. package/dist/extensions/server.cjs +73 -0
  16. package/dist/extensions/server.cjs.map +1 -0
  17. package/dist/extensions/server.d.cts +5 -0
  18. package/dist/extensions/server.d.cts.map +1 -0
  19. package/dist/extensions/server.d.mts +5 -0
  20. package/dist/extensions/server.d.mts.map +1 -0
  21. package/dist/extensions/server.mjs +68 -0
  22. package/dist/extensions/server.mjs.map +1 -0
  23. package/dist/extensions/web.mjs +515 -0
  24. package/dist/extensions/web.mjs.map +1 -0
  25. package/dist/index.cjs +5 -0
  26. package/dist/index.d.cts +4 -0
  27. package/dist/index.d.mts +4 -0
  28. package/dist/index.mjs +3 -0
  29. package/dist/src/constants/git.cjs +8 -0
  30. package/dist/src/constants/git.cjs.map +1 -0
  31. package/dist/src/constants/git.mjs +7 -0
  32. package/dist/src/constants/git.mjs.map +1 -0
  33. package/dist/src/extensions/(backend)/api/_lib/route.server.cjs +93 -0
  34. package/dist/src/extensions/(backend)/api/_lib/route.server.cjs.map +1 -0
  35. package/dist/src/extensions/(backend)/api/_lib/route.server.mjs +92 -0
  36. package/dist/src/extensions/(backend)/api/_lib/route.server.mjs.map +1 -0
  37. package/dist/src/extensions/(backend)/api/route.server.cjs +7 -0
  38. package/dist/src/extensions/(backend)/api/route.server.cjs.map +1 -0
  39. package/dist/src/extensions/(backend)/api/route.server.mjs +8 -0
  40. package/dist/src/extensions/(backend)/api/route.server.mjs.map +1 -0
  41. package/dist/src/extensions/(backend)/channel/_lib/git-worktrees.server.cjs +223 -0
  42. package/dist/src/extensions/(backend)/channel/_lib/git-worktrees.server.cjs.map +1 -0
  43. package/dist/src/extensions/(backend)/channel/_lib/git-worktrees.server.mjs +222 -0
  44. package/dist/src/extensions/(backend)/channel/_lib/git-worktrees.server.mjs.map +1 -0
  45. package/dist/src/extensions/(backend)/channel/git-worktrees.server.cjs +7 -0
  46. package/dist/src/extensions/(backend)/channel/git-worktrees.server.cjs.map +1 -0
  47. package/dist/src/extensions/(backend)/channel/git-worktrees.server.mjs +8 -0
  48. package/dist/src/extensions/(backend)/channel/git-worktrees.server.mjs.map +1 -0
  49. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs +7 -0
  50. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs.map +1 -0
  51. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs +8 -0
  52. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs.map +1 -0
  53. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs +73 -0
  54. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs.map +1 -0
  55. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs +72 -0
  56. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs.map +1 -0
  57. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/git.cli.cjs +17 -0
  58. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/git.cli.cjs.map +1 -0
  59. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/git.cli.mjs +16 -0
  60. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/git.cli.mjs.map +1 -0
  61. package/dist/src/extensions/workspaces/sessions/(backend)/command/git.cli.cjs +7 -0
  62. package/dist/src/extensions/workspaces/sessions/(backend)/command/git.cli.cjs.map +1 -0
  63. package/dist/src/extensions/workspaces/sessions/(backend)/command/git.cli.mjs +8 -0
  64. package/dist/src/extensions/workspaces/sessions/(backend)/command/git.cli.mjs.map +1 -0
  65. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompi-use-git.cli.cjs +15 -0
  66. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompi-use-git.cli.cjs.map +1 -0
  67. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompi-use-git.cli.mjs +15 -0
  68. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompi-use-git.cli.mjs.map +1 -0
  69. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGit.server.cjs +6 -0
  70. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGit.server.cjs.map +1 -0
  71. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGit.server.mjs +6 -0
  72. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGit.server.mjs.map +1 -0
  73. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGitReadme.server.cjs +6 -0
  74. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGitReadme.server.cjs.map +1 -0
  75. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGitReadme.server.mjs +6 -0
  76. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGitReadme.server.mjs.map +1 -0
  77. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiUseGit.server.cjs +6 -0
  78. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiUseGit.server.cjs.map +1 -0
  79. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiUseGit.server.mjs +6 -0
  80. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiUseGit.server.mjs.map +1 -0
  81. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompi-use-git.cli.cjs +7 -0
  82. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompi-use-git.cli.cjs.map +1 -0
  83. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompi-use-git.cli.mjs +8 -0
  84. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompi-use-git.cli.mjs.map +1 -0
  85. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGit.server.cjs +7 -0
  86. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGit.server.cjs.map +1 -0
  87. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGit.server.mjs +8 -0
  88. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGit.server.mjs.map +1 -0
  89. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGitReadme.server.cjs +7 -0
  90. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGitReadme.server.cjs.map +1 -0
  91. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGitReadme.server.mjs +8 -0
  92. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiGitReadme.server.mjs.map +1 -0
  93. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiUseGit.server.cjs +7 -0
  94. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiUseGit.server.cjs.map +1 -0
  95. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiUseGit.server.mjs +8 -0
  96. package/dist/src/extensions/workspaces/sessions/(backend)/resource/doompiUseGit.server.mjs.map +1 -0
  97. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs +7 -0
  98. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs.map +1 -0
  99. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs +8 -0
  100. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs.map +1 -0
  101. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs +7 -0
  102. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs.map +1 -0
  103. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs +8 -0
  104. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs.map +1 -0
  105. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/runWorktree.cli.cjs +38 -0
  106. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/runWorktree.cli.cjs.map +1 -0
  107. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/runWorktree.cli.mjs +36 -0
  108. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/runWorktree.cli.mjs.map +1 -0
  109. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.cli.cjs +7 -0
  110. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.cli.cjs.map +1 -0
  111. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.cli.mjs +8 -0
  112. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.cli.mjs.map +1 -0
  113. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.server.cjs +6 -0
  114. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.server.cjs.map +1 -0
  115. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.server.mjs +7 -0
  116. package/dist/src/extensions/workspaces/sessions/(backend)/tool/runWorktree.server.mjs.map +1 -0
  117. package/dist/src/schemas/apiContracts.cjs +143 -0
  118. package/dist/src/schemas/apiContracts.cjs.map +1 -0
  119. package/dist/src/schemas/apiContracts.d.cts +53 -0
  120. package/dist/src/schemas/apiContracts.d.cts.map +1 -0
  121. package/dist/src/schemas/apiContracts.d.mts +53 -0
  122. package/dist/src/schemas/apiContracts.d.mts.map +1 -0
  123. package/dist/src/schemas/apiContracts.mjs +140 -0
  124. package/dist/src/schemas/apiContracts.mjs.map +1 -0
  125. package/dist/src/schemas/runWorktreeTool.cjs +152 -0
  126. package/dist/src/schemas/runWorktreeTool.cjs.map +1 -0
  127. package/dist/src/schemas/runWorktreeTool.mjs +150 -0
  128. package/dist/src/schemas/runWorktreeTool.mjs.map +1 -0
  129. package/dist/src/services/atomicJson/index.cjs +42 -0
  130. package/dist/src/services/atomicJson/index.cjs.map +1 -0
  131. package/dist/src/services/atomicJson/index.mjs +38 -0
  132. package/dist/src/services/atomicJson/index.mjs.map +1 -0
  133. package/dist/src/services/compositionMirror/index.cjs +119 -0
  134. package/dist/src/services/compositionMirror/index.cjs.map +1 -0
  135. package/dist/src/services/compositionMirror/index.mjs +116 -0
  136. package/dist/src/services/compositionMirror/index.mjs.map +1 -0
  137. package/dist/src/services/errors/index.cjs +29 -0
  138. package/dist/src/services/errors/index.cjs.map +1 -0
  139. package/dist/src/services/errors/index.mjs +27 -0
  140. package/dist/src/services/errors/index.mjs.map +1 -0
  141. package/dist/src/services/extensionService/index.cjs +13 -0
  142. package/dist/src/services/extensionService/index.cjs.map +1 -0
  143. package/dist/src/services/extensionService/index.d.cts +7 -0
  144. package/dist/src/services/extensionService/index.d.cts.map +1 -0
  145. package/dist/src/services/extensionService/index.d.mts +7 -0
  146. package/dist/src/services/extensionService/index.d.mts.map +1 -0
  147. package/dist/src/services/extensionService/index.mjs +13 -0
  148. package/dist/src/services/extensionService/index.mjs.map +1 -0
  149. package/dist/src/services/gitCli/index.cjs +144 -0
  150. package/dist/src/services/gitCli/index.cjs.map +1 -0
  151. package/dist/src/services/gitCli/index.mjs +142 -0
  152. package/dist/src/services/gitCli/index.mjs.map +1 -0
  153. package/dist/src/services/gitDependencies/index.cjs +14 -0
  154. package/dist/src/services/gitDependencies/index.cjs.map +1 -0
  155. package/dist/src/services/gitDependencies/index.d.cts +5 -0
  156. package/dist/src/services/gitDependencies/index.d.cts.map +1 -0
  157. package/dist/src/services/gitDependencies/index.d.mts +5 -0
  158. package/dist/src/services/gitDependencies/index.d.mts.map +1 -0
  159. package/dist/src/services/gitDependencies/index.mjs +14 -0
  160. package/dist/src/services/gitDependencies/index.mjs.map +1 -0
  161. package/dist/src/services/paths/index.cjs +66 -0
  162. package/dist/src/services/paths/index.cjs.map +1 -0
  163. package/dist/src/services/paths/index.mjs +60 -0
  164. package/dist/src/services/paths/index.mjs.map +1 -0
  165. package/dist/src/services/repositoryIdentity/index.cjs +71 -0
  166. package/dist/src/services/repositoryIdentity/index.cjs.map +1 -0
  167. package/dist/src/services/repositoryIdentity/index.mjs +65 -0
  168. package/dist/src/services/repositoryIdentity/index.mjs.map +1 -0
  169. package/dist/src/services/runWorktree/index.cjs +146 -0
  170. package/dist/src/services/runWorktree/index.cjs.map +1 -0
  171. package/dist/src/services/runWorktree/index.mjs +143 -0
  172. package/dist/src/services/runWorktree/index.mjs.map +1 -0
  173. package/dist/src/services/worktreeEvents/index.cjs +64 -0
  174. package/dist/src/services/worktreeEvents/index.cjs.map +1 -0
  175. package/dist/src/services/worktreeEvents/index.d.cts +14 -0
  176. package/dist/src/services/worktreeEvents/index.d.cts.map +1 -0
  177. package/dist/src/services/worktreeEvents/index.d.mts +14 -0
  178. package/dist/src/services/worktreeEvents/index.d.mts.map +1 -0
  179. package/dist/src/services/worktreeEvents/index.mjs +60 -0
  180. package/dist/src/services/worktreeEvents/index.mjs.map +1 -0
  181. package/dist/src/services/worktreeNaming/index.cjs +99 -0
  182. package/dist/src/services/worktreeNaming/index.cjs.map +1 -0
  183. package/dist/src/services/worktreeNaming/index.d.cts +33 -0
  184. package/dist/src/services/worktreeNaming/index.d.cts.map +1 -0
  185. package/dist/src/services/worktreeNaming/index.d.mts +33 -0
  186. package/dist/src/services/worktreeNaming/index.d.mts.map +1 -0
  187. package/dist/src/services/worktreeNaming/index.mjs +94 -0
  188. package/dist/src/services/worktreeNaming/index.mjs.map +1 -0
  189. package/dist/src/services/worktreeOperations/index.cjs +324 -0
  190. package/dist/src/services/worktreeOperations/index.cjs.map +1 -0
  191. package/dist/src/services/worktreeOperations/index.d.cts +39 -0
  192. package/dist/src/services/worktreeOperations/index.d.cts.map +1 -0
  193. package/dist/src/services/worktreeOperations/index.d.mts +39 -0
  194. package/dist/src/services/worktreeOperations/index.d.mts.map +1 -0
  195. package/dist/src/services/worktreeOperations/index.mjs +322 -0
  196. package/dist/src/services/worktreeOperations/index.mjs.map +1 -0
  197. package/dist/src/services/worktreeRegistry/index.cjs +38 -0
  198. package/dist/src/services/worktreeRegistry/index.cjs.map +1 -0
  199. package/dist/src/services/worktreeRegistry/index.mjs +38 -0
  200. package/dist/src/services/worktreeRegistry/index.mjs.map +1 -0
  201. package/dist/src/types/extension.d.cts +16 -0
  202. package/dist/src/types/extension.d.cts.map +1 -0
  203. package/dist/src/types/extension.d.mts +16 -0
  204. package/dist/src/types/extension.d.mts.map +1 -0
  205. package/dist/src/types/webWorktrees.cjs +20 -0
  206. package/dist/src/types/webWorktrees.cjs.map +1 -0
  207. package/dist/src/types/webWorktrees.mjs +20 -0
  208. package/dist/src/types/webWorktrees.mjs.map +1 -0
  209. package/dist/src/types/worktreeRegistry.d.cts +40 -0
  210. package/dist/src/types/worktreeRegistry.d.cts.map +1 -0
  211. package/dist/src/types/worktreeRegistry.d.mts +40 -0
  212. package/dist/src/types/worktreeRegistry.d.mts.map +1 -0
  213. package/package.json +6 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["mirrorComposition","HubUnavailableError","fs","DoomGitExpectedError","createWorktreeRegistry","registryFile","require","refuseSpawn","shortId","randomUUID","worktreeDirectory","worktreesRoot","repositoryLabel","repositoryId","refuseClose","reconcile","MAX_WORKTREE_MESSAGE_BYTES","planPrune"],"sources":["../../../../src/services/worktreeOperations/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\n\nimport type { DoomHubSessionService } from '@agimon-ai/doompi-core/hub-channel';\nimport type { DoomSessionDeliveryService } from '@agimon-ai/doompi-session';\n\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry';\nimport { mirrorComposition } from '../compositionMirror';\nimport { DoomGitExpectedError, HubUnavailableError } from '../errors';\nimport { registryFile, worktreesRoot } from '../paths';\nimport { repositoryId, repositoryLabel, shortId } from '../repositoryIdentity';\nimport { MAX_WORKTREE_MESSAGE_BYTES, type WorktreeMessageInbox, type WorktreeMessageParty } from '../worktreeEvents';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../worktreeNaming';\nimport { createWorktreeRegistry } from '../worktreeRegistry';\n\nconst GIT_WORKTREE_DELEGATION_KIND = 'git.worktree.delegation';\nconst GIT_WORKTREE_MESSAGE_KIND = 'git.worktree.message';\nconst GIT_WORKTREE_REPORT_KIND = 'git.worktree.report';\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 task?: 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<import('../worktreeEvents').WorktreeMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** The canonical hub-owned session lifecycle. */\n sessionService?: DoomHubSessionService;\n /** Legacy in-memory fallback used outside the fixed Session composition. */\n messageInbox?: WorktreeMessageInbox;\n /** Reads the active Session provider when an operation executes. */\n sessionDelivery?: () => DoomSessionDeliveryService | undefined;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n homeDir?: 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 sessionService = deps.sessionService;\n const mirror = deps.mirror ?? mirrorComposition;\n const now = deps.now ?? (() => new Date());\n const requireSessionService = (): DoomHubSessionService => {\n if (sessionService === undefined)\n throw new HubUnavailableError('The cockpit session service is unavailable. Start the cockpit and try again.');\n return sessionService;\n };\n const requireMessageInbox = (): WorktreeMessageInbox => {\n if (deps.messageInbox === undefined)\n throw new HubUnavailableError('The Git message service is unavailable. Start the cockpit and try again.');\n return deps.messageInbox;\n };\n const readSessionDelivery = (): DoomSessionDeliveryService | undefined => deps.sessionDelivery?.();\n const requireSessionDelivery = (): DoomSessionDeliveryService => {\n const delivery = readSessionDelivery();\n if (delivery === undefined)\n throw new HubUnavailableError('The Session delivery service is unavailable. Start the cockpit and try again.');\n return delivery;\n };\n const probe = {\n alive: (record: WorktreeRecord) => requireSessionService().isLive(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 * worktree registry is shared and another process may have written it since\n * 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 (!requireSessionService().isLive(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 const peerFor = (\n context: WorktreeContext,\n record: WorktreeRecord,\n ): { sessionId: string; party: WorktreeMessageParty } => {\n if (context.sessionId === record.parentSessionId) return { sessionId: record.sessionId, party: 'parent' };\n if (context.sessionId === record.sessionId) return { sessionId: record.parentSessionId, party: 'child' };\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n 'Use a worktree owned by this session.',\n );\n };\n\n const requirePeerLive = (peerSessionId: string): void => {\n if (!requireSessionService().isLive(peerSessionId)) {\n throw new DoomGitExpectedError(\n 'worktree_peer_unavailable',\n 'The other worktree session is no longer live.',\n false,\n 'Start a new worktree session before sending a message.',\n );\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 taskDelivery = request.task === undefined ? undefined : requireSessionDelivery();\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 const session = await requireSessionService().create({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n sessionProvenance: 'worktree',\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n sessionId = session.sessionId;\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 requireSessionService()\n .close(sessionId)\n .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 if (request.task !== undefined && taskDelivery !== undefined) {\n try {\n const receipt = await taskDelivery.deliver({\n recipientKey: sessionId,\n kind: GIT_WORKTREE_DELEGATION_KIND,\n prompt: request.task,\n metadata: {\n worktreeId: record.id,\n fromRole: 'parent',\n text: request.task,\n sentAt: record.createdAt,\n },\n });\n const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new Error(\n admission === 'recovery_required'\n ? 'The recipient could not admit the task.'\n : 'The recipient did not confirm task admission before the timeout.',\n );\n }\n } catch (error) {\n throw new DoomGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created, but its task admission was not confirmed (${(error as Error).message}).`,\n true,\n `Use send with worktree ${record.id} to deliver the task without recreating the worktree.`,\n );\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 requireSessionService().close(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 /** Sends only between the parent session and its own worktree session. */\n async send(context, id, message) {\n if (Buffer.byteLength(message, 'utf8') > MAX_WORKTREE_MESSAGE_BYTES) {\n throw new DoomGitExpectedError(\n 'message_too_large',\n `A message may not exceed ${String(MAX_WORKTREE_MESSAGE_BYTES)} bytes.`,\n false,\n 'Send a shorter message.',\n );\n }\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n requirePeerLive(peer.sessionId);\n const sentAt = new Date().toISOString();\n const delivery = readSessionDelivery();\n if (delivery !== undefined) {\n const kind = peer.party === 'parent' ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;\n const receipt = await delivery.deliver({\n recipientKey: peer.sessionId,\n kind,\n prompt:\n peer.party === 'parent'\n ? `Parent message for worktree ${record.id}:\\n\\n${message}`\n : `Report from worktree ${record.id}:\\n\\n${message}`,\n metadata: { worktreeId: record.id, fromRole: peer.party, text: message, sentAt },\n });\n const admission = await delivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new DoomGitExpectedError(\n 'message_delivery_failed',\n `Worktree ${record.id} persisted the message, but its session did not confirm admission.`,\n true,\n admission === 'recovery_required'\n ? 'Call messages from the recipient session to recover the persisted text.'\n : 'The message remains durable; retry after the recipient is ready.',\n );\n }\n return;\n }\n requireMessageInbox().send(peer.sessionId, {\n version: 1,\n worktreeId: record.id,\n fromSessionId: context.sessionId,\n from: peer.party,\n text: message,\n sentAt,\n });\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n const delivery = readSessionDelivery();\n if (delivery === undefined) return requireMessageInbox().receive(record.id);\n const entries = delivery\n .inbox({ consumed: false, metadata: { worktreeId: record.id } })\n .filter(\n (entry) =>\n entry.senderKey === peer.sessionId &&\n (entry.state === 'admitted' || entry.state === 'recovery_required') &&\n (peer.party === 'parent'\n ? entry.kind === GIT_WORKTREE_REPORT_KIND\n : entry.kind === GIT_WORKTREE_MESSAGE_KIND || entry.kind === GIT_WORKTREE_DELEGATION_KIND),\n );\n return entries.map((entry) => {\n delivery.consume(entry.deliveryId);\n return {\n version: 1,\n worktreeId: record.id,\n fromSessionId: entry.senderKey,\n from: peer.party === 'parent' ? ('child' as const) : ('parent' as const),\n text:\n entry.state === 'recovery_required'\n ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}`\n : (entry.metadata.text ?? entry.prompt),\n sentAt: entry.metadata.sentAt ?? '',\n };\n });\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":";;;;;;;;;;;;AAgBA,MAAM,+BAA+B;AACrC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AAgDjC,SAAgB,yBAAyB,MAAkD;CACzF,MAAM,EAAE,QAAQ;CAChB,MAAM,iBAAiB,KAAK;CAC5B,MAAM,SAAS,KAAK,UAAUA,cAAAA;CAC9B,MAAM,MAAM,KAAK,8BAAc,IAAI,KAAK;CACxC,MAAM,8BAAqD;EACzD,IAAI,mBAAmB,KAAA,GACrB,MAAM,IAAIC,gBAAAA,oBAAoB,8EAA8E;EAC9G,OAAO;CACT;CACA,MAAM,4BAAkD;EACtD,IAAI,KAAK,iBAAiB,KAAA,GACxB,MAAM,IAAIA,gBAAAA,oBAAoB,0EAA0E;EAC1G,OAAO,KAAK;CACd;CACA,MAAM,4BAAoE,KAAK,kBAAkB;CACjG,MAAM,+BAA2D;EAC/D,MAAM,WA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AQ,IAAI,OAAO,EAAE,CAAC,CAAC;GAC5E,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,39 @@
1
+ import { WorktreeMessage } from "../worktreeEvents/index.cjs";
2
+ import { WorktreeRecord } from "../../types/worktreeRegistry.cjs";
3
+ import { planPrune } from "../worktreeNaming/index.cjs";
4
+ import "@agimon-ai/doompi-core/hub-channel";
5
+ import "@agimon-ai/doompi-session";
6
+ //#region src/services/worktreeOperations/index.d.ts
7
+ export interface WorktreeContext {
8
+ /** Where the calling session is working, used to find the repository. */
9
+ cwd: string;
10
+ /** The calling session, recorded as the new session's parent. */
11
+ sessionId: string;
12
+ }
13
+ export interface SpawnWorktreeRequest {
14
+ branch: string;
15
+ baseRef?: string;
16
+ name?: string;
17
+ task?: string;
18
+ }
19
+ export interface SpawnOptions {
20
+ /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */
21
+ signal?: AbortSignal;
22
+ /** Phase labels, for a caller that can show them while the work runs. */
23
+ onProgress?: (label: string) => void;
24
+ }
25
+ export interface WorktreeOperations {
26
+ spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;
27
+ close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;
28
+ list(context: WorktreeContext): Promise<WorktreeRecord[]>;
29
+ status(context: WorktreeContext, id: string): Promise<{
30
+ record: WorktreeRecord;
31
+ dirtyFiles: string[];
32
+ }>;
33
+ merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;
34
+ prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;
35
+ send(context: WorktreeContext, id: string, message: string): Promise<void>;
36
+ messages(context: WorktreeContext, id: string): Promise<WorktreeMessage[]>;
37
+ }
38
+ //#endregion
39
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../../src/services/worktreeOperations/index.ts"],"mappings":";;;;;;iBAmBiB;;EAEf;;EAEA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;;EAEf,SAAS;;EAET,cAAc;;iBAGC;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,QAA9B"}
@@ -0,0 +1,39 @@
1
+ import { WorktreeMessage } from "../worktreeEvents/index.mjs";
2
+ import { WorktreeRecord } from "../../types/worktreeRegistry.mjs";
3
+ import { planPrune } from "../worktreeNaming/index.mjs";
4
+ import "@agimon-ai/doompi-session";
5
+ import "@agimon-ai/doompi-core/hub-channel";
6
+ //#region src/services/worktreeOperations/index.d.ts
7
+ export interface WorktreeContext {
8
+ /** Where the calling session is working, used to find the repository. */
9
+ cwd: string;
10
+ /** The calling session, recorded as the new session's parent. */
11
+ sessionId: string;
12
+ }
13
+ export interface SpawnWorktreeRequest {
14
+ branch: string;
15
+ baseRef?: string;
16
+ name?: string;
17
+ task?: string;
18
+ }
19
+ export interface SpawnOptions {
20
+ /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */
21
+ signal?: AbortSignal;
22
+ /** Phase labels, for a caller that can show them while the work runs. */
23
+ onProgress?: (label: string) => void;
24
+ }
25
+ export interface WorktreeOperations {
26
+ spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;
27
+ close(context: WorktreeContext, id: string, force: boolean): Promise<WorktreeRecord>;
28
+ list(context: WorktreeContext): Promise<WorktreeRecord[]>;
29
+ status(context: WorktreeContext, id: string): Promise<{
30
+ record: WorktreeRecord;
31
+ dirtyFiles: string[];
32
+ }>;
33
+ merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;
34
+ prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;
35
+ send(context: WorktreeContext, id: string, message: string): Promise<void>;
36
+ messages(context: WorktreeContext, id: string): Promise<WorktreeMessage[]>;
37
+ }
38
+ //#endregion
39
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/services/worktreeOperations/index.ts"],"mappings":";;;;;;iBAmBiB;;EAEf;;EAEA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;;EAEf,SAAS;;EAET,cAAc;;iBAGC;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,QAA9B"}
@@ -0,0 +1,322 @@
1
+ import { mirrorComposition } from "../compositionMirror/index.mjs";
2
+ import { DoomGitExpectedError, HubUnavailableError } from "../errors/index.mjs";
3
+ import { repositoryId, repositoryLabel, shortId } from "../repositoryIdentity/index.mjs";
4
+ import { registryFile, worktreesRoot } from "../paths/index.mjs";
5
+ import { MAX_WORKTREE_MESSAGE_BYTES } from "../worktreeEvents/index.mjs";
6
+ import { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from "../worktreeNaming/index.mjs";
7
+ import { createWorktreeRegistry } from "../worktreeRegistry/index.mjs";
8
+ import fs from "node:fs";
9
+ import { randomUUID } from "node:crypto";
10
+ //#region src/services/worktreeOperations/index.ts
11
+ const GIT_WORKTREE_DELEGATION_KIND = "git.worktree.delegation";
12
+ const GIT_WORKTREE_MESSAGE_KIND = "git.worktree.message";
13
+ const GIT_WORKTREE_REPORT_KIND = "git.worktree.report";
14
+ function createWorktreeOperations(deps) {
15
+ const { git } = deps;
16
+ const sessionService = deps.sessionService;
17
+ const mirror = deps.mirror ?? mirrorComposition;
18
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
19
+ const requireSessionService = () => {
20
+ if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
21
+ return sessionService;
22
+ };
23
+ const requireMessageInbox = () => {
24
+ if (deps.messageInbox === void 0) throw new HubUnavailableError("The Git message service is unavailable. Start the cockpit and try again.");
25
+ return deps.messageInbox;
26
+ };
27
+ const readSessionDelivery = () => deps.sessionDelivery?.();
28
+ const requireSessionDelivery = () => {
29
+ const delivery = readSessionDelivery();
30
+ if (delivery === void 0) throw new HubUnavailableError("The Session delivery service is unavailable. Start the cockpit and try again.");
31
+ return delivery;
32
+ };
33
+ const probe = {
34
+ alive: (record) => requireSessionService().isLive(record.sessionId),
35
+ exists: (path) => fs.existsSync(path)
36
+ };
37
+ /**
38
+ * Everything an action needs about the repository it is acting on.
39
+ *
40
+ * Resolved per call rather than cached: a session's cwd is stable, but the
41
+ * worktree registry is shared and another process may have written it since
42
+ * the last call.
43
+ */
44
+ const resolve = async (context) => {
45
+ const root = await git.repositoryRoot(context.cwd);
46
+ if (root === void 0) throw new DoomGitExpectedError("not_a_repository", `${context.cwd} is not inside a git repository.`, false, "Run this from a repository checkout.");
47
+ const store = createWorktreeRegistry(registryFile(root, deps.homeDir));
48
+ return {
49
+ root,
50
+ store,
51
+ records: store.list()
52
+ };
53
+ };
54
+ const require = (records, id) => {
55
+ const record = records.find((entry) => entry.id === id);
56
+ if (record === void 0) throw new DoomGitExpectedError("worktree_not_found", `No worktree with id ${id}.`, false, "Call list to see the current ids.");
57
+ return record;
58
+ };
59
+ /**
60
+ * Refuses to destroy or merge a worktree another live session is using.
61
+ *
62
+ * `parentSessionId` records who asked for the worktree. Two sessions in one
63
+ * checkout share this registry, so without the check either could close the
64
+ * other's work in progress by id.
65
+ *
66
+ * Once that session is gone there is no owner left to protect, and refusing
67
+ * would strand the worktree: nothing else could ever close it.
68
+ */
69
+ const requireOwner = (context, record, action) => {
70
+ if (record.parentSessionId === context.sessionId) return;
71
+ if (!requireSessionService().isLive(record.parentSessionId)) return;
72
+ throw new DoomGitExpectedError("worktree_not_owned", `Worktree ${record.id} belongs to another session.`, false, `Ask the session that created it to ${action} it, or close that session first.`);
73
+ };
74
+ const peerFor = (context, record) => {
75
+ if (context.sessionId === record.parentSessionId) return {
76
+ sessionId: record.sessionId,
77
+ party: "parent"
78
+ };
79
+ if (context.sessionId === record.sessionId) return {
80
+ sessionId: record.parentSessionId,
81
+ party: "child"
82
+ };
83
+ throw new DoomGitExpectedError("worktree_not_owned", `Worktree ${record.id} belongs to another session.`, false, "Use a worktree owned by this session.");
84
+ };
85
+ const requirePeerLive = (peerSessionId) => {
86
+ if (!requireSessionService().isLive(peerSessionId)) throw new DoomGitExpectedError("worktree_peer_unavailable", "The other worktree session is no longer live.", false, "Start a new worktree session before sending a message.");
87
+ };
88
+ return {
89
+ async spawn(context, request, options) {
90
+ const { root, store, records } = await resolve(context);
91
+ const refusal = refuseSpawn({
92
+ branch: request.branch,
93
+ existing: records
94
+ });
95
+ if (refusal !== void 0) throw new DoomGitExpectedError("worktree_exists", refusal, false, "Pick another branch name, or close it.");
96
+ const taskDelivery = request.task === void 0 ? void 0 : requireSessionDelivery();
97
+ const baseRef = request.baseRef ?? await git.currentBranch(root) ?? "HEAD";
98
+ const id = shortId(randomUUID());
99
+ const path = worktreeDirectory({
100
+ worktreesRoot: worktreesRoot(deps.homeDir),
101
+ repositoryLabel: repositoryLabel(root),
102
+ repositoryId: repositoryId(root),
103
+ branch: request.branch,
104
+ shortId: id
105
+ });
106
+ const cancelled = () => options?.signal?.aborted === true;
107
+ const rollback = async () => {
108
+ await git.removeWorktree({
109
+ repositoryRoot: root,
110
+ path,
111
+ force: true
112
+ }).catch(() => void 0);
113
+ return await git.deleteBranch({
114
+ repositoryRoot: root,
115
+ branch: request.branch
116
+ }).catch(() => false) ? "" : ` The branch ${request.branch} has work on it and was kept.`;
117
+ };
118
+ options?.onProgress?.(`creating branch ${request.branch}\u2026`);
119
+ await git.addWorktree({
120
+ repositoryRoot: root,
121
+ path,
122
+ branch: request.branch,
123
+ baseRef
124
+ });
125
+ if (cancelled()) {
126
+ const kept = await rollback();
127
+ throw new DoomGitExpectedError("spawn_cancelled", `Cancelled before the session started.${kept}`, false, "The worktree was removed; run it again when you are ready.");
128
+ }
129
+ options?.onProgress?.("mirroring build output…");
130
+ mirror(root, path);
131
+ options?.onProgress?.("starting session…");
132
+ let sessionId;
133
+ try {
134
+ sessionId = (await requireSessionService().create({
135
+ cwd: path,
136
+ name: request.name ?? request.branch,
137
+ parentSessionId: context.sessionId,
138
+ sessionProvenance: "worktree",
139
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
140
+ })).sessionId;
141
+ } catch (error) {
142
+ const kept = await rollback();
143
+ if (cancelled()) throw new DoomGitExpectedError("spawn_cancelled", `Cancelled while the session was starting.${kept}`, false, "The worktree was removed; run it again when you are ready.");
144
+ if (error instanceof HubUnavailableError) throw new DoomGitExpectedError("hub_unavailable", `${error.message}${kept}`, true, "Start the cockpit and try again.");
145
+ throw error;
146
+ }
147
+ const record = {
148
+ version: 1,
149
+ id,
150
+ branch: request.branch,
151
+ baseRef,
152
+ path,
153
+ repositoryRoot: root,
154
+ sessionId,
155
+ parentSessionId: context.sessionId,
156
+ status: "running",
157
+ createdAt: now().toISOString()
158
+ };
159
+ try {
160
+ store.replace([...records, record]);
161
+ } catch (error) {
162
+ await requireSessionService().close(sessionId).catch(() => void 0);
163
+ const kept = await rollback();
164
+ throw new DoomGitExpectedError("registry_write_failed", `The worktree was created but the registry could not be written (${error.message}).${kept}`, true, "Check the registry file for permissions or free space, then try again.");
165
+ }
166
+ if (request.task !== void 0 && taskDelivery !== void 0) try {
167
+ const receipt = await taskDelivery.deliver({
168
+ recipientKey: sessionId,
169
+ kind: GIT_WORKTREE_DELEGATION_KIND,
170
+ prompt: request.task,
171
+ metadata: {
172
+ worktreeId: record.id,
173
+ fromRole: "parent",
174
+ text: request.task,
175
+ sentAt: record.createdAt
176
+ }
177
+ });
178
+ const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);
179
+ if (admission !== "admitted") throw new Error(admission === "recovery_required" ? "The recipient could not admit the task." : "The recipient did not confirm task admission before the timeout.");
180
+ } catch (error) {
181
+ throw new DoomGitExpectedError("task_delivery_failed", `Worktree ${record.id} was created, but its task admission was not confirmed (${error.message}).`, true, `Use send with worktree ${record.id} to deliver the task without recreating the worktree.`);
182
+ }
183
+ return record;
184
+ },
185
+ async close(context, id, force) {
186
+ const { root, store, records } = await resolve(context);
187
+ const record = require(records, id);
188
+ requireOwner(context, record, "close");
189
+ const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];
190
+ const refusal = refuseClose({
191
+ record,
192
+ dirtyFiles,
193
+ force
194
+ });
195
+ if (refusal !== void 0) throw new DoomGitExpectedError("worktree_dirty", refusal, false, "Commit the work, or pass force: true.");
196
+ await requireSessionService().close(record.sessionId);
197
+ await git.removeWorktree({
198
+ repositoryRoot: root,
199
+ path: record.path,
200
+ force
201
+ });
202
+ store.replace(records.filter((entry) => entry.id !== id));
203
+ return record;
204
+ },
205
+ async list(context) {
206
+ const { store, records } = await resolve(context);
207
+ const outcome = reconcile(records, probe);
208
+ if (outcome.changed.length > 0) store.replace(outcome.records);
209
+ return outcome.records;
210
+ },
211
+ async status(context, id) {
212
+ const { records } = await resolve(context);
213
+ const record = require(records, id);
214
+ return {
215
+ record,
216
+ dirtyFiles: fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : []
217
+ };
218
+ },
219
+ async merge(context, id, message) {
220
+ const { root, records } = await resolve(context);
221
+ const record = require(records, id);
222
+ requireOwner(context, record, "merge");
223
+ const parentDirty = await git.dirtyFiles(root);
224
+ if (parentDirty.length > 0) throw new DoomGitExpectedError("worktree_dirty", `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(", ")}.`, false, "Commit or stash the parent checkout first.");
225
+ await git.mergeBranch({
226
+ repositoryRoot: root,
227
+ branch: record.branch,
228
+ ...message === void 0 ? {} : { message }
229
+ });
230
+ return record;
231
+ },
232
+ /** Sends only between the parent session and its own worktree session. */
233
+ async send(context, id, message) {
234
+ if (Buffer.byteLength(message, "utf8") > 65536) throw new DoomGitExpectedError("message_too_large", `A message may not exceed ${String(MAX_WORKTREE_MESSAGE_BYTES)} bytes.`, false, "Send a shorter message.");
235
+ const { records } = await resolve(context);
236
+ const record = require(records, id);
237
+ const peer = peerFor(context, record);
238
+ requirePeerLive(peer.sessionId);
239
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
240
+ const delivery = readSessionDelivery();
241
+ if (delivery !== void 0) {
242
+ const kind = peer.party === "parent" ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;
243
+ const receipt = await delivery.deliver({
244
+ recipientKey: peer.sessionId,
245
+ kind,
246
+ prompt: peer.party === "parent" ? `Parent message for worktree ${record.id}:\n\n${message}` : `Report from worktree ${record.id}:\n\n${message}`,
247
+ metadata: {
248
+ worktreeId: record.id,
249
+ fromRole: peer.party,
250
+ text: message,
251
+ sentAt
252
+ }
253
+ });
254
+ const admission = await delivery.waitForAdmission(receipt.deliveryId);
255
+ if (admission !== "admitted") throw new DoomGitExpectedError("message_delivery_failed", `Worktree ${record.id} persisted the message, but its session did not confirm admission.`, true, admission === "recovery_required" ? "Call messages from the recipient session to recover the persisted text." : "The message remains durable; retry after the recipient is ready.");
256
+ return;
257
+ }
258
+ requireMessageInbox().send(peer.sessionId, {
259
+ version: 1,
260
+ worktreeId: record.id,
261
+ fromSessionId: context.sessionId,
262
+ from: peer.party,
263
+ text: message,
264
+ sentAt
265
+ });
266
+ },
267
+ async messages(context, id) {
268
+ const { records } = await resolve(context);
269
+ const record = require(records, id);
270
+ const peer = peerFor(context, record);
271
+ const delivery = readSessionDelivery();
272
+ if (delivery === void 0) return requireMessageInbox().receive(record.id);
273
+ return delivery.inbox({
274
+ consumed: false,
275
+ metadata: { worktreeId: record.id }
276
+ }).filter((entry) => entry.senderKey === peer.sessionId && (entry.state === "admitted" || entry.state === "recovery_required") && (peer.party === "parent" ? entry.kind === GIT_WORKTREE_REPORT_KIND : entry.kind === GIT_WORKTREE_MESSAGE_KIND || entry.kind === GIT_WORKTREE_DELEGATION_KIND)).map((entry) => {
277
+ delivery.consume(entry.deliveryId);
278
+ return {
279
+ version: 1,
280
+ worktreeId: record.id,
281
+ fromSessionId: entry.senderKey,
282
+ from: peer.party === "parent" ? "child" : "parent",
283
+ text: entry.state === "recovery_required" ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}` : entry.metadata.text ?? entry.prompt,
284
+ sentAt: entry.metadata.sentAt ?? ""
285
+ };
286
+ });
287
+ },
288
+ async prune(context, dryRun) {
289
+ const { root, store, records } = await resolve(context);
290
+ const reconciled = reconcile(records, probe);
291
+ const gitPaths = await git.listWorktreePaths(root);
292
+ const dirtyByPath = /* @__PURE__ */ new Map();
293
+ for (const record of reconciled.records) if (record.status === "orphaned" && fs.existsSync(record.path)) dirtyByPath.set(record.path, await git.dirtyFiles(record.path));
294
+ const plan = planPrune({
295
+ records: reconciled.records,
296
+ gitPaths,
297
+ worktreesRoot: worktreesRoot(deps.homeDir),
298
+ dirtyByPath
299
+ });
300
+ if (dryRun) {
301
+ store.replace(reconciled.records);
302
+ return plan;
303
+ }
304
+ for (const record of plan.remove) await git.removeWorktree({
305
+ repositoryRoot: root,
306
+ path: record.path,
307
+ force: false
308
+ });
309
+ for (const record of [...plan.remove, ...plan.forget]) if (!await git.deleteBranch({
310
+ repositoryRoot: root,
311
+ branch: record.branch
312
+ }).catch(() => false)) plan.keptBranches.push(record.branch);
313
+ const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));
314
+ store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));
315
+ return plan;
316
+ }
317
+ };
318
+ }
319
+ //#endregion
320
+ export { createWorktreeOperations };
321
+
322
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/worktreeOperations/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\n\nimport type { DoomHubSessionService } from '@agimon-ai/doompi-core/hub-channel';\nimport type { DoomSessionDeliveryService } from '@agimon-ai/doompi-session';\n\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry';\nimport { mirrorComposition } from '../compositionMirror';\nimport { DoomGitExpectedError, HubUnavailableError } from '../errors';\nimport { registryFile, worktreesRoot } from '../paths';\nimport { repositoryId, repositoryLabel, shortId } from '../repositoryIdentity';\nimport { MAX_WORKTREE_MESSAGE_BYTES, type WorktreeMessageInbox, type WorktreeMessageParty } from '../worktreeEvents';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, worktreeDirectory } from '../worktreeNaming';\nimport { createWorktreeRegistry } from '../worktreeRegistry';\n\nconst GIT_WORKTREE_DELEGATION_KIND = 'git.worktree.delegation';\nconst GIT_WORKTREE_MESSAGE_KIND = 'git.worktree.message';\nconst GIT_WORKTREE_REPORT_KIND = 'git.worktree.report';\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 task?: 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<import('../worktreeEvents').WorktreeMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n /** The canonical hub-owned session lifecycle. */\n sessionService?: DoomHubSessionService;\n /** Legacy in-memory fallback used outside the fixed Session composition. */\n messageInbox?: WorktreeMessageInbox;\n /** Reads the active Session provider when an operation executes. */\n sessionDelivery?: () => DoomSessionDeliveryService | undefined;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n homeDir?: 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 sessionService = deps.sessionService;\n const mirror = deps.mirror ?? mirrorComposition;\n const now = deps.now ?? (() => new Date());\n const requireSessionService = (): DoomHubSessionService => {\n if (sessionService === undefined)\n throw new HubUnavailableError('The cockpit session service is unavailable. Start the cockpit and try again.');\n return sessionService;\n };\n const requireMessageInbox = (): WorktreeMessageInbox => {\n if (deps.messageInbox === undefined)\n throw new HubUnavailableError('The Git message service is unavailable. Start the cockpit and try again.');\n return deps.messageInbox;\n };\n const readSessionDelivery = (): DoomSessionDeliveryService | undefined => deps.sessionDelivery?.();\n const requireSessionDelivery = (): DoomSessionDeliveryService => {\n const delivery = readSessionDelivery();\n if (delivery === undefined)\n throw new HubUnavailableError('The Session delivery service is unavailable. Start the cockpit and try again.');\n return delivery;\n };\n const probe = {\n alive: (record: WorktreeRecord) => requireSessionService().isLive(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 * worktree registry is shared and another process may have written it since\n * 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 (!requireSessionService().isLive(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 const peerFor = (\n context: WorktreeContext,\n record: WorktreeRecord,\n ): { sessionId: string; party: WorktreeMessageParty } => {\n if (context.sessionId === record.parentSessionId) return { sessionId: record.sessionId, party: 'parent' };\n if (context.sessionId === record.sessionId) return { sessionId: record.parentSessionId, party: 'child' };\n throw new DoomGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n 'Use a worktree owned by this session.',\n );\n };\n\n const requirePeerLive = (peerSessionId: string): void => {\n if (!requireSessionService().isLive(peerSessionId)) {\n throw new DoomGitExpectedError(\n 'worktree_peer_unavailable',\n 'The other worktree session is no longer live.',\n false,\n 'Start a new worktree session before sending a message.',\n );\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 taskDelivery = request.task === undefined ? undefined : requireSessionDelivery();\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 const session = await requireSessionService().create({\n cwd: path,\n name: request.name ?? request.branch,\n parentSessionId: context.sessionId,\n sessionProvenance: 'worktree',\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n sessionId = session.sessionId;\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 requireSessionService()\n .close(sessionId)\n .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 if (request.task !== undefined && taskDelivery !== undefined) {\n try {\n const receipt = await taskDelivery.deliver({\n recipientKey: sessionId,\n kind: GIT_WORKTREE_DELEGATION_KIND,\n prompt: request.task,\n metadata: {\n worktreeId: record.id,\n fromRole: 'parent',\n text: request.task,\n sentAt: record.createdAt,\n },\n });\n const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new Error(\n admission === 'recovery_required'\n ? 'The recipient could not admit the task.'\n : 'The recipient did not confirm task admission before the timeout.',\n );\n }\n } catch (error) {\n throw new DoomGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created, but its task admission was not confirmed (${(error as Error).message}).`,\n true,\n `Use send with worktree ${record.id} to deliver the task without recreating the worktree.`,\n );\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 requireSessionService().close(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 /** Sends only between the parent session and its own worktree session. */\n async send(context, id, message) {\n if (Buffer.byteLength(message, 'utf8') > MAX_WORKTREE_MESSAGE_BYTES) {\n throw new DoomGitExpectedError(\n 'message_too_large',\n `A message may not exceed ${String(MAX_WORKTREE_MESSAGE_BYTES)} bytes.`,\n false,\n 'Send a shorter message.',\n );\n }\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n requirePeerLive(peer.sessionId);\n const sentAt = new Date().toISOString();\n const delivery = readSessionDelivery();\n if (delivery !== undefined) {\n const kind = peer.party === 'parent' ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;\n const receipt = await delivery.deliver({\n recipientKey: peer.sessionId,\n kind,\n prompt:\n peer.party === 'parent'\n ? `Parent message for worktree ${record.id}:\\n\\n${message}`\n : `Report from worktree ${record.id}:\\n\\n${message}`,\n metadata: { worktreeId: record.id, fromRole: peer.party, text: message, sentAt },\n });\n const admission = await delivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new DoomGitExpectedError(\n 'message_delivery_failed',\n `Worktree ${record.id} persisted the message, but its session did not confirm admission.`,\n true,\n admission === 'recovery_required'\n ? 'Call messages from the recipient session to recover the persisted text.'\n : 'The message remains durable; retry after the recipient is ready.',\n );\n }\n return;\n }\n requireMessageInbox().send(peer.sessionId, {\n version: 1,\n worktreeId: record.id,\n fromSessionId: context.sessionId,\n from: peer.party,\n text: message,\n sentAt,\n });\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n const delivery = readSessionDelivery();\n if (delivery === undefined) return requireMessageInbox().receive(record.id);\n const entries = delivery\n .inbox({ consumed: false, metadata: { worktreeId: record.id } })\n .filter(\n (entry) =>\n entry.senderKey === peer.sessionId &&\n (entry.state === 'admitted' || entry.state === 'recovery_required') &&\n (peer.party === 'parent'\n ? entry.kind === GIT_WORKTREE_REPORT_KIND\n : entry.kind === GIT_WORKTREE_MESSAGE_KIND || entry.kind === GIT_WORKTREE_DELEGATION_KIND),\n );\n return entries.map((entry) => {\n delivery.consume(entry.deliveryId);\n return {\n version: 1,\n worktreeId: record.id,\n fromSessionId: entry.senderKey,\n from: peer.party === 'parent' ? ('child' as const) : ('parent' as const),\n text:\n entry.state === 'recovery_required'\n ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}`\n : (entry.metadata.text ?? entry.prompt),\n sentAt: entry.metadata.sentAt ?? '',\n };\n });\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":";;;;;;;;;;AAgBA,MAAM,+BAA+B;AACrC,MAAM,4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,KAAK,MAAM,CAAC,CAAC,KAAK,WAAW,OAAO,EAAE,CAAC;GACnF,MAAM,QAAQ,WAAW,QAAQ,QAAQ,WAAW,CAAC,QAAQ,IAAI,OAAO,EAAE,CAAC,CAAC;GAC5E,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,38 @@
1
+ const require_index = require("../atomicJson/index.cjs");
2
+ //#region src/services/worktreeRegistry/index.ts
3
+ function isRecord(value) {
4
+ if (typeof value !== "object" || value === null) return false;
5
+ const record = value;
6
+ return record.version === 1 && typeof record.id === "string" && record.id !== "" && typeof record.path === "string" && typeof record.branch === "string" && typeof record.sessionId === "string";
7
+ }
8
+ /**
9
+ * The worktree registry for one repository, as a single JSON file.
10
+ *
11
+ * One file rather than a file per worktree, and read-modify-write rather than
12
+ * merging: every write comes from a tool call in one session's turn, so there
13
+ * is no concurrent writer to reconcile with. Choosing the simpler shape now
14
+ * means a reader can see the whole registry in one place; if concurrent writers
15
+ * ever appear, that is the point to revisit, not before.
16
+ *
17
+ * A file that does not parse is treated as empty rather than fatal. Losing
18
+ * track of worktrees is recoverable through prune; refusing to run is not.
19
+ */
20
+ function createWorktreeRegistry(file) {
21
+ return {
22
+ list() {
23
+ const parsed = require_index.readJson(file);
24
+ if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.entries)) return [];
25
+ return parsed.entries.filter(isRecord);
26
+ },
27
+ replace(entries) {
28
+ require_index.writeJsonAtomic(file, {
29
+ version: 1,
30
+ entries
31
+ });
32
+ }
33
+ };
34
+ }
35
+ //#endregion
36
+ exports.createWorktreeRegistry = createWorktreeRegistry;
37
+
38
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["readJson"],"sources":["../../../../src/services/worktreeRegistry/index.ts"],"sourcesContent":["import {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeRegistryFile,\n type WorktreeRegistryStore,\n} from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\n\nfunction isRecord(value: unknown): value is WorktreeRecord {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Partial<WorktreeRecord>;\n return (\n record.version === WORKTREE_RECORD_VERSION &&\n typeof record.id === 'string' &&\n record.id !== '' &&\n typeof record.path === 'string' &&\n typeof record.branch === 'string' &&\n typeof record.sessionId === 'string'\n );\n}\n\n/**\n * The worktree registry for one repository, as a single JSON file.\n *\n * One file rather than a file per worktree, and read-modify-write rather than\n * merging: every write comes from a tool call in one session's turn, so there\n * is no concurrent writer to reconcile with. Choosing the simpler shape now\n * means a reader can see the whole registry in one place; if concurrent writers\n * ever appear, that is the point to revisit, not before.\n *\n * A file that does not parse is treated as empty rather than fatal. Losing\n * track of worktrees is recoverable through prune; refusing to run is not.\n */\nexport function createWorktreeRegistry(file: string): WorktreeRegistryStore {\n return {\n list() {\n const parsed = readJson<WorktreeRegistryFile>(file);\n if (!parsed || parsed.version !== WORKTREE_RECORD_VERSION || !Array.isArray(parsed.entries)) return [];\n return parsed.entries.filter(isRecord);\n },\n replace(entries) {\n writeJsonAtomic(file, { version: WORKTREE_RECORD_VERSION, entries } satisfies WorktreeRegistryFile);\n },\n };\n}\n"],"mappings":";;AAQA,SAAS,SAAS,OAAyC;CACzD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,OACE,OAAO,YAAA,KACP,OAAO,OAAO,OAAO,YACrB,OAAO,OAAO,MACd,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,WAAW,YACzB,OAAO,OAAO,cAAc;AAEhC;;;;;;;;;;;;;AAcA,SAAgB,uBAAuB,MAAqC;CAC1E,OAAO;EACL,OAAO;GACL,MAAM,SAASA,cAAAA,SAA+B,IAAI;GAClD,IAAI,CAAC,UAAU,OAAO,YAAA,KAAuC,CAAC,MAAM,QAAQ,OAAO,OAAO,GAAG,OAAO,CAAC;GACrG,OAAO,OAAO,QAAQ,OAAO,QAAQ;EACvC;EACA,QAAQ,SAAS;GACf,cAAA,gBAAgB,MAAM;IAAE,SAAA;IAAkC;GAAQ,CAAgC;EACpG;CACF;AACF"}
@@ -0,0 +1,38 @@
1
+ import { readJson, writeJsonAtomic } from "../atomicJson/index.mjs";
2
+ //#region src/services/worktreeRegistry/index.ts
3
+ function isRecord(value) {
4
+ if (typeof value !== "object" || value === null) return false;
5
+ const record = value;
6
+ return record.version === 1 && typeof record.id === "string" && record.id !== "" && typeof record.path === "string" && typeof record.branch === "string" && typeof record.sessionId === "string";
7
+ }
8
+ /**
9
+ * The worktree registry for one repository, as a single JSON file.
10
+ *
11
+ * One file rather than a file per worktree, and read-modify-write rather than
12
+ * merging: every write comes from a tool call in one session's turn, so there
13
+ * is no concurrent writer to reconcile with. Choosing the simpler shape now
14
+ * means a reader can see the whole registry in one place; if concurrent writers
15
+ * ever appear, that is the point to revisit, not before.
16
+ *
17
+ * A file that does not parse is treated as empty rather than fatal. Losing
18
+ * track of worktrees is recoverable through prune; refusing to run is not.
19
+ */
20
+ function createWorktreeRegistry(file) {
21
+ return {
22
+ list() {
23
+ const parsed = readJson(file);
24
+ if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.entries)) return [];
25
+ return parsed.entries.filter(isRecord);
26
+ },
27
+ replace(entries) {
28
+ writeJsonAtomic(file, {
29
+ version: 1,
30
+ entries
31
+ });
32
+ }
33
+ };
34
+ }
35
+ //#endregion
36
+ export { createWorktreeRegistry };
37
+
38
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/worktreeRegistry/index.ts"],"sourcesContent":["import {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeRegistryFile,\n type WorktreeRegistryStore,\n} from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\n\nfunction isRecord(value: unknown): value is WorktreeRecord {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Partial<WorktreeRecord>;\n return (\n record.version === WORKTREE_RECORD_VERSION &&\n typeof record.id === 'string' &&\n record.id !== '' &&\n typeof record.path === 'string' &&\n typeof record.branch === 'string' &&\n typeof record.sessionId === 'string'\n );\n}\n\n/**\n * The worktree registry for one repository, as a single JSON file.\n *\n * One file rather than a file per worktree, and read-modify-write rather than\n * merging: every write comes from a tool call in one session's turn, so there\n * is no concurrent writer to reconcile with. Choosing the simpler shape now\n * means a reader can see the whole registry in one place; if concurrent writers\n * ever appear, that is the point to revisit, not before.\n *\n * A file that does not parse is treated as empty rather than fatal. Losing\n * track of worktrees is recoverable through prune; refusing to run is not.\n */\nexport function createWorktreeRegistry(file: string): WorktreeRegistryStore {\n return {\n list() {\n const parsed = readJson<WorktreeRegistryFile>(file);\n if (!parsed || parsed.version !== WORKTREE_RECORD_VERSION || !Array.isArray(parsed.entries)) return [];\n return parsed.entries.filter(isRecord);\n },\n replace(entries) {\n writeJsonAtomic(file, { version: WORKTREE_RECORD_VERSION, entries } satisfies WorktreeRegistryFile);\n },\n };\n}\n"],"mappings":";;AAQA,SAAS,SAAS,OAAyC;CACzD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,OACE,OAAO,YAAA,KACP,OAAO,OAAO,OAAO,YACrB,OAAO,OAAO,MACd,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,WAAW,YACzB,OAAO,OAAO,cAAc;AAEhC;;;;;;;;;;;;;AAcA,SAAgB,uBAAuB,MAAqC;CAC1E,OAAO;EACL,OAAO;GACL,MAAM,SAAS,SAA+B,IAAI;GAClD,IAAI,CAAC,UAAU,OAAO,YAAA,KAAuC,CAAC,MAAM,QAAQ,OAAO,OAAO,GAAG,OAAO,CAAC;GACrG,OAAO,OAAO,QAAQ,OAAO,QAAQ;EACvC;EACA,QAAQ,SAAS;GACf,gBAAgB,MAAM;IAAE,SAAA;IAAkC;GAAQ,CAAgC;EACpG;CACF;AACF"}