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