@agimon-ai/doompi-git 0.0.1-alpha.3 → 0.0.1-alpha.30

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 (179) hide show
  1. package/README.md +2 -0
  2. package/dist/apiContracts.cjs +149 -0
  3. package/dist/apiContracts.cjs.map +1 -0
  4. package/dist/apiContracts.d.mts +53 -0
  5. package/dist/apiContracts.d.mts.map +1 -0
  6. package/dist/apiContracts.mjs +144 -0
  7. package/dist/apiContracts.mjs.map +1 -0
  8. package/dist/extensions/pi.cjs +109 -1
  9. package/dist/extensions/pi.cjs.map +1 -0
  10. package/dist/extensions/pi.d.mts +6 -2
  11. package/dist/extensions/pi.d.mts.map +1 -0
  12. package/dist/extensions/pi.mjs +104 -1
  13. package/dist/extensions/pi.mjs.map +1 -0
  14. package/dist/extensions/server.cjs +495 -0
  15. package/dist/extensions/server.cjs.map +1 -0
  16. package/dist/extensions/server.d.mts +5 -0
  17. package/dist/extensions/server.d.mts.map +1 -0
  18. package/dist/extensions/server.mjs +490 -0
  19. package/dist/extensions/server.mjs.map +1 -0
  20. package/dist/extensions/web.mjs +580 -0
  21. package/dist/extensions/web.mjs.map +1 -0
  22. package/dist/gitDependencies-D-EUEIkE.mjs +22 -0
  23. package/dist/gitDependencies-D-EUEIkE.mjs.map +1 -0
  24. package/dist/gitDependencies-DKJr5kLQ.cjs +33 -0
  25. package/dist/gitDependencies-DKJr5kLQ.cjs.map +1 -0
  26. package/dist/index-BQq2vblZ.d.mts +143 -0
  27. package/dist/index-BQq2vblZ.d.mts.map +1 -0
  28. package/dist/index.cjs +4 -1
  29. package/dist/index.d.mts +2 -5
  30. package/dist/index.mjs +2 -1
  31. package/dist/runWorktree-B6ikYRrG.cjs +318 -0
  32. package/dist/runWorktree-B6ikYRrG.cjs.map +1 -0
  33. package/dist/runWorktree-BL99h9oH.mjs +289 -0
  34. package/dist/runWorktree-BL99h9oH.mjs.map +1 -0
  35. package/dist/worktreeOperations-DAbs0ZTX.mjs +1054 -0
  36. package/dist/worktreeOperations-DAbs0ZTX.mjs.map +1 -0
  37. package/dist/worktreeOperations-DjO_Y5Yv.cjs +1138 -0
  38. package/dist/worktreeOperations-DjO_Y5Yv.cjs.map +1 -0
  39. package/package.json +53 -39
  40. package/src/prompts/doompi-use-git/SKILL.md +5 -2
  41. package/dist/_virtual/_rolldown/runtime.cjs +0 -1
  42. package/dist/adapters/channel/worktreeChannel.cjs +0 -2
  43. package/dist/adapters/channel/worktreeChannel.cjs.map +0 -1
  44. package/dist/adapters/channel/worktreeChannel.d.cts +0 -40
  45. package/dist/adapters/channel/worktreeChannel.d.cts.map +0 -1
  46. package/dist/adapters/channel/worktreeChannel.d.mts +0 -40
  47. package/dist/adapters/channel/worktreeChannel.d.mts.map +0 -1
  48. package/dist/adapters/channel/worktreeChannel.mjs +0 -2
  49. package/dist/adapters/channel/worktreeChannel.mjs.map +0 -1
  50. package/dist/adapters/filesystem/atomicJson.cjs +0 -2
  51. package/dist/adapters/filesystem/atomicJson.cjs.map +0 -1
  52. package/dist/adapters/filesystem/atomicJson.mjs +0 -2
  53. package/dist/adapters/filesystem/atomicJson.mjs.map +0 -1
  54. package/dist/adapters/filesystem/paths.cjs +0 -2
  55. package/dist/adapters/filesystem/paths.cjs.map +0 -1
  56. package/dist/adapters/filesystem/paths.mjs +0 -2
  57. package/dist/adapters/filesystem/paths.mjs.map +0 -1
  58. package/dist/adapters/hub/hubClient.cjs +0 -2
  59. package/dist/adapters/hub/hubClient.cjs.map +0 -1
  60. package/dist/adapters/hub/hubClient.d.cts +0 -1
  61. package/dist/adapters/hub/hubClient.d.mts +0 -1
  62. package/dist/adapters/hub/hubClient.mjs +0 -2
  63. package/dist/adapters/hub/hubClient.mjs.map +0 -1
  64. package/dist/adapters/pi/extension.cjs +0 -2
  65. package/dist/adapters/pi/extension.cjs.map +0 -1
  66. package/dist/adapters/pi/extension.d.cts +0 -9
  67. package/dist/adapters/pi/extension.d.cts.map +0 -1
  68. package/dist/adapters/pi/extension.d.mts +0 -9
  69. package/dist/adapters/pi/extension.d.mts.map +0 -1
  70. package/dist/adapters/pi/extension.mjs +0 -2
  71. package/dist/adapters/pi/extension.mjs.map +0 -1
  72. package/dist/adapters/pi/extensions/runWorktreeTool.cjs +0 -15
  73. package/dist/adapters/pi/extensions/runWorktreeTool.cjs.map +0 -1
  74. package/dist/adapters/pi/extensions/runWorktreeTool.mjs +0 -15
  75. package/dist/adapters/pi/extensions/runWorktreeTool.mjs.map +0 -1
  76. package/dist/adapters/web/worktreesChannel.cjs +0 -2
  77. package/dist/adapters/web/worktreesChannel.cjs.map +0 -1
  78. package/dist/adapters/web/worktreesChannel.d.cts +0 -21
  79. package/dist/adapters/web/worktreesChannel.d.cts.map +0 -1
  80. package/dist/adapters/web/worktreesChannel.d.mts +0 -21
  81. package/dist/adapters/web/worktreesChannel.d.mts.map +0 -1
  82. package/dist/adapters/web/worktreesChannel.mjs +0 -2
  83. package/dist/adapters/web/worktreesChannel.mjs.map +0 -1
  84. package/dist/adapters/worktree/dependencyInstall.cjs +0 -2
  85. package/dist/adapters/worktree/dependencyInstall.cjs.map +0 -1
  86. package/dist/adapters/worktree/dependencyInstall.mjs +0 -2
  87. package/dist/adapters/worktree/dependencyInstall.mjs.map +0 -1
  88. package/dist/adapters/worktree/gitCli.cjs +0 -4
  89. package/dist/adapters/worktree/gitCli.cjs.map +0 -1
  90. package/dist/adapters/worktree/gitCli.mjs +0 -4
  91. package/dist/adapters/worktree/gitCli.mjs.map +0 -1
  92. package/dist/adapters/worktree/repositoryIdentity.cjs +0 -2
  93. package/dist/adapters/worktree/repositoryIdentity.cjs.map +0 -1
  94. package/dist/adapters/worktree/repositoryIdentity.mjs +0 -2
  95. package/dist/adapters/worktree/repositoryIdentity.mjs.map +0 -1
  96. package/dist/adapters/worktree/worktreeOperations.cjs +0 -2
  97. package/dist/adapters/worktree/worktreeOperations.cjs.map +0 -1
  98. package/dist/adapters/worktree/worktreeOperations.d.cts +0 -32
  99. package/dist/adapters/worktree/worktreeOperations.d.cts.map +0 -1
  100. package/dist/adapters/worktree/worktreeOperations.d.mts +0 -32
  101. package/dist/adapters/worktree/worktreeOperations.d.mts.map +0 -1
  102. package/dist/adapters/worktree/worktreeOperations.mjs +0 -2
  103. package/dist/adapters/worktree/worktreeOperations.mjs.map +0 -1
  104. package/dist/adapters/worktree/worktreeRegistry.cjs +0 -2
  105. package/dist/adapters/worktree/worktreeRegistry.cjs.map +0 -1
  106. package/dist/adapters/worktree/worktreeRegistry.mjs +0 -2
  107. package/dist/adapters/worktree/worktreeRegistry.mjs.map +0 -1
  108. package/dist/commands/doomGitCommand.cjs +0 -2
  109. package/dist/commands/doomGitCommand.cjs.map +0 -1
  110. package/dist/commands/doomGitCommand.mjs +0 -2
  111. package/dist/commands/doomGitCommand.mjs.map +0 -1
  112. package/dist/container/index.cjs +0 -2
  113. package/dist/container/index.cjs.map +0 -1
  114. package/dist/container/index.d.cts +0 -6
  115. package/dist/container/index.d.cts.map +0 -1
  116. package/dist/container/index.d.mts +0 -6
  117. package/dist/container/index.d.mts.map +0 -1
  118. package/dist/container/index.mjs +0 -2
  119. package/dist/container/index.mjs.map +0 -1
  120. package/dist/extensions/pi.d.cts +0 -2
  121. package/dist/hubApi.cjs +0 -2
  122. package/dist/hubApi.cjs.map +0 -1
  123. package/dist/hubApi.d.cts +0 -6
  124. package/dist/hubApi.d.cts.map +0 -1
  125. package/dist/hubApi.d.mts +0 -6
  126. package/dist/hubApi.d.mts.map +0 -1
  127. package/dist/hubApi.mjs +0 -2
  128. package/dist/hubApi.mjs.map +0 -1
  129. package/dist/index.d.cts +0 -5
  130. package/dist/schemas/runWorktreeTool.cjs +0 -2
  131. package/dist/schemas/runWorktreeTool.cjs.map +0 -1
  132. package/dist/schemas/runWorktreeTool.mjs +0 -2
  133. package/dist/schemas/runWorktreeTool.mjs.map +0 -1
  134. package/dist/services/extensionService.cjs +0 -2
  135. package/dist/services/extensionService.cjs.map +0 -1
  136. package/dist/services/extensionService.d.cts +0 -8
  137. package/dist/services/extensionService.d.cts.map +0 -1
  138. package/dist/services/extensionService.d.mts +0 -8
  139. package/dist/services/extensionService.d.mts.map +0 -1
  140. package/dist/services/extensionService.mjs +0 -2
  141. package/dist/services/extensionService.mjs.map +0 -1
  142. package/dist/services/support/errors.cjs +0 -2
  143. package/dist/services/support/errors.cjs.map +0 -1
  144. package/dist/services/support/errors.mjs +0 -2
  145. package/dist/services/support/errors.mjs.map +0 -1
  146. package/dist/services/worktreeNaming.cjs +0 -2
  147. package/dist/services/worktreeNaming.cjs.map +0 -1
  148. package/dist/services/worktreeNaming.d.cts +0 -27
  149. package/dist/services/worktreeNaming.d.cts.map +0 -1
  150. package/dist/services/worktreeNaming.d.mts +0 -27
  151. package/dist/services/worktreeNaming.d.mts.map +0 -1
  152. package/dist/services/worktreeNaming.mjs +0 -2
  153. package/dist/services/worktreeNaming.mjs.map +0 -1
  154. package/dist/types/extension.d.cts +0 -17
  155. package/dist/types/extension.d.cts.map +0 -1
  156. package/dist/types/extension.d.mts +0 -17
  157. package/dist/types/extension.d.mts.map +0 -1
  158. package/dist/types/webWorktrees.cjs +0 -2
  159. package/dist/types/webWorktrees.cjs.map +0 -1
  160. package/dist/types/webWorktrees.mjs +0 -2
  161. package/dist/types/webWorktrees.mjs.map +0 -1
  162. package/dist/types/worktreeRegistry.d.cts +0 -41
  163. package/dist/types/worktreeRegistry.d.cts.map +0 -1
  164. package/dist/types/worktreeRegistry.d.mts +0 -41
  165. package/dist/types/worktreeRegistry.d.mts.map +0 -1
  166. package/dist/webHub.cjs +0 -1
  167. package/dist/webHub.d.cts +0 -2
  168. package/dist/webHub.d.mts +0 -2
  169. package/dist/webHub.mjs +0 -1
  170. package/src/exports/webClient.ts +0 -1
  171. package/src/types/webWorktrees.ts +0 -55
  172. package/src/types/worktreeRegistry.ts +0 -69
  173. package/src/web/components/RunWorktreeToolMessage.tsx +0 -37
  174. package/src/web/components/WorktreesActivitySection.tsx +0 -64
  175. package/src/web/components/WorktreesPanel.tsx +0 -125
  176. package/src/web/components/toolRenderers.ts +0 -7
  177. package/src/web/index.ts +0 -30
  178. package/src/web/stores/worktreesActivityStore.ts +0 -124
  179. package/src/web/tsconfig.json +0 -22
@@ -0,0 +1,1054 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { removeSyncLocation, resolveWorktreeSyncLocation } from "@agimon-ai/doompi-core/syncLocation";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import { isDeepStrictEqual } from "node:util";
8
+ import { setTimeout } from "node:timers/promises";
9
+ //#region src/services/gitCli/index.ts
10
+ /**
11
+ * Git, as this package needs it.
12
+ *
13
+ * The timeouts are not uniform because the operations are not comparable. A
14
+ * read answers in milliseconds; `worktree add` copies an entire checkout and
15
+ * `worktree remove` deletes one, both bounded by the filesystem rather than by
16
+ * git, and both minutes rather than seconds on a large repository or on
17
+ * Windows. A single timeout would either fail honest work or hang on a wedged
18
+ * one.
19
+ */
20
+ const READ_TIMEOUT_MS = 3e4;
21
+ const ADD_TIMEOUT_MS = 3e5;
22
+ const REMOVE_TIMEOUT_MS = 3e5;
23
+ const PRUNE_TIMEOUT_MS = 15e3;
24
+ const MAX_OUTPUT_BYTES = 1e6;
25
+ /**
26
+ * Runs git and reports the outcome without ever throwing on a non-zero exit.
27
+ *
28
+ * LC_ALL is pinned because two callers below decide what to do by matching
29
+ * git's own wording, and a translated message would silently turn a recognised
30
+ * condition into an unrecognised failure.
31
+ */
32
+ function git(cwd, args, timeout) {
33
+ return new Promise((resolve) => {
34
+ execFile("git", [...args], {
35
+ cwd,
36
+ timeout,
37
+ maxBuffer: MAX_OUTPUT_BYTES,
38
+ env: {
39
+ ...process.env,
40
+ LC_ALL: "C"
41
+ }
42
+ }, (error, stdout, stderr) => {
43
+ resolve({
44
+ code: error && typeof error.code === "number" ? error.code : error ? 1 : 0,
45
+ stdout: String(stdout),
46
+ stderr: String(stderr)
47
+ });
48
+ });
49
+ });
50
+ }
51
+ /**
52
+ * The message a failed git call is allowed to surface.
53
+ *
54
+ * Raw stderr never travels: it can carry a remote URL with a token in it, and
55
+ * this text ends up in a tool result the model reads and may repeat.
56
+ */
57
+ function failure(operation, result) {
58
+ return /* @__PURE__ */ new Error(`git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`);
59
+ }
60
+ /** Git's own words for "that worktree is not there any more". */
61
+ function missingWorktree(stderr) {
62
+ const normalized = stderr.toLowerCase();
63
+ return normalized.includes("is not a working tree") || normalized.includes("cannot remove working tree");
64
+ }
65
+ function createWorktreeGit() {
66
+ const prune = async (repositoryRoot) => {
67
+ await git(repositoryRoot, ["worktree", "prune"], PRUNE_TIMEOUT_MS);
68
+ };
69
+ return {
70
+ async addWorktree({ repositoryRoot, path, branch, baseRef }) {
71
+ const result = await git(repositoryRoot, [
72
+ "worktree",
73
+ "add",
74
+ "-b",
75
+ branch,
76
+ path,
77
+ baseRef
78
+ ], ADD_TIMEOUT_MS);
79
+ if (result.code !== 0) throw failure("worktree add", result);
80
+ },
81
+ async removeWorktree({ repositoryRoot, path, force }) {
82
+ const result = await git(repositoryRoot, [
83
+ "worktree",
84
+ "remove",
85
+ ...force ? ["--force"] : [],
86
+ path
87
+ ], REMOVE_TIMEOUT_MS);
88
+ if (result.code === 0) return;
89
+ if (missingWorktree(result.stderr) && !fs.existsSync(path)) {
90
+ await prune(repositoryRoot);
91
+ return;
92
+ }
93
+ throw failure("worktree remove", result);
94
+ },
95
+ async deleteBranch({ repositoryRoot, branch }) {
96
+ return (await git(repositoryRoot, [
97
+ "branch",
98
+ "-d",
99
+ branch
100
+ ], READ_TIMEOUT_MS)).code === 0;
101
+ },
102
+ pruneWorktrees: prune,
103
+ async listWorktreePaths(repositoryRoot) {
104
+ const result = await git(repositoryRoot, [
105
+ "worktree",
106
+ "list",
107
+ "--porcelain"
108
+ ], READ_TIMEOUT_MS);
109
+ if (result.code !== 0) return [];
110
+ return result.stdout.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice(9).trim()).filter((line) => line !== "");
111
+ },
112
+ async dirtyFiles(path) {
113
+ const result = await git(path, ["status", "--porcelain"], READ_TIMEOUT_MS);
114
+ if (result.code !== 0) return [];
115
+ return result.stdout.split("\n").map((line) => line.slice(3).trim()).filter((line) => line !== "");
116
+ },
117
+ async repositoryRoot(cwd) {
118
+ const result = await git(cwd, ["rev-parse", "--show-toplevel"], READ_TIMEOUT_MS);
119
+ if (result.code !== 0) return void 0;
120
+ const root = result.stdout.trim();
121
+ return root === "" ? void 0 : root;
122
+ },
123
+ async currentBranch(cwd) {
124
+ const result = await git(cwd, [
125
+ "rev-parse",
126
+ "--abbrev-ref",
127
+ "HEAD"
128
+ ], READ_TIMEOUT_MS);
129
+ if (result.code !== 0) return void 0;
130
+ const branch = result.stdout.trim();
131
+ return branch === "" ? void 0 : branch;
132
+ },
133
+ async remoteBaseRef(cwd) {
134
+ const upstream = await git(cwd, [
135
+ "rev-parse",
136
+ "--abbrev-ref",
137
+ "--symbolic-full-name",
138
+ "@{upstream}"
139
+ ], READ_TIMEOUT_MS);
140
+ if (upstream.code === 0) {
141
+ const branch = upstream.stdout.trim();
142
+ if (branch !== "") return branch;
143
+ }
144
+ const origin = await git(cwd, [
145
+ "symbolic-ref",
146
+ "--quiet",
147
+ "--short",
148
+ "refs/remotes/origin/HEAD"
149
+ ], READ_TIMEOUT_MS);
150
+ if (origin.code === 0) {
151
+ const branch = origin.stdout.trim();
152
+ if (branch !== "") return branch;
153
+ }
154
+ const defaults = await git(cwd, [
155
+ "for-each-ref",
156
+ "--format=%(symref:short)",
157
+ "refs/remotes"
158
+ ], READ_TIMEOUT_MS);
159
+ if (defaults.code !== 0) return void 0;
160
+ return defaults.stdout.split("\n").map((line) => line.trim()).find((line) => line !== "");
161
+ },
162
+ async mergeBranch({ repositoryRoot, branch, message }) {
163
+ const result = await git(repositoryRoot, [
164
+ "merge",
165
+ "--no-ff",
166
+ ...message === void 0 ? [] : ["-m", message],
167
+ branch
168
+ ], READ_TIMEOUT_MS);
169
+ if (result.code === 0) return;
170
+ throw failure("merge", result);
171
+ }
172
+ };
173
+ }
174
+ //#endregion
175
+ //#region src/services/compositionMirror/index.ts
176
+ /**
177
+ * Giving a new worktree the build output its parent checkout already has.
178
+ *
179
+ * DESIGN PATTERNS:
180
+ * - Mirrors, never builds. Everything here is a copy or a symlink of something
181
+ * the parent checkout already produced, so it costs seconds and cannot fail
182
+ * the way a package manager or a compiler can.
183
+ * - `node_modules` is linked, `dist` is copied. The module tree is gigabytes
184
+ * and read-only in practice, so a link is right; build output is small and a
185
+ * link would send a build run inside the worktree straight into the parent's
186
+ * directory.
187
+ * - Absent parent output means nothing to do. A repository with no
188
+ * `node_modules` at its root is either not a JS project or not installed, and
189
+ * either way this has no opinion about it, so a Rust, Go or Python worktree
190
+ * pays nothing.
191
+ *
192
+ * WHY THIS EXISTS:
193
+ * A DoomPi session composes the extensions its repository's config names, and
194
+ * this repository names its own workspace packages by relative path. Those
195
+ * packages declare `pi.extensions` under `dist/`, which git does not track, so
196
+ * a fresh worktree resolves none of them and the session dies on start. The
197
+ * parent checkout has already built exactly what the child needs.
198
+ *
199
+ * AVOID:
200
+ * - Recursing into `node_modules`. The scan is bounded and skips it; without
201
+ * that this walks a gigabyte to find nothing.
202
+ * - Treating a mirror failure as fatal. The worktree is good either way; only
203
+ * the session's composition is poorer for it.
204
+ */
205
+ /** Directories that are build output worth copying into a new worktree. */
206
+ const OUTPUT_DIRECTORY = "dist";
207
+ const MODULES_DIRECTORY = "node_modules";
208
+ const GIT_DIRECTORY = ".git";
209
+ /**
210
+ * How deep the scan goes.
211
+ *
212
+ * Four levels reaches `layers/<group>/<package>/dist` in this repository's
213
+ * layout, and a workspace that buries a package deeper than that gets a
214
+ * partial mirror rather than a slow one.
215
+ */
216
+ const MAX_DEPTH = 4;
217
+ function scan(root) {
218
+ const found = {
219
+ outputs: [],
220
+ modules: []
221
+ };
222
+ const walk = (relative, depth) => {
223
+ let entries;
224
+ try {
225
+ entries = fs.readdirSync(path.join(root, relative), { withFileTypes: true });
226
+ } catch {
227
+ return;
228
+ }
229
+ for (const entry of entries) {
230
+ const child = relative === "" ? entry.name : `${relative}/${entry.name}`;
231
+ if (entry.name === GIT_DIRECTORY) continue;
232
+ if (entry.name === MODULES_DIRECTORY) {
233
+ try {
234
+ if (entry.isDirectory() || entry.isSymbolicLink() && fs.statSync(path.join(root, child)).isDirectory()) found.modules.push(child);
235
+ } catch {}
236
+ continue;
237
+ }
238
+ if (!entry.isDirectory()) continue;
239
+ if (entry.name === OUTPUT_DIRECTORY) {
240
+ found.outputs.push(child);
241
+ continue;
242
+ }
243
+ if (depth < MAX_DEPTH) walk(child, depth + 1);
244
+ }
245
+ };
246
+ walk("", 1);
247
+ return found;
248
+ }
249
+ /**
250
+ * Copies the parent's build output into a worktree and links its modules.
251
+ *
252
+ * Individual failures are counted out rather than thrown: a mirror that lands
253
+ * partly is still better than none, and the caller has a worktree either way.
254
+ */
255
+ function mirrorComposition(source, target) {
256
+ if (!fs.existsSync(path.join(source, MODULES_DIRECTORY))) return {
257
+ kind: "skipped",
258
+ reason: "no-modules"
259
+ };
260
+ const found = scan(source);
261
+ let copied = 0;
262
+ let linked = 0;
263
+ for (const relative of found.modules) {
264
+ const destination = path.join(target, relative);
265
+ if (fs.existsSync(destination)) continue;
266
+ try {
267
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
268
+ fs.symlinkSync(fs.realpathSync(path.join(source, relative)), destination, "dir");
269
+ linked += 1;
270
+ } catch {}
271
+ }
272
+ for (const relative of found.outputs) {
273
+ const destination = path.join(target, relative);
274
+ if (fs.existsSync(destination)) continue;
275
+ try {
276
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
277
+ fs.cpSync(path.join(source, relative), destination, { recursive: true });
278
+ copied += 1;
279
+ } catch {}
280
+ }
281
+ return {
282
+ kind: "mirrored",
283
+ copied,
284
+ linked
285
+ };
286
+ }
287
+ //#endregion
288
+ //#region src/services/errors/index.ts
289
+ var DoomGitExpectedError = class extends Error {
290
+ code;
291
+ retryable;
292
+ recovery;
293
+ constructor(code, message, retryable, recovery) {
294
+ super(`[${code}] ${message}\nRecovery: ${recovery}`);
295
+ this.code = code;
296
+ this.retryable = retryable;
297
+ this.recovery = recovery;
298
+ this.name = "DoomGitExpectedError";
299
+ }
300
+ };
301
+ /** Raised when a worktree action needs the canonical hub but it is not injected. */
302
+ var HubUnavailableError = class extends Error {
303
+ constructor(message) {
304
+ super(message);
305
+ this.name = "HubUnavailableError";
306
+ }
307
+ };
308
+ function invalidRequest(message, recovery) {
309
+ return new DoomGitExpectedError("invalid_request", message, false, recovery);
310
+ }
311
+ //#endregion
312
+ //#region src/services/atomicJson/index.ts
313
+ const OWNER_ONLY_FILE = 384;
314
+ /**
315
+ * Writes JSON so a reader never sees a half-written file.
316
+ *
317
+ * The registry is read by the same process that writes it, and by a later
318
+ * process after a crash. A plain write can be interrupted between the truncate
319
+ * and the last byte, which leaves a file that parses as nothing and loses every
320
+ * record in it. Writing beside the target and renaming makes the swap atomic on
321
+ * the same filesystem, so a reader sees either the old file or the new one.
322
+ */
323
+ function writeJsonAtomic(file, value) {
324
+ const directory = path.dirname(file);
325
+ fs.mkdirSync(directory, { recursive: true });
326
+ const temporary = path.join(directory, `.${path.basename(file)}.${String(process.pid)}.tmp`);
327
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: OWNER_ONLY_FILE });
328
+ fs.renameSync(temporary, file);
329
+ }
330
+ /**
331
+ * Reads JSON, treating every failure as absent.
332
+ *
333
+ * A missing file and an unparseable one mean the same thing to every caller
334
+ * here: there is nothing to act on. Distinguishing them would only offer a
335
+ * choice no caller wants to make.
336
+ */
337
+ function readJson(file) {
338
+ try {
339
+ return JSON.parse(fs.readFileSync(file, "utf8"));
340
+ } catch {
341
+ return;
342
+ }
343
+ }
344
+ //#endregion
345
+ //#region src/services/repositoryIdentity/index.ts
346
+ const ID_LENGTH = 12;
347
+ const MAX_LABEL_LENGTH = 32;
348
+ /**
349
+ * The git directory shared by a repository and all of its worktrees.
350
+ *
351
+ * A normal checkout has a `.git` directory. A linked worktree has a `.git`
352
+ * FILE pointing at `<common>/worktrees/<name>`, whose `commondir` points back
353
+ * at the shared directory. Following that chain is what makes every worktree of
354
+ * one repository agree on the repository's identity, which matters here because
355
+ * the registry is per repository and must be found from inside a worktree too.
356
+ * A session may run in a subdirectory, so the nearest enclosing checkout is used.
357
+ */
358
+ function gitCommonDirectory(directory) {
359
+ let root = path.resolve(directory);
360
+ let marker = path.join(root, ".git");
361
+ let stat;
362
+ for (;;) try {
363
+ stat = fs.statSync(marker);
364
+ break;
365
+ } catch {
366
+ const parent = path.dirname(root);
367
+ if (parent === root) return void 0;
368
+ root = parent;
369
+ marker = path.join(root, ".git");
370
+ }
371
+ if (stat.isDirectory()) return marker;
372
+ let pointer;
373
+ try {
374
+ pointer = fs.readFileSync(marker, "utf8").trim();
375
+ } catch {
376
+ return;
377
+ }
378
+ if (!pointer.startsWith("gitdir:")) return void 0;
379
+ const gitDir = path.resolve(root, pointer.slice(7).trim());
380
+ try {
381
+ const common = fs.readFileSync(path.join(gitDir, "commondir"), "utf8").trim();
382
+ return path.resolve(gitDir, common);
383
+ } catch {
384
+ return gitDir;
385
+ }
386
+ }
387
+ /** A directory name that is recognisable to a person and safe on a filesystem. */
388
+ function repositoryLabel(root) {
389
+ const label = path.basename(root).toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, MAX_LABEL_LENGTH);
390
+ return label === "" ? "repository" : label;
391
+ }
392
+ /**
393
+ * A stable id for the repository a directory belongs to.
394
+ *
395
+ * Keyed on the common git directory rather than the given path, so the main
396
+ * checkout and every worktree of it resolve to one id and therefore to one
397
+ * registry. Falling back to the path keeps a non-repository directory usable
398
+ * instead of failing, though nothing here should reach that case.
399
+ */
400
+ function repositoryId(root) {
401
+ const common = gitCommonDirectory(root);
402
+ const token = common === void 0 ? `root:${path.resolve(root)}` : `git:${common}`;
403
+ return createHash("sha256").update(token).digest("hex").slice(0, ID_LENGTH);
404
+ }
405
+ /** A short, collision-resistant suffix for one worktree directory. */
406
+ function shortId(seed) {
407
+ return createHash("sha256").update(seed).digest("hex").slice(0, 8);
408
+ }
409
+ //#endregion
410
+ //#region src/services/paths/index.ts
411
+ /**
412
+ * Where this package keeps its own state.
413
+ *
414
+ * Outside the repository on purpose. A worktree directory inside the checkout
415
+ * would be found by every glob the repository's own tooling runs, and would
416
+ * resolve workspace imports against the parent checkout rather than the
417
+ * worktree, so a session there would build the wrong source while appearing to
418
+ * work.
419
+ */
420
+ function doomGitRoot(homeDir = os.homedir()) {
421
+ return path.join(homeDir, ".pi", ".doom", "git");
422
+ }
423
+ /** The directory every worktree for every repository is created under. */
424
+ function worktreesRoot(homeDir = os.homedir()) {
425
+ return path.join(doomGitRoot(homeDir), "worktrees");
426
+ }
427
+ /** One registry file per repository, keyed by the shared git directory. */
428
+ function registryFile(repositoryRoot, homeDir = os.homedir()) {
429
+ const id = repositoryId(repositoryRoot);
430
+ const root = path.join(doomGitRoot(homeDir), "registry");
431
+ const canonical = path.join(root, id, "worktrees.json");
432
+ if (fs.existsSync(canonical)) return canonical;
433
+ let names;
434
+ try {
435
+ names = fs.readdirSync(root);
436
+ } catch {
437
+ return canonical;
438
+ }
439
+ const legacyFiles = names.filter((entry) => entry.endsWith(`--${id}`)).sort().map((entry) => path.join(root, entry, "worktrees.json")).filter((file) => fs.existsSync(file));
440
+ if (legacyFiles.length === 0) return canonical;
441
+ const entries = /* @__PURE__ */ new Map();
442
+ for (const file of legacyFiles) {
443
+ const legacy = readJson(file);
444
+ if (legacy?.version !== 1 || !Array.isArray(legacy.entries)) continue;
445
+ for (const value of legacy.entries) {
446
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || value.id === "") continue;
447
+ const entry = value;
448
+ const existing = entries.get(entry.id);
449
+ if (existing !== void 0 && !isDeepStrictEqual(existing, entry)) throw new Error(`Conflicting legacy worktree registry entries for '${entry.id}'.`);
450
+ entries.set(entry.id, entry);
451
+ }
452
+ }
453
+ const temporary = `${canonical}.${randomUUID()}.migration`;
454
+ writeJsonAtomic(temporary, {
455
+ version: 1,
456
+ entries: [...entries.values()]
457
+ });
458
+ try {
459
+ fs.linkSync(temporary, canonical);
460
+ } catch (error) {
461
+ if (error.code !== "EEXIST") throw error;
462
+ } finally {
463
+ fs.rmSync(temporary);
464
+ }
465
+ return canonical;
466
+ }
467
+ //#endregion
468
+ //#region src/services/worktreeEvents/index.ts
469
+ const GIT_WORKTREE_LIFECYCLE_EVENT = "git_worktree_lifecycle";
470
+ const GIT_WORKTREE_MESSAGE_EVENT = "git_worktree_message";
471
+ const MAX_WORKTREE_MESSAGE_BYTES = 65536;
472
+ function isMessageParty(value) {
473
+ return value === "parent" || value === "child";
474
+ }
475
+ function parseMessage(value) {
476
+ if (typeof value !== "object" || value === null) return void 0;
477
+ const record = value;
478
+ if (record.version !== 1) return void 0;
479
+ if (typeof record.worktreeId !== "string" || record.worktreeId === "") return void 0;
480
+ if (typeof record.fromSessionId !== "string" || record.fromSessionId === "") return void 0;
481
+ if (!isMessageParty(record.from)) return void 0;
482
+ if (typeof record.text !== "string" || record.text === "") return void 0;
483
+ if (Buffer.byteLength(record.text, "utf8") > 65536) return void 0;
484
+ if (typeof record.sentAt !== "string" || record.sentAt === "") return void 0;
485
+ return record;
486
+ }
487
+ function createWorktreeMessageInbox(directEvents, sessionId) {
488
+ if (sessionId === "") throw new Error("The Git message service requires a session identity.");
489
+ const messages = /* @__PURE__ */ new Map();
490
+ const unsubscribe = directEvents.subscribe(GIT_WORKTREE_MESSAGE_EVENT, sessionId, (payload) => {
491
+ const message = parseMessage(payload);
492
+ if (message === void 0) return;
493
+ const inbox = messages.get(message.worktreeId) ?? [];
494
+ if (inbox.length >= 100) inbox.shift();
495
+ inbox.push(message);
496
+ messages.set(message.worktreeId, inbox);
497
+ });
498
+ let closed = false;
499
+ return {
500
+ send(targetSessionId, message) {
501
+ if (closed) throw new Error("The Git message service is closed.");
502
+ directEvents.publish(GIT_WORKTREE_MESSAGE_EVENT, targetSessionId, message);
503
+ },
504
+ receive(worktreeId) {
505
+ if (closed) return [];
506
+ const inbox = messages.get(worktreeId);
507
+ if (inbox === void 0) return [];
508
+ messages.delete(worktreeId);
509
+ return inbox;
510
+ },
511
+ close() {
512
+ if (closed) return;
513
+ closed = true;
514
+ unsubscribe();
515
+ messages.clear();
516
+ }
517
+ };
518
+ }
519
+ function isWorktreeLifecycleEvent(value) {
520
+ if (typeof value !== "object" || value === null) return false;
521
+ const record = value;
522
+ return record.version === 1 && typeof record.repositoryRoot === "string" && record.repositoryRoot !== "";
523
+ }
524
+ //#endregion
525
+ //#region src/services/worktreeNaming/index.ts
526
+ const MAX_SLUG_LENGTH = 64;
527
+ /**
528
+ * A branch name reduced to one safe path segment.
529
+ *
530
+ * Slashes are the point: `wt/fix-auth` is a perfectly good branch and a
531
+ * terrible directory name, because the nested directory it implies is not the
532
+ * one the worktree lives in.
533
+ */
534
+ function branchSlug(branch) {
535
+ const slug = branch.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, MAX_SLUG_LENGTH).replace(/-+$/gu, "");
536
+ return slug === "" ? "worktree" : slug;
537
+ }
538
+ /**
539
+ * The directory for one worktree.
540
+ *
541
+ * The short id disambiguates two branches whose slugs collide, such as
542
+ * `feature/x` and `feature_x`, which would otherwise want the same directory.
543
+ */
544
+ function worktreeDirectory(input) {
545
+ const repository = `${input.repositoryLabel}--${input.repositoryId}`;
546
+ return `${input.worktreesRoot}/${repository}/${branchSlug(input.branch)}--${input.shortId}`;
547
+ }
548
+ /** Why a worktree cannot be created, or undefined when it can. */
549
+ function refuseSpawn(input) {
550
+ if (input.branch.trim() === "") return "A branch name is required.";
551
+ const live = input.existing.find((record) => record.branch === input.branch && record.status !== "orphaned");
552
+ if (live) return `Branch ${input.branch} already has a worktree (${live.id}).`;
553
+ }
554
+ /** Why a worktree cannot be closed, or undefined when it can. */
555
+ function refuseClose(input) {
556
+ if (!input.record) return "No worktree with that id. Call list to see the current ids.";
557
+ if (input.dirtyFiles.length === 0 || input.force) return void 0;
558
+ const names = input.dirtyFiles.slice(0, 10).join(", ");
559
+ const more = input.dirtyFiles.length > 10 ? `, and ${String(input.dirtyFiles.length - 10)} more` : "";
560
+ return `${String(input.dirtyFiles.length)} uncommitted file(s): ${names}${more}. Pass force: true to discard them.`;
561
+ }
562
+ /**
563
+ * Marks records whose process or directory is gone as orphaned.
564
+ *
565
+ * Nothing is deleted here. A doompi-git orphan owns a directory that may hold
566
+ * uncommitted work, so losing the record would lose the only pointer to it.
567
+ * Deletion is always a separate, named decision.
568
+ */
569
+ function reconcile(records, probe) {
570
+ const changed = [];
571
+ return {
572
+ records: records.map((record) => {
573
+ if (record.status === "orphaned") return record;
574
+ if (!(!probe.exists(record.path) || !probe.alive(record))) return record;
575
+ changed.push(record.id);
576
+ return {
577
+ ...record,
578
+ status: "orphaned"
579
+ };
580
+ }),
581
+ changed
582
+ };
583
+ }
584
+ /**
585
+ * What a prune would do, decided before anything is destroyed.
586
+ *
587
+ * Separating the plan from the execution is what makes dryRun honest and lets
588
+ * the destructive half be reviewed on its own.
589
+ */
590
+ function planPrune(input) {
591
+ const plan = {
592
+ remove: [],
593
+ forget: [],
594
+ untracked: [],
595
+ keptDirty: [],
596
+ keptBranches: []
597
+ };
598
+ const known = new Set(input.records.map((record) => record.path));
599
+ const listed = new Set(input.gitPaths);
600
+ for (const record of input.records) {
601
+ if (record.status !== "orphaned") continue;
602
+ if (!listed.has(record.path)) {
603
+ plan.forget.push(record);
604
+ continue;
605
+ }
606
+ if ((input.dirtyByPath.get(record.path) ?? []).length > 0) {
607
+ plan.keptDirty.push(record);
608
+ continue;
609
+ }
610
+ plan.remove.push(record);
611
+ }
612
+ for (const path of input.gitPaths) if (path.startsWith(`${input.worktreesRoot}/`) && !known.has(path)) plan.untracked.push(path);
613
+ return plan;
614
+ }
615
+ //#endregion
616
+ //#region src/services/worktreeRegistry/index.ts
617
+ const LOCK_WAIT_MS = 5e3;
618
+ const LOCK_RETRY_MS = 25;
619
+ function isRecord(value) {
620
+ if (typeof value !== "object" || value === null) return false;
621
+ const record = value;
622
+ return record.version === 1 && typeof record.id === "string" && record.id !== "" && typeof record.path === "string" && typeof record.branch === "string" && typeof record.sessionId === "string";
623
+ }
624
+ /**
625
+ * Repository mutations hold an exclusive directory lock from the read through
626
+ * the final commit. This works across independently loaded packages and hosts.
627
+ * A crashed owner leaves a visible lock, never a lease another writer may steal.
628
+ */
629
+ function createWorktreeRegistry(file) {
630
+ return {
631
+ list() {
632
+ const parsed = readJson(file);
633
+ if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.entries)) return [];
634
+ return parsed.entries.filter(isRecord);
635
+ },
636
+ replace(entries) {
637
+ writeJsonAtomic(file, {
638
+ version: 1,
639
+ entries
640
+ });
641
+ },
642
+ async transaction(operation, signal) {
643
+ const lock = `${file}.lock`;
644
+ fs.mkdirSync(path.dirname(file), { recursive: true });
645
+ const deadline = Date.now() + LOCK_WAIT_MS;
646
+ for (;;) {
647
+ signal?.throwIfAborted();
648
+ try {
649
+ fs.mkdirSync(lock, { mode: 448 });
650
+ break;
651
+ } catch (error) {
652
+ if (error.code !== "EEXIST") throw error;
653
+ if (Date.now() >= deadline) throw new DoomGitExpectedError("registry_busy", "Another worktree operation holds the repository registry.", true, "Retry after it finishes. After a host crash, inspect and remove the abandoned worktrees.json.lock directory.");
654
+ await setTimeout(LOCK_RETRY_MS, void 0, { signal });
655
+ }
656
+ }
657
+ try {
658
+ fs.writeFileSync(path.join(lock, "owner.json"), JSON.stringify({
659
+ pid: process.pid,
660
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
661
+ }), { mode: 384 });
662
+ signal?.throwIfAborted();
663
+ return await operation();
664
+ } finally {
665
+ fs.rmSync(lock, { recursive: true });
666
+ }
667
+ }
668
+ };
669
+ }
670
+ //#endregion
671
+ //#region src/services/worktreeOperations/index.ts
672
+ const GIT_WORKTREE_DELEGATION_KIND = "git.worktree.delegation";
673
+ const GIT_WORKTREE_MESSAGE_KIND = "git.worktree.message";
674
+ const GIT_WORKTREE_REPORT_KIND = "git.worktree.report";
675
+ function createWorktreeOperations(deps) {
676
+ const { git } = deps;
677
+ const sessionService = deps.sessionService;
678
+ const mirror = deps.mirror ?? mirrorComposition;
679
+ const removeStorage = deps.cleanupStorage ?? ((repositoryRoot, worktreeRoot) => {
680
+ removeSyncLocation(resolveWorktreeSyncLocation(repositoryRoot, worktreeRoot, deps.homeDir));
681
+ });
682
+ const cleanupStorage = (repositoryRoot, worktreeRoot) => {
683
+ try {
684
+ removeStorage(repositoryRoot, worktreeRoot);
685
+ } catch (error) {
686
+ throw new DoomGitExpectedError("worktree_cleanup_failed", `The worktree checkout was removed, but its generated storage could not be deleted (${error instanceof Error ? error.message : String(error)}).`, true, "Retry close or prune after fixing the storage permissions.");
687
+ }
688
+ };
689
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
690
+ const requireSessionService = () => {
691
+ if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
692
+ return sessionService;
693
+ };
694
+ const requireMessageInbox = () => {
695
+ if (deps.messageInbox === void 0) throw new HubUnavailableError("The Git message service is unavailable. Start the cockpit and try again.");
696
+ return deps.messageInbox;
697
+ };
698
+ const readSessionDelivery = () => deps.sessionDelivery?.();
699
+ const requireSessionDelivery = () => {
700
+ const delivery = readSessionDelivery();
701
+ if (delivery === void 0) throw new HubUnavailableError("The Session delivery service is unavailable. Start the cockpit and try again.");
702
+ return delivery;
703
+ };
704
+ const probe = {
705
+ alive: (record) => requireSessionService().isLive(record.sessionId),
706
+ exists: (path) => fs.existsSync(path)
707
+ };
708
+ /**
709
+ * Everything an action needs about the repository it is acting on.
710
+ *
711
+ * Resolved per call rather than cached: a session's cwd is stable, but the
712
+ * worktree registry is shared and another process may have written it since
713
+ * the last call.
714
+ */
715
+ const resolve = async (context) => {
716
+ const root = await git.repositoryRoot(context.cwd);
717
+ 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.");
718
+ const store = createWorktreeRegistry(registryFile(root, deps.homeDir));
719
+ return {
720
+ root,
721
+ store,
722
+ records: store.list()
723
+ };
724
+ };
725
+ const require = (records, id) => {
726
+ const record = records.find((entry) => entry.id === id);
727
+ if (record === void 0) throw new DoomGitExpectedError("worktree_not_found", `No worktree with id ${id}.`, false, "Call list to see the current ids.");
728
+ return record;
729
+ };
730
+ /**
731
+ * Refuses to destroy or merge a worktree another live session is using.
732
+ *
733
+ * `parentSessionId` records who asked for the worktree. Two sessions in one
734
+ * checkout share this registry, so without the check either could close the
735
+ * other's work in progress by id.
736
+ *
737
+ * Once that session is gone there is no owner left to protect, and refusing
738
+ * would strand the worktree: nothing else could ever close it.
739
+ */
740
+ const requireOwner = (context, record, action) => {
741
+ if (record.parentSessionId === context.sessionId) return;
742
+ if (!requireSessionService().isLive(record.parentSessionId)) return;
743
+ 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.`);
744
+ };
745
+ const peerFor = (context, record) => {
746
+ if (context.sessionId === record.parentSessionId) return {
747
+ sessionId: record.sessionId,
748
+ party: "parent"
749
+ };
750
+ if (context.sessionId === record.sessionId) return {
751
+ sessionId: record.parentSessionId,
752
+ party: "child"
753
+ };
754
+ throw new DoomGitExpectedError("worktree_not_owned", `Worktree ${record.id} belongs to another session.`, false, "Use a worktree owned by this session.");
755
+ };
756
+ const requirePeerLive = (peerSessionId) => {
757
+ 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.");
758
+ };
759
+ const operations = {
760
+ async spawn(context, request, options) {
761
+ const { root, store, records } = await resolve(context);
762
+ const reservations = request.reservationId === void 0 ? void 0 : requireSessionService().reservations;
763
+ if (request.reservationId !== void 0 && (!reservations || request.task !== void 0)) throw new DoomGitExpectedError("invalid_request", "Reserved worktree sessions require host setup and cannot start a task.", false, "Create the session from its pending setup card.");
764
+ const reserved = request.reservationId === void 0 ? void 0 : reservations.read(request.reservationId, context.sessionId);
765
+ const existing = reserved === void 0 ? void 0 : records.find((record) => record.sessionId === reserved.sessionId);
766
+ if (existing) {
767
+ const expectedPath = worktreeDirectory({
768
+ worktreesRoot: worktreesRoot(deps.homeDir),
769
+ repositoryLabel: repositoryLabel(root),
770
+ repositoryId: repositoryId(root),
771
+ branch: request.branch,
772
+ shortId: shortId(reserved.sessionId)
773
+ });
774
+ if (existing.parentSessionId !== context.sessionId || existing.repositoryRoot !== root || existing.branch !== request.branch || existing.path !== expectedPath || existing.path !== reserved?.cwd || request.baseRef !== void 0 && existing.baseRef !== request.baseRef || !fs.existsSync(existing.path) || !(await git.listWorktreePaths(root)).includes(existing.path) || await git.repositoryRoot(existing.path) !== existing.path || await git.currentBranch(existing.path) !== request.branch) throw new DoomGitExpectedError("invalid_request", "The reserved checkout no longer matches this setup.", false, "Inspect the existing branch and checkout; they will not be replaced.");
775
+ if (!requireSessionService().isLive(existing.sessionId)) {
776
+ if ((await requireSessionService().create({
777
+ cwd: existing.path,
778
+ name: request.name ?? request.branch,
779
+ parentSessionId: context.sessionId,
780
+ sessionProvenance: "worktree",
781
+ reservationId: request.reservationId,
782
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
783
+ })).sessionId !== existing.sessionId) throw new Error("The host did not use the reserved session identity.");
784
+ }
785
+ await reservations.complete(request.reservationId, context.sessionId);
786
+ return existing;
787
+ }
788
+ const refusal = refuseSpawn({
789
+ branch: request.branch,
790
+ existing: records
791
+ });
792
+ if (refusal !== void 0) throw new DoomGitExpectedError("worktree_exists", refusal, false, "Pick another branch name, or close it.");
793
+ const taskDelivery = request.task === void 0 ? void 0 : requireSessionDelivery();
794
+ const baseRef = request.baseRef ?? await git.remoteBaseRef(root);
795
+ if (baseRef === void 0) throw new DoomGitExpectedError("git_failed", "No remote base branch is available for this repository.", false, "Fetch a remote branch or pass an explicit baseRef.");
796
+ const id = shortId(reserved?.sessionId ?? randomUUID());
797
+ let path = worktreeDirectory({
798
+ worktreesRoot: worktreesRoot(deps.homeDir),
799
+ repositoryLabel: repositoryLabel(root),
800
+ repositoryId: repositoryId(root),
801
+ branch: request.branch,
802
+ shortId: id
803
+ });
804
+ if (request.reservationId !== void 0) path = (await reservations.prepare(request.reservationId, context.sessionId, path)).cwd;
805
+ const recovering = reserved?.cwd !== void 0 && fs.existsSync(path);
806
+ if (recovering && (!(await git.listWorktreePaths(root)).includes(path) || await git.currentBranch(path) !== request.branch)) throw new DoomGitExpectedError("invalid_request", "The reserved checkout no longer matches this setup.", false, "Inspect the existing directory; it will not be replaced.");
807
+ const cancelled = () => options?.signal?.aborted === true;
808
+ const rollback = async () => {
809
+ if (reserved) return ` The reserved checkout at ${path} was retained for recovery.`;
810
+ await git.removeWorktree({
811
+ repositoryRoot: root,
812
+ path,
813
+ force: true
814
+ }).catch(() => void 0);
815
+ return await git.deleteBranch({
816
+ repositoryRoot: root,
817
+ branch: request.branch
818
+ }).catch(() => false) ? "" : ` The branch ${request.branch} has work on it and was kept.`;
819
+ };
820
+ options?.onProgress?.(`creating branch ${request.branch}\u2026`);
821
+ if (!recovering) await git.addWorktree({
822
+ repositoryRoot: root,
823
+ path,
824
+ branch: request.branch,
825
+ baseRef
826
+ });
827
+ if (cancelled()) throw new DoomGitExpectedError("spawn_cancelled", `Cancelled before the session started.${await rollback()}`, false, reserved ? "Retry setup with the same branch to recover the reserved checkout." : "The worktree was removed; run it again when you are ready.");
828
+ options?.onProgress?.("mirroring build output…");
829
+ if (!recovering) mirror(root, path);
830
+ options?.onProgress?.("starting session…");
831
+ let sessionId;
832
+ try {
833
+ sessionId = (await requireSessionService().create({
834
+ cwd: path,
835
+ name: request.name ?? request.branch,
836
+ parentSessionId: context.sessionId,
837
+ sessionProvenance: "worktree",
838
+ ...options?.signal === void 0 ? {} : { signal: options.signal },
839
+ ...request.reservationId === void 0 ? {} : { reservationId: request.reservationId }
840
+ })).sessionId;
841
+ if (reserved && sessionId !== reserved.sessionId) throw new Error("The host did not use the reserved session identity.");
842
+ } catch (error) {
843
+ const kept = await rollback();
844
+ if (cancelled()) throw new DoomGitExpectedError("spawn_cancelled", `Cancelled while the session was starting.${kept}`, false, reserved ? "Retry setup with the same branch to recover the reserved checkout." : "The worktree was removed; run it again when you are ready.");
845
+ if (error instanceof HubUnavailableError) throw new DoomGitExpectedError("hub_unavailable", `${error.message}${kept}`, true, "Start the cockpit and try again.");
846
+ throw error;
847
+ }
848
+ const record = {
849
+ version: 1,
850
+ id,
851
+ branch: request.branch,
852
+ baseRef,
853
+ path,
854
+ repositoryRoot: root,
855
+ sessionId,
856
+ parentSessionId: context.sessionId,
857
+ status: "running",
858
+ createdAt: now().toISOString()
859
+ };
860
+ try {
861
+ store.replace([...records, record]);
862
+ } catch (error) {
863
+ await requireSessionService().close(sessionId).catch(() => void 0);
864
+ const kept = await rollback();
865
+ 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.");
866
+ }
867
+ if (request.task !== void 0 && taskDelivery !== void 0) try {
868
+ const receipt = await taskDelivery.deliver({
869
+ recipientKey: sessionId,
870
+ kind: GIT_WORKTREE_DELEGATION_KIND,
871
+ prompt: request.task,
872
+ metadata: {
873
+ worktreeId: record.id,
874
+ fromRole: "parent",
875
+ text: request.task,
876
+ sentAt: record.createdAt
877
+ }
878
+ });
879
+ const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);
880
+ 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.");
881
+ } catch (error) {
882
+ 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.`);
883
+ }
884
+ if (request.reservationId !== void 0) await reservations.complete(request.reservationId, context.sessionId);
885
+ return record;
886
+ },
887
+ async close(context, id, force) {
888
+ const { root, store, records } = await resolve(context);
889
+ const record = require(records, id);
890
+ requireOwner(context, record, "close");
891
+ const refusal = refuseClose({
892
+ record,
893
+ dirtyFiles: fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [],
894
+ force
895
+ });
896
+ if (refusal !== void 0) throw new DoomGitExpectedError("worktree_dirty", refusal, false, "Commit the work, or pass force: true.");
897
+ await requireSessionService().close(record.sessionId);
898
+ await git.removeWorktree({
899
+ repositoryRoot: root,
900
+ path: record.path,
901
+ force
902
+ });
903
+ cleanupStorage(root, record.path);
904
+ store.replace(records.filter((entry) => entry.id !== id));
905
+ return record;
906
+ },
907
+ async list(context) {
908
+ const { store, records } = await resolve(context);
909
+ const outcome = reconcile(records, probe);
910
+ if (outcome.changed.length > 0) store.replace(outcome.records);
911
+ return outcome.records;
912
+ },
913
+ async status(context, id) {
914
+ const { records } = await resolve(context);
915
+ const record = require(records, id);
916
+ return {
917
+ record,
918
+ dirtyFiles: fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : []
919
+ };
920
+ },
921
+ async merge(context, id, message) {
922
+ const { root, records } = await resolve(context);
923
+ const record = require(records, id);
924
+ requireOwner(context, record, "merge");
925
+ const parentDirty = await git.dirtyFiles(root);
926
+ 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.");
927
+ await git.mergeBranch({
928
+ repositoryRoot: root,
929
+ branch: record.branch,
930
+ ...message === void 0 ? {} : { message }
931
+ });
932
+ return record;
933
+ },
934
+ /** Sends only between the parent session and its own worktree session. */
935
+ async send(context, id, message) {
936
+ 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.");
937
+ const { records } = await resolve(context);
938
+ const record = require(records, id);
939
+ const peer = peerFor(context, record);
940
+ requirePeerLive(peer.sessionId);
941
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
942
+ const delivery = readSessionDelivery();
943
+ if (delivery !== void 0) {
944
+ const kind = peer.party === "parent" ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;
945
+ const receipt = await delivery.deliver({
946
+ recipientKey: peer.sessionId,
947
+ kind,
948
+ prompt: peer.party === "parent" ? `Parent message for worktree ${record.id}:\n\n${message}` : `Report from worktree ${record.id}:\n\n${message}`,
949
+ metadata: {
950
+ worktreeId: record.id,
951
+ fromRole: peer.party,
952
+ text: message,
953
+ sentAt
954
+ }
955
+ });
956
+ const admission = await delivery.waitForAdmission(receipt.deliveryId);
957
+ 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.");
958
+ return;
959
+ }
960
+ requireMessageInbox().send(peer.sessionId, {
961
+ version: 1,
962
+ worktreeId: record.id,
963
+ fromSessionId: context.sessionId,
964
+ from: peer.party,
965
+ text: message,
966
+ sentAt
967
+ });
968
+ },
969
+ async messages(context, id) {
970
+ const { records } = await resolve(context);
971
+ const record = require(records, id);
972
+ const peer = peerFor(context, record);
973
+ const delivery = readSessionDelivery();
974
+ if (delivery === void 0) return requireMessageInbox().receive(record.id);
975
+ return delivery.inbox({
976
+ consumed: false,
977
+ metadata: { worktreeId: record.id }
978
+ }).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) => {
979
+ delivery.consume(entry.deliveryId);
980
+ return {
981
+ version: 1,
982
+ worktreeId: record.id,
983
+ fromSessionId: entry.senderKey,
984
+ from: peer.party === "parent" ? "child" : "parent",
985
+ text: entry.state === "recovery_required" ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}` : entry.metadata.text ?? entry.prompt,
986
+ sentAt: entry.metadata.sentAt ?? ""
987
+ };
988
+ });
989
+ },
990
+ async prune(context, dryRun) {
991
+ const { root, store, records } = await resolve(context);
992
+ const reconciled = reconcile(records, probe);
993
+ const gitPaths = await git.listWorktreePaths(root);
994
+ const dirtyByPath = /* @__PURE__ */ new Map();
995
+ for (const record of reconciled.records) if (record.status === "orphaned" && fs.existsSync(record.path)) dirtyByPath.set(record.path, await git.dirtyFiles(record.path));
996
+ const plan = planPrune({
997
+ records: reconciled.records,
998
+ gitPaths,
999
+ worktreesRoot: worktreesRoot(deps.homeDir),
1000
+ dirtyByPath
1001
+ });
1002
+ if (dryRun) {
1003
+ store.replace(reconciled.records);
1004
+ return plan;
1005
+ }
1006
+ for (const record of plan.remove) {
1007
+ await git.removeWorktree({
1008
+ repositoryRoot: root,
1009
+ path: record.path,
1010
+ force: false
1011
+ });
1012
+ cleanupStorage(root, record.path);
1013
+ }
1014
+ for (const record of plan.forget) cleanupStorage(root, record.path);
1015
+ for (const record of [...plan.remove, ...plan.forget]) if (!await git.deleteBranch({
1016
+ repositoryRoot: root,
1017
+ branch: record.branch
1018
+ }).catch(() => false)) plan.keptBranches.push(record.branch);
1019
+ const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));
1020
+ store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));
1021
+ return plan;
1022
+ }
1023
+ };
1024
+ const locked = async (context, operation, signal) => {
1025
+ try {
1026
+ const { store } = await resolve(context);
1027
+ return await store.transaction(operation, signal);
1028
+ } catch (error) {
1029
+ if (signal?.aborted && !(error instanceof DoomGitExpectedError)) throw new DoomGitExpectedError("spawn_cancelled", "The worktree operation was cancelled.", false, "Inspect its recorded state before retrying.");
1030
+ if ([
1031
+ "ENOTDIR",
1032
+ "EACCES",
1033
+ "EROFS",
1034
+ "ENOSPC"
1035
+ ].includes(String(error.code))) throw new DoomGitExpectedError("registry_write_failed", "The worktree registry is not writable.", true, "Check permissions and free space before retrying.");
1036
+ throw error;
1037
+ }
1038
+ };
1039
+ return {
1040
+ ...operations,
1041
+ spawn: (context, request, options) => {
1042
+ if (sessionService === void 0) return Promise.reject(new DoomGitExpectedError("hub_unavailable", "The cockpit session service is unavailable.", true, "Use the cockpit worktree tool after its Git server facet is available."));
1043
+ return locked(context, () => operations.spawn(context, request, options), options?.signal);
1044
+ },
1045
+ close: (context, id, force) => locked(context, () => operations.close(context, id, force)),
1046
+ list: (context) => locked(context, () => operations.list(context)),
1047
+ merge: (context, id, message) => locked(context, () => operations.merge(context, id, message)),
1048
+ prune: (context, dryRun) => locked(context, () => operations.prune(context, dryRun))
1049
+ };
1050
+ }
1051
+ //#endregion
1052
+ export { isWorktreeLifecycleEvent as a, HubUnavailableError as c, createWorktreeMessageInbox as i, invalidRequest as l, createWorktreeRegistry as n, registryFile as o, GIT_WORKTREE_LIFECYCLE_EVENT as r, DoomGitExpectedError as s, createWorktreeOperations as t, createWorktreeGit as u };
1053
+
1054
+ //# sourceMappingURL=worktreeOperations-DAbs0ZTX.mjs.map