@ai-hero/sandcastle 0.13.0 → 0.14.1

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 (77) hide show
  1. package/README.md +3 -3
  2. package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
  3. package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
  4. package/dist/chunk-4BB7DNPW.js.map +1 -0
  5. package/dist/chunk-4GZMUHVO.js +60 -0
  6. package/dist/chunk-4GZMUHVO.js.map +1 -0
  7. package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
  8. package/dist/chunk-7JUTKCHL.js.map +1 -0
  9. package/dist/chunk-7PHPLDVS.js +284 -0
  10. package/dist/chunk-7PHPLDVS.js.map +1 -0
  11. package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
  12. package/dist/chunk-BXLS4HRY.js.map +1 -0
  13. package/dist/chunk-EM4QNWKF.js +3161 -0
  14. package/dist/chunk-EM4QNWKF.js.map +1 -0
  15. package/dist/chunk-EXYXBRCX.js +60 -0
  16. package/dist/chunk-EXYXBRCX.js.map +1 -0
  17. package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
  18. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  19. package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
  20. package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
  21. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  22. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  23. package/dist/chunk-SAQXFLO2.js +1268 -0
  24. package/dist/chunk-SAQXFLO2.js.map +1 -0
  25. package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
  26. package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
  27. package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
  28. package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
  29. package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
  30. package/dist/chunk-WYOGXC72.js.map +1 -0
  31. package/dist/chunk-YDQW5IOY.js +799 -0
  32. package/dist/chunk-YDQW5IOY.js.map +1 -0
  33. package/dist/index.d.ts +51 -4
  34. package/dist/index.js +892 -2018
  35. package/dist/index.js.map +1 -1
  36. package/dist/main.js +322 -251
  37. package/dist/main.js.map +1 -1
  38. package/dist/sandboxes/bwrap.d.ts +1 -1
  39. package/dist/sandboxes/bwrap.js +9 -14
  40. package/dist/sandboxes/bwrap.js.map +1 -1
  41. package/dist/sandboxes/daytona.d.ts +1 -1
  42. package/dist/sandboxes/daytona.js +183 -136
  43. package/dist/sandboxes/daytona.js.map +1 -1
  44. package/dist/sandboxes/docker.d.ts +23 -1
  45. package/dist/sandboxes/docker.js +7 -3
  46. package/dist/sandboxes/e2b.d.ts +41 -0
  47. package/dist/sandboxes/e2b.js +202 -0
  48. package/dist/sandboxes/e2b.js.map +1 -0
  49. package/dist/sandboxes/modal.d.ts +78 -0
  50. package/dist/sandboxes/modal.js +171 -0
  51. package/dist/sandboxes/modal.js.map +1 -0
  52. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  53. package/dist/sandboxes/no-sandbox.js +1 -1
  54. package/dist/sandboxes/podman.d.ts +27 -4
  55. package/dist/sandboxes/podman.js +19 -43
  56. package/dist/sandboxes/podman.js.map +1 -1
  57. package/dist/sandboxes/seatbelt.d.ts +2 -2
  58. package/dist/sandboxes/seatbelt.js +10 -7
  59. package/dist/sandboxes/seatbelt.js.map +1 -1
  60. package/dist/sandboxes/sprites.d.ts +54 -0
  61. package/dist/sandboxes/sprites.js +219 -0
  62. package/dist/sandboxes/sprites.js.map +1 -0
  63. package/dist/sandboxes/vercel.d.ts +10 -1
  64. package/dist/sandboxes/vercel.js +74 -46
  65. package/dist/sandboxes/vercel.js.map +1 -1
  66. package/dist/templates/parallel-planner/main.mts +43 -21
  67. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  68. package/dist/templates/sequential-reviewer/main.mts +1 -1
  69. package/package.json +36 -4
  70. package/dist/chunk-4EIVTSOZ.js +0 -93
  71. package/dist/chunk-4EIVTSOZ.js.map +0 -1
  72. package/dist/chunk-7N7AMUYA.js.map +0 -1
  73. package/dist/chunk-A4C2FG74.js.map +0 -1
  74. package/dist/chunk-LWNC4UTZ.js.map +0 -1
  75. package/dist/chunk-NMQ5Z6YG.js.map +0 -1
  76. package/dist/chunk-U42XXICG.js.map +0 -1
  77. package/dist/chunk-XCYK7I45.js.map +0 -1
@@ -0,0 +1,3161 @@
1
+ import { createRequire } from 'node:module';
2
+ import { patchGitMountsForWindows, SANDBOX_REPO_DIR, removeMountTempDirs, normalizeMounts, makeSandboxFromHandle } from './chunk-7PHPLDVS.js';
3
+ import { registerShutdown } from './chunk-EXYXBRCX.js';
4
+ import { FileSystem_exports, WorktreeError, withTimeout, CopyToWorktreeTimeoutError, AgentIdleTimeoutError, AgentError, ContainerStartTimeoutError, SyncInTimeoutError, ExecError, HookTimeoutError, CopyToWorktreeError, SyncError, WorktreeTimeoutError, SyncOutPathError, HostGitError, CommitCollectionTimeoutError, GitSetupTimeoutError, MergeToHostTimeoutError } from './chunk-YDQW5IOY.js';
5
+ import { Effect_exports, Context_exports, Layer_exports, Console_exports, Exit_exports, Option_exports, DateTime_exports, Clock_exports, Predicate_exports, Ref_exports, Schedule_exports, Duration_exports, Deferred_exports, Runtime_exports } from './chunk-JEQ4IVQM.js';
6
+ import { join, dirname, relative, resolve, posix, basename, isAbsolute, sep, normalize, win32, delimiter } from 'path';
7
+ import * as clack from '@clack/prompts';
8
+ import { styleText } from 'util';
9
+ import { randomBytes } from 'crypto';
10
+ import { execFile, spawn } from 'child_process';
11
+ import { tmpdir, devNull } from 'os';
12
+ import { readFile, lstat, mkdir as mkdir$1, writeFile as writeFile$1, readdir as readdir$1, stat as stat$1, realpath, access as access$1, constants, readlink } from 'fs';
13
+ import { stat, mkdir, mkdtemp, rm, access, readdir, writeFile, readFile as readFile$1 } from 'fs/promises';
14
+
15
+ createRequire(import.meta.url);
16
+ var severityToClack = {
17
+ info: clack.log.info,
18
+ success: clack.log.success,
19
+ warn: clack.log.warning,
20
+ error: clack.log.error
21
+ };
22
+ var terminalStyle = {
23
+ status: (message) => styleText("bold", message),
24
+ summaryTitle: (title) => styleText("bold", title),
25
+ summaryRow: (key, value) => `${styleText("bold", key)}: ${styleText("dim", value)}`,
26
+ toolCall: (text) => styleText("dim", text)
27
+ };
28
+ var printClackText = (text) => {
29
+ const trimmed = text.replaceAll(/^\n+|\n+$/gu, "");
30
+ if (trimmed.trim().length > 0) {
31
+ clack.log.message(trimmed);
32
+ }
33
+ };
34
+ var makeTextBuffer = () => {
35
+ let pendingText = "";
36
+ return {
37
+ flush: () => {
38
+ const text = pendingText;
39
+ pendingText = "";
40
+ printClackText(text);
41
+ },
42
+ write: (chunk) => {
43
+ pendingText += chunk;
44
+ const lastNewline = pendingText.lastIndexOf("\n");
45
+ if (lastNewline === -1) {
46
+ return;
47
+ }
48
+ const complete = pendingText.slice(0, lastNewline);
49
+ pendingText = pendingText.slice(lastNewline + 1);
50
+ printClackText(complete);
51
+ }
52
+ };
53
+ };
54
+ var clackSpinner = (flushText) => (message, effect) => Effect_exports.acquireUseRelease(
55
+ Effect_exports.sync(() => {
56
+ flushText();
57
+ const s = clack.spinner();
58
+ s.start(message);
59
+ return s;
60
+ }),
61
+ () => effect,
62
+ (s, exit) => Effect_exports.sync(() => {
63
+ if (exit._tag === "Success") {
64
+ s.stop(message);
65
+ } else {
66
+ s.stop(`${message} (failed)`);
67
+ }
68
+ })
69
+ );
70
+ var clackTaskLog = (flushText) => (title, effect) => Effect_exports.acquireUseRelease(
71
+ Effect_exports.sync(() => {
72
+ flushText();
73
+ return clack.taskLog({ title });
74
+ }),
75
+ (log2) => effect((msg) => {
76
+ log2.message(msg);
77
+ }),
78
+ (log2, exit) => Effect_exports.sync(() => {
79
+ if (exit._tag === "Success") {
80
+ log2.success(title, { showLog: true });
81
+ } else {
82
+ log2.error(title, { showLog: true });
83
+ }
84
+ })
85
+ );
86
+ var makeClackDisplayService = Effect_exports.gen(function* () {
87
+ const text = makeTextBuffer();
88
+ const sync = (f) => Effect_exports.sync(() => {
89
+ text.flush();
90
+ f();
91
+ });
92
+ yield* Effect_exports.addFinalizer(() => Effect_exports.sync(text.flush));
93
+ return {
94
+ intro: (title) => sync(() => {
95
+ clack.intro(styleText("inverse", ` ${title} `));
96
+ }),
97
+ status: (message, severity) => sync(() => {
98
+ severityToClack[severity](terminalStyle.status(message));
99
+ }),
100
+ spinner: clackSpinner(text.flush),
101
+ summary: (title, rows) => sync(() => {
102
+ const lines = Object.entries(rows).map(([key, value]) => terminalStyle.summaryRow(key, value)).join("\n");
103
+ clack.note(lines, terminalStyle.summaryTitle(title));
104
+ }),
105
+ taskLog: clackTaskLog(text.flush),
106
+ text: (message) => sync(() => {
107
+ clack.log.message(message);
108
+ }),
109
+ textChunk: (chunk) => Effect_exports.sync(() => {
110
+ text.write(chunk);
111
+ }),
112
+ toolCall: (name, formattedArgs) => sync(() => {
113
+ clack.log.step(terminalStyle.toolCall(`${name}(${formattedArgs})`));
114
+ })
115
+ };
116
+ });
117
+
118
+ // src/Display.ts
119
+ var Display = class extends Context_exports.Tag("@ai-hero/sandcastle/Display")() {
120
+ };
121
+ var silentDisplayService = (ref) => {
122
+ const record = (entry) => Ref_exports.update(ref, (entries) => [...entries, entry]);
123
+ return {
124
+ intro: (title) => record({ _tag: "intro", title }),
125
+ status: (message, severity) => record({ _tag: "status", message, severity }),
126
+ spinner: (message, effect) => record({ _tag: "spinner", message }).pipe(Effect_exports.andThen(effect)),
127
+ summary: (title, rows) => record({ _tag: "summary", title, rows }),
128
+ taskLog: (title, effect) => {
129
+ const messages = [];
130
+ return Effect_exports.flatMap(
131
+ effect((msg) => {
132
+ messages.push(msg);
133
+ }),
134
+ (result) => Effect_exports.as(
135
+ record({ _tag: "taskLog", title, messages: [...messages] }),
136
+ result
137
+ )
138
+ );
139
+ },
140
+ text: (message) => record({ _tag: "text", message }),
141
+ textChunk: (chunk) => record({ _tag: "textChunk", message: chunk }),
142
+ toolCall: (name, formattedArgs) => record({ _tag: "toolCall", name, formattedArgs })
143
+ };
144
+ };
145
+ var SilentDisplay = {
146
+ layer: (ref) => Layer_exports.succeed(Display, silentDisplayService(ref))
147
+ };
148
+ var makeLogWriter = (fs, filePath) => {
149
+ let midLine = false;
150
+ return {
151
+ appendToLog: (line) => Effect_exports.suspend(() => {
152
+ const prefix = midLine ? "\n" : "";
153
+ midLine = false;
154
+ return fs.writeFileString(filePath, `${prefix}${line}
155
+ `, { flag: "a" }).pipe(Effect_exports.ignore);
156
+ }),
157
+ appendRaw: (chunk) => Effect_exports.suspend(() => {
158
+ if (chunk.length === 0) {
159
+ return Effect_exports.void;
160
+ }
161
+ midLine = !chunk.endsWith("\n");
162
+ return fs.writeFileString(filePath, chunk, { flag: "a" }).pipe(Effect_exports.ignore);
163
+ })
164
+ };
165
+ };
166
+ var elapsedSince = (start) => Clock_exports.currentTimeMillis.pipe(
167
+ Effect_exports.map((now) => ((now - start) / 1e3).toFixed(1))
168
+ );
169
+ var fileDisplayService = ({
170
+ appendToLog,
171
+ appendRaw
172
+ }) => ({
173
+ intro: () => Effect_exports.void,
174
+ status: (message, _severity) => appendToLog(message.replace(/^\[[^\]]+\] /u, "")),
175
+ spinner: (message, effect) => Effect_exports.gen(function* () {
176
+ yield* appendToLog(`${message}...`);
177
+ const start = yield* Clock_exports.currentTimeMillis;
178
+ const result = yield* effect;
179
+ const elapsed = yield* elapsedSince(start);
180
+ yield* appendToLog(`${message} done (${elapsed}s)`);
181
+ return result;
182
+ }),
183
+ summary: (title, rows) => {
184
+ const lines = Object.entries(rows).map(([key, value]) => ` ${key}: ${value}`).join("\n");
185
+ return appendToLog(`${title}
186
+ ${lines}`);
187
+ },
188
+ taskLog: (title, effect) => Effect_exports.gen(function* () {
189
+ yield* appendToLog(title);
190
+ const start = yield* Clock_exports.currentTimeMillis;
191
+ const messages = [];
192
+ const result = yield* effect((msg) => {
193
+ messages.push(msg);
194
+ });
195
+ const elapsed = yield* elapsedSince(start);
196
+ for (const msg of messages) {
197
+ yield* appendToLog(` ${msg}`);
198
+ }
199
+ yield* appendToLog(`${title} done (${elapsed}s)`);
200
+ return result;
201
+ }),
202
+ text: (message) => appendToLog(message),
203
+ textChunk: (chunk) => appendRaw(chunk),
204
+ toolCall: (name, formattedArgs) => appendToLog(`${name}(${formattedArgs})`)
205
+ });
206
+ var FileDisplay = {
207
+ layer: (filePath) => Layer_exports.effect(
208
+ Display,
209
+ Effect_exports.gen(function* () {
210
+ const fs = yield* FileSystem_exports.FileSystem;
211
+ yield* fs.makeDirectory(dirname(filePath), { recursive: true }).pipe(Effect_exports.orDie);
212
+ const delimiter2 = `
213
+ --- Run started: ${DateTime_exports.formatIso(yield* DateTime_exports.now)} ---
214
+ `;
215
+ yield* fs.writeFileString(filePath, delimiter2, { flag: "a" }).pipe(Effect_exports.orDie);
216
+ return fileDisplayService(makeLogWriter(fs, filePath));
217
+ })
218
+ )
219
+ };
220
+ var ClackDisplay = {
221
+ layer: Layer_exports.scoped(Display, makeClackDisplayService)
222
+ };
223
+
224
+ // src/ErrorHandler.ts
225
+ var formatErrorMessage = (error) => {
226
+ switch (error._tag) {
227
+ case "ExecError": {
228
+ return `Command failed in sandbox (${error.command}): ${error.message}`;
229
+ }
230
+ case "ExecHostError": {
231
+ return `Command failed on host (${error.command}): ${error.message}`;
232
+ }
233
+ case "CopyError": {
234
+ return `File copy failed: ${error.message}`;
235
+ }
236
+ case "DockerError": {
237
+ return `Docker operation failed: ${error.message}. Is Docker running?`;
238
+ }
239
+ case "PodmanError": {
240
+ return `Podman operation failed: ${error.message}. Is Podman running?`;
241
+ }
242
+ case "SyncError": {
243
+ return `Git sync failed: ${error.message}`;
244
+ }
245
+ case "WorktreeError": {
246
+ return `Git worktree operation failed: ${error.message}`;
247
+ }
248
+ case "PromptError": {
249
+ return `Failed to resolve prompt: ${error.message}`;
250
+ }
251
+ case "AgentError": {
252
+ return `Agent invocation failed: ${error.message}`;
253
+ }
254
+ case "ConfigDirError":
255
+ case "InitError":
256
+ case "AgentIdleTimeoutError":
257
+ case "WorktreeTimeoutError":
258
+ case "ContainerStartTimeoutError":
259
+ case "CopyToWorktreeTimeoutError":
260
+ case "CopyToWorktreeError":
261
+ case "SyncInTimeoutError":
262
+ case "HookTimeoutError":
263
+ case "GitSetupTimeoutError":
264
+ case "PromptExpansionTimeoutError":
265
+ case "CommitCollectionTimeoutError":
266
+ case "MergeToHostTimeoutError":
267
+ case "SessionCaptureError":
268
+ case "SyncOutPathError":
269
+ case "CwdError":
270
+ case "ImageNotFoundError": {
271
+ return error.message;
272
+ }
273
+ }
274
+ };
275
+ var showErrorAndExit = (error) => Effect_exports.gen(function* () {
276
+ const d = yield* Display;
277
+ yield* d.status(formatErrorMessage(error), "error");
278
+ return yield* Effect_exports.sync(() => process.exit(1));
279
+ });
280
+ var sandboxErrorTags = {
281
+ ExecError: true,
282
+ ExecHostError: true,
283
+ CopyError: true,
284
+ DockerError: true,
285
+ PodmanError: true,
286
+ SyncError: true,
287
+ SyncOutPathError: true,
288
+ WorktreeError: true,
289
+ PromptError: true,
290
+ AgentError: true,
291
+ ConfigDirError: true,
292
+ InitError: true,
293
+ AgentIdleTimeoutError: true,
294
+ WorktreeTimeoutError: true,
295
+ ContainerStartTimeoutError: true,
296
+ CopyToWorktreeTimeoutError: true,
297
+ CopyToWorktreeError: true,
298
+ SyncInTimeoutError: true,
299
+ HookTimeoutError: true,
300
+ GitSetupTimeoutError: true,
301
+ PromptExpansionTimeoutError: true,
302
+ CommitCollectionTimeoutError: true,
303
+ MergeToHostTimeoutError: true,
304
+ SessionCaptureError: true,
305
+ CwdError: true,
306
+ ImageNotFoundError: true
307
+ };
308
+ var isSandboxError = (error) => Predicate_exports.hasProperty(error, "_tag") && typeof error._tag === "string" && Object.hasOwn(sandboxErrorTags, error._tag);
309
+ var withFriendlyErrors = (effect) => Effect_exports.catchIf(
310
+ effect,
311
+ (error) => isSandboxError(error),
312
+ (error) => showErrorAndExit(error)
313
+ );
314
+
315
+ // src/hostGitEntries.ts
316
+ var TRUSTED_SCOPES = /* @__PURE__ */ new Set([
317
+ "system",
318
+ "global",
319
+ "command"
320
+ ]);
321
+ var isTrusted = (entry) => TRUSTED_SCOPES.has(entry.scope);
322
+ var lastTrustedValue = (entries, keys) => {
323
+ const trusted = entries.filter((e) => isTrusted(e) && keys.includes(e.key));
324
+ const last = trusted.at(-1);
325
+ return last === void 0 ? void 0 : last.value ?? "true";
326
+ };
327
+ var keyAndValue = (entry) => {
328
+ const newline = entry.indexOf("\n");
329
+ return newline === -1 ? { key: entry, value: void 0 } : { key: entry.slice(0, newline), value: entry.slice(newline + 1) };
330
+ };
331
+ var parseConfigList = (output) => {
332
+ const fields = output.split("\0");
333
+ const entries = [];
334
+ for (let i = 0; i + 2 < fields.length; i += 3) {
335
+ entries.push({
336
+ scope: fields[i] ?? "",
337
+ origin: fields[i + 1] ?? "",
338
+ ...keyAndValue(fields[i + 2] ?? "")
339
+ });
340
+ }
341
+ return entries;
342
+ };
343
+ var parseFileConfigList = (output, file, scope) => output.split("\0").filter((entry) => entry !== "").map((entry) => {
344
+ const { key, value } = keyAndValue(entry);
345
+ return { scope, origin: `file:${file}`, key, value };
346
+ });
347
+
348
+ // src/hostGitHooks.ts
349
+ var hookKeyParts = (key) => {
350
+ const last = key.lastIndexOf(".");
351
+ return key.startsWith("hook.") && last > "hook.".length ? { name: key.slice("hook.".length, last), variable: key.slice(last + 1) } : void 0;
352
+ };
353
+ var RUNNING_HOOK_VARIABLES = /* @__PURE__ */ new Set([
354
+ "command",
355
+ "event",
356
+ "parallel"
357
+ ]);
358
+ var overridesForHook = (entries, name, repoVariables) => {
359
+ const key = (variable) => `hook.${name}.${variable}`;
360
+ const enabled = lastTrustedValue(entries, [key("enabled")]);
361
+ const command = lastTrustedValue(entries, [key("command")]);
362
+ if (command !== void 0) {
363
+ const events = entries.filter((e) => isTrusted(e) && e.key === key("event")).map((e) => [key("event"), e.value ?? ""]);
364
+ return [
365
+ [key("command"), command],
366
+ // An empty event clears the list; then the user's events, in order.
367
+ [key("event"), ""],
368
+ ...events,
369
+ [key("enabled"), enabled ?? "true"]
370
+ ];
371
+ }
372
+ if ([...repoVariables].some((v) => RUNNING_HOOK_VARIABLES.has(v))) {
373
+ return [[key("enabled"), "false"]];
374
+ }
375
+ return enabled === void 0 ? [] : [[key("enabled"), enabled]];
376
+ };
377
+ var hookOverrides = (entries) => {
378
+ const repoVariables = /* @__PURE__ */ new Map();
379
+ for (const entry of entries) {
380
+ const parts = isTrusted(entry) ? void 0 : hookKeyParts(entry.key);
381
+ if (parts !== void 0) {
382
+ const variables = repoVariables.get(parts.name) ?? /* @__PURE__ */ new Set();
383
+ variables.add(parts.variable);
384
+ repoVariables.set(parts.name, variables);
385
+ }
386
+ }
387
+ return [...repoVariables].flatMap(
388
+ ([name, variables]) => overridesForHook(entries, name, variables)
389
+ );
390
+ };
391
+
392
+ // src/hostGitConfig.ts
393
+ var PINNED_GROUPS = [
394
+ [["core.fsmonitor"], "false"],
395
+ [["core.hookspath"], devNull],
396
+ [["core.pager"], "cat"],
397
+ [["core.editor"], "true"],
398
+ [["sequence.editor"], "true"],
399
+ [["diff.external"], ""],
400
+ [["gpg.program", "gpg.openpgp.program"], "gpg"],
401
+ [["gpg.x509.program"], "gpgsm"],
402
+ [["gpg.ssh.program"], "ssh-keygen"],
403
+ [["protocol.ext.allow"], "never"],
404
+ [["submodule.recurse"], "false"],
405
+ [["fetch.recursesubmodules"], "false"]
406
+ ];
407
+ var REPO_SET_KEYS = /* @__PURE__ */ new Map([
408
+ ["core.sshcommand", "ssh"],
409
+ ["core.askpass", ""],
410
+ ["core.alternaterefscommand", ""],
411
+ ["gpg.ssh.defaultkeycommand", ""]
412
+ ]);
413
+ var NAMED_KEYS = /* @__PURE__ */ new Map([
414
+ ["filter.clean", ""],
415
+ ["filter.smudge", ""],
416
+ ["filter.process", ""],
417
+ ["filter.required", "false"],
418
+ ["diff.command", ""],
419
+ ["diff.textconv", ""],
420
+ ["merge.driver", ""],
421
+ ["remote.uploadpack", "git-upload-pack"],
422
+ ["remote.receivepack", "git-receive-pack"]
423
+ ]);
424
+ var namedKeyClass = (key) => {
425
+ const first = key.indexOf(".");
426
+ const last = key.lastIndexOf(".");
427
+ if (first === -1 || first === last) {
428
+ return void 0;
429
+ }
430
+ return `${key.slice(0, first)}.${key.slice(last + 1)}`;
431
+ };
432
+ var isCredentialHelperKey = (key) => key.startsWith("credential.") && key.endsWith(".helper");
433
+ var pinnedOverrides = (entries) => PINNED_GROUPS.flatMap(([keys, neutral]) => {
434
+ const value = lastTrustedValue(entries, keys) ?? neutral;
435
+ return keys.map((key) => [key, value]);
436
+ });
437
+ var neutralForRepoSetKey = (key) => {
438
+ const exact = REPO_SET_KEYS.get(key);
439
+ if (exact !== void 0) {
440
+ return exact;
441
+ }
442
+ const named2 = namedKeyClass(key);
443
+ return named2 === void 0 ? void 0 : NAMED_KEYS.get(named2);
444
+ };
445
+ var repoSetOverrides = (entries) => {
446
+ const repoKeys = new Set(
447
+ entries.filter((e) => !isTrusted(e)).map((e) => e.key)
448
+ );
449
+ const overrides = [];
450
+ for (const key of repoKeys) {
451
+ const neutral = neutralForRepoSetKey(key);
452
+ if (neutral !== void 0) {
453
+ overrides.push([key, lastTrustedValue(entries, [key]) ?? neutral]);
454
+ }
455
+ }
456
+ if (repoKeys.has("core.gitproxy")) {
457
+ overrides.push(["protocol.git.allow", "never"]);
458
+ }
459
+ return overrides;
460
+ };
461
+ var credentialOverrides = (entries) => {
462
+ const keys = /* @__PURE__ */ new Set([
463
+ "credential.helper",
464
+ ...entries.map((e) => e.key).filter((key) => isCredentialHelperKey(key))
465
+ ]);
466
+ return [
467
+ ...[...keys].map((key) => [key, ""]),
468
+ ...entries.filter((e) => isTrusted(e) && keys.has(e.key)).map((e) => [e.key, e.value ?? ""])
469
+ ];
470
+ };
471
+ var hardeningOverrides = (entries) => [
472
+ ...pinnedOverrides(entries),
473
+ ...repoSetOverrides(entries),
474
+ ...credentialOverrides(entries),
475
+ ...hookOverrides(entries)
476
+ ];
477
+ var withConfigOverrides = (env, overrides) => {
478
+ const existing = Number(env["GIT_CONFIG_COUNT"] ?? "0");
479
+ const start = Number.isInteger(existing) && existing > 0 ? existing : 0;
480
+ const result = {
481
+ ...env,
482
+ GIT_CONFIG_COUNT: String(start + overrides.length)
483
+ };
484
+ for (const [offset, [key, value]] of overrides.entries()) {
485
+ result[`GIT_CONFIG_KEY_${start + offset}`] = key;
486
+ result[`GIT_CONFIG_VALUE_${start + offset}`] = value;
487
+ }
488
+ return result;
489
+ };
490
+ var refusal = (args, message) => new HostGitError({
491
+ message: `Refusing to run git on the host: ${message}`,
492
+ args,
493
+ stdout: "",
494
+ stderr: ""
495
+ });
496
+ var fsCall = (args, what, call) => Effect_exports.async((resume) => {
497
+ call((error, value) => {
498
+ resume(
499
+ error === null ? Effect_exports.succeed(value) : Effect_exports.fail(refusal(args, `${what}: ${error.message}`))
500
+ );
501
+ });
502
+ });
503
+ var realPath = (args, p) => fsCall(args, `cannot resolve ${p}`, (done) => {
504
+ realpath(p, done);
505
+ });
506
+ var readText = (args, p) => fsCall(args, `cannot read ${p}`, (done) => {
507
+ readFile(p, "utf8", done);
508
+ });
509
+ var statOf = (args, p) => fsCall(args, `cannot stat ${p}`, (done) => {
510
+ lstat(p, done);
511
+ });
512
+ var isManagedWorktree = (dir) => {
513
+ const parent = dirname(resolve(dir));
514
+ return basename(parent) === "worktrees" && basename(dirname(parent)) === ".sandcastle";
515
+ };
516
+ var GITDIR_LINE = /^gitdir: (?<path>.+)$/u;
517
+ var readLinkedWorktree = (args, dir) => Effect_exports.gen(function* () {
518
+ const dotGit = join(dir, ".git");
519
+ const pointer = yield* readText(args, dotGit);
520
+ const path = GITDIR_LINE.exec(pointer.trim())?.groups?.["path"];
521
+ if (path === void 0) {
522
+ return yield* refusal(args, `${dotGit} is not a gitdir pointer`);
523
+ }
524
+ const gitDir = yield* realPath(args, resolve(dir, path));
525
+ const commondir = yield* readText(args, join(gitDir, "commondir"));
526
+ const commonDir = yield* realPath(args, resolve(gitDir, commondir.trim()));
527
+ const layoutParent = yield* realPath(args, dirname(dirname(gitDir)));
528
+ if (basename(dirname(gitDir)) !== "worktrees" || layoutParent !== commonDir) {
529
+ return yield* refusal(
530
+ args,
531
+ `${dotGit} points at ${gitDir}, which is not a worktree of ${commonDir}`
532
+ );
533
+ }
534
+ return { gitDir, commonDir };
535
+ });
536
+ var commonDirOf = (args, repoDir) => Effect_exports.gen(function* () {
537
+ const dotGit = join(repoDir, ".git");
538
+ const stat5 = yield* statOf(args, dotGit);
539
+ if (stat5.isDirectory()) {
540
+ return yield* realPath(args, dotGit);
541
+ }
542
+ const linked = yield* readLinkedWorktree(args, repoDir);
543
+ return linked.commonDir;
544
+ });
545
+ var resolveGitDirPins = (cwd, args) => Effect_exports.gen(function* () {
546
+ const dotGit = join(cwd, ".git");
547
+ const managed = isManagedWorktree(cwd);
548
+ const stat5 = yield* statOf(args, dotGit).pipe(Effect_exports.option);
549
+ if (stat5._tag === "None" || stat5.value.isDirectory()) {
550
+ if (managed) {
551
+ return yield* refusal(args, `${dotGit} is not a worktree's .git file`);
552
+ }
553
+ const none = {};
554
+ return none;
555
+ }
556
+ if (!stat5.value.isFile()) {
557
+ return yield* refusal(args, `${dotGit} is not a regular file`);
558
+ }
559
+ const dirs = yield* readLinkedWorktree(args, cwd);
560
+ if (managed) {
561
+ const repoDir = dirname(dirname(dirname(resolve(cwd))));
562
+ const expected = yield* commonDirOf(args, repoDir);
563
+ if (dirs.commonDir !== expected) {
564
+ return yield* refusal(
565
+ args,
566
+ `${dotGit} leads to ${dirs.commonDir}, not to ${expected}`
567
+ );
568
+ }
569
+ }
570
+ return {
571
+ GIT_DIR: dirs.gitDir,
572
+ GIT_COMMON_DIR: dirs.commonDir,
573
+ GIT_WORK_TREE: cwd
574
+ };
575
+ });
576
+ var INCLUDED_SCOPE = "included";
577
+ var MAX_INCLUDE_DEPTH = 10;
578
+ var isIncludeKey = (key) => key === "include.path" || key.startsWith("includeif.") && key.endsWith(".path");
579
+ var includeTarget = (entry, cwd, env) => {
580
+ const path = entry.value;
581
+ if (path === void 0 || path === "" || !entry.origin.startsWith("file:")) {
582
+ return void 0;
583
+ }
584
+ const including = resolve(cwd, entry.origin.slice("file:".length));
585
+ if (path.startsWith("~/")) {
586
+ const home = env["HOME"];
587
+ return home === void 0 ? void 0 : join(home, path.slice(2));
588
+ }
589
+ if (path.startsWith("~") || path.startsWith("%(prefix)/")) {
590
+ return void 0;
591
+ }
592
+ return isAbsolute(path) ? path : resolve(dirname(including), path);
593
+ };
594
+ var isRegularFile = (path) => Effect_exports.async((resume) => {
595
+ stat$1(path, (error, stats) => {
596
+ resume(Effect_exports.succeed(error === null && stats?.isFile() === true));
597
+ });
598
+ });
599
+ var repoIncludedEntries = (entries, { cwd, env, listFile }) => Effect_exports.gen(function* () {
600
+ const seen = /* @__PURE__ */ new Set();
601
+ const found = [];
602
+ let pending = entries.filter((e) => !isTrusted(e) && isIncludeKey(e.key));
603
+ for (let depth = 0; depth < MAX_INCLUDE_DEPTH && pending.length > 0; depth++) {
604
+ const next = [];
605
+ for (const include of pending) {
606
+ const file = includeTarget(include, cwd, env);
607
+ if (file !== void 0 && !seen.has(file)) {
608
+ seen.add(file);
609
+ if (yield* isRegularFile(file)) {
610
+ const read = parseFileConfigList(
611
+ yield* listFile(file),
612
+ file,
613
+ INCLUDED_SCOPE
614
+ );
615
+ found.push(...read);
616
+ next.push(...read.filter((e) => isIncludeKey(e.key)));
617
+ }
618
+ }
619
+ }
620
+ pending = next;
621
+ }
622
+ return found;
623
+ });
624
+ var SAFE_PROTOCOLS = "file:git:http:https:ssh";
625
+ var pathKey = (env) => Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
626
+ var attempt = (call) => Effect_exports.async((resume) => {
627
+ call((error, value) => {
628
+ resume(
629
+ Effect_exports.succeed(error === null ? Option_exports.some(value) : Option_exports.none())
630
+ );
631
+ });
632
+ });
633
+ var formsOf = (p) => attempt((done) => {
634
+ realpath(p, done);
635
+ }).pipe(
636
+ Effect_exports.map(
637
+ (real) => Option_exports.isSome(real) ? [resolve(p), real.value] : [resolve(p)]
638
+ )
639
+ );
640
+ var isWithin = (child, parent) => {
641
+ const rel = relative(parent, child);
642
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
643
+ };
644
+ var repoRoots = (cwd, commonDir) => {
645
+ if (commonDir === void 0) {
646
+ return [cwd];
647
+ }
648
+ return basename(commonDir) === ".git" ? [cwd, commonDir, dirname(commonDir)] : [cwd, commonDir];
649
+ };
650
+ var trustedPath = (pathValue, roots) => Effect_exports.gen(function* () {
651
+ const rootForms = (yield* Effect_exports.all(roots.map((r) => formsOf(r)))).flat();
652
+ const entries = pathValue.split(delimiter).filter((entry) => entry !== "" && isAbsolute(entry));
653
+ const checked = yield* Effect_exports.all(
654
+ entries.map(
655
+ (entry) => formsOf(entry).pipe(
656
+ Effect_exports.map((forms) => ({
657
+ entry,
658
+ inside: forms.some(
659
+ (form) => rootForms.some((root) => isWithin(form, root))
660
+ )
661
+ }))
662
+ )
663
+ ),
664
+ { concurrency: "unbounded" }
665
+ );
666
+ return checked.filter(({ inside }) => !inside).map(({ entry }) => entry).join(delimiter);
667
+ });
668
+ var isExecutableFile = (p) => Effect_exports.gen(function* () {
669
+ const info = yield* attempt((done) => {
670
+ stat$1(p, done);
671
+ });
672
+ if (Option_exports.isNone(info) || !info.value.isFile()) {
673
+ return false;
674
+ }
675
+ const executable = yield* attempt((done) => {
676
+ access$1(p, constants.X_OK, (error) => {
677
+ done(error, void 0);
678
+ });
679
+ });
680
+ return Option_exports.isSome(executable);
681
+ });
682
+ var findGit = (pathValue, env) => Effect_exports.gen(function* () {
683
+ const extensions = process.platform === "win32" ? (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((ext) => ext.length > 0) : [""];
684
+ const candidates = pathValue.split(delimiter).flatMap((dir) => extensions.map((ext) => join(dir, `git${ext}`)));
685
+ for (const candidate of candidates) {
686
+ if (yield* isExecutableFile(candidate)) {
687
+ return Option_exports.some(candidate);
688
+ }
689
+ }
690
+ return Option_exports.none();
691
+ });
692
+ var withTrustedPrograms = (env, roots) => Effect_exports.gen(function* () {
693
+ const key = pathKey(env);
694
+ return {
695
+ ...env,
696
+ [key]: yield* trustedPath(env[key] ?? "", roots),
697
+ GIT_ALLOW_PROTOCOL: env["GIT_ALLOW_PROTOCOL"] ?? SAFE_PROTOCOLS
698
+ };
699
+ });
700
+ var pathOf = (env) => env[pathKey(env)] ?? "";
701
+
702
+ // src/hostGit.ts
703
+ var MAX_BUFFER = 10 * 1024 * 1024;
704
+ var ignoreStdinError = () => void 0;
705
+ var spawnGit = (args, { git, cwd, env, input = "" }) => Effect_exports.async((resume) => {
706
+ const child = execFile(
707
+ git,
708
+ [...args],
709
+ { cwd, env, maxBuffer: MAX_BUFFER, encoding: "utf8" },
710
+ (error, stdout, stderr) => {
711
+ if (error) {
712
+ resume(
713
+ Effect_exports.fail(
714
+ new HostGitError({
715
+ message: stderr.trim() || error.message,
716
+ args,
717
+ stdout,
718
+ stderr
719
+ })
720
+ )
721
+ );
722
+ return;
723
+ }
724
+ resume(Effect_exports.succeed({ stdout, stderr }));
725
+ }
726
+ );
727
+ child.stdin?.on("error", ignoreStdinError);
728
+ child.stdin?.end(input);
729
+ });
730
+ var hostGitOutput = (args, cwd, options) => Effect_exports.gen(function* () {
731
+ const pins = yield* resolveGitDirPins(cwd, args);
732
+ const env = yield* withTrustedPrograms(
733
+ {
734
+ ...process.env,
735
+ ...options?.env,
736
+ ...pins,
737
+ // Several callers match git's messages; under a localized locale they
738
+ // would silently stop matching (issue #595).
739
+ LC_ALL: "C",
740
+ GIT_TERMINAL_PROMPT: "0"
741
+ },
742
+ repoRoots(cwd, pins["GIT_COMMON_DIR"])
743
+ );
744
+ const found = yield* findGit(pathOf(env), env);
745
+ if (Option_exports.isNone(found)) {
746
+ return yield* new HostGitError({
747
+ message: "git was not found on PATH (outside the repository)",
748
+ args,
749
+ stdout: "",
750
+ stderr: ""
751
+ });
752
+ }
753
+ const git = found.value;
754
+ const listConfig = (flags) => spawnGit(["config", ...flags, "--list", "-z"], { git, cwd, env }).pipe(
755
+ Effect_exports.map((o) => o.stdout),
756
+ Effect_exports.orElseSucceed(() => "")
757
+ );
758
+ const listed = parseConfigList(
759
+ yield* listConfig(["--show-scope", "--show-origin"])
760
+ );
761
+ const included = yield* repoIncludedEntries(listed, {
762
+ cwd,
763
+ env,
764
+ listFile: (file) => listConfig(["--file", file, "--no-includes"])
765
+ });
766
+ const overrides = hardeningOverrides([...listed, ...included]);
767
+ return yield* spawnGit(args, {
768
+ git,
769
+ cwd,
770
+ env: withConfigOverrides(env, overrides),
771
+ input: options?.input
772
+ });
773
+ });
774
+ var hostGit = (args, cwd, options) => hostGitOutput(args, cwd, options).pipe(Effect_exports.map((o) => o.stdout));
775
+
776
+ // src/WorktreeManager.ts
777
+ var WORKTREE_TIMEOUT_MS = 3e4;
778
+ var NO_CONFIG_LOCK_FLAGS = [
779
+ "-c",
780
+ "branch.autoSetupMerge=false",
781
+ "-c",
782
+ "push.autoSetupRemote=false"
783
+ ];
784
+ var pad = (n) => String(n).padStart(2, "0");
785
+ var formatTimestamp = (date) => `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
786
+ var randomBranchSuffix = () => randomBytes(3).toString("hex");
787
+ var sanitizeName = (name) => name.toLowerCase().replaceAll(/[^a-z0-9]/gu, (char) => "-".repeat(char.length));
788
+ var execGit = (args, cwd) => hostGit(args, cwd).pipe(
789
+ Effect_exports.mapError((e) => new WorktreeError({ message: e.message }))
790
+ );
791
+ var generateTempBranchName = (name) => {
792
+ const ts = formatTimestamp(/* @__PURE__ */ new Date());
793
+ const suffix = randomBranchSuffix();
794
+ if (name !== void 0 && name !== "") {
795
+ return `sandcastle/${sanitizeName(name)}/${ts}-${suffix}`;
796
+ }
797
+ return `sandcastle/${ts}-${suffix}`;
798
+ };
799
+ var getCurrentBranch = (repoDir) => execGit(["rev-parse", "--abbrev-ref", "HEAD"], repoDir).pipe(
800
+ Effect_exports.map((output) => output.trim())
801
+ );
802
+ var normalizePath = (p) => p.replaceAll("\\", "/");
803
+ var findCollidingWorktree = (existing, branch, worktreePath) => existing.find((wt) => wt.branch === branch) ?? existing.find((wt) => normalizePath(wt.path) === normalizePath(worktreePath));
804
+ var isManagedWorktreePath = (worktreePath, worktreesDir) => normalizePath(worktreePath).startsWith(normalizePath(worktreesDir));
805
+ var isOrphanedWorktreePath = (entryPath, activeWorktreePaths) => {
806
+ const normalizedEntry = normalizePath(entryPath);
807
+ for (const active of activeWorktreePaths) {
808
+ if (normalizePath(active) === normalizedEntry) {
809
+ return false;
810
+ }
811
+ }
812
+ return true;
813
+ };
814
+ var listWorktrees = (repoDir) => execGit(["worktree", "list", "--porcelain"], repoDir).pipe(
815
+ Effect_exports.map((output) => {
816
+ const entries = [];
817
+ let currentPath = null;
818
+ let currentBranch = null;
819
+ for (const line of output.split("\n")) {
820
+ if (line.startsWith("worktree ")) {
821
+ if (currentPath !== null) {
822
+ entries.push({ path: currentPath, branch: currentBranch });
823
+ }
824
+ currentPath = line.slice("worktree ".length).trim();
825
+ currentBranch = null;
826
+ } else if (line.startsWith("branch ")) {
827
+ currentBranch = line.slice("branch refs/heads/".length).trim();
828
+ }
829
+ }
830
+ if (currentPath !== null) {
831
+ entries.push({ path: currentPath, branch: currentBranch });
832
+ }
833
+ return entries;
834
+ })
835
+ );
836
+ var worktreeTimeout = (repoDir, operation, noun) => new WorktreeTimeoutError({
837
+ message: `Worktree ${noun} timed out after ${WORKTREE_TIMEOUT_MS}ms`,
838
+ timeoutMs: WORKTREE_TIMEOUT_MS,
839
+ path: repoDir,
840
+ operation
841
+ });
842
+ var headSha = (worktreePath) => execGit(["rev-parse", "HEAD"], worktreePath).pipe(
843
+ Effect_exports.map((s) => s.trim()),
844
+ Effect_exports.orElseSucceed(() => "")
845
+ );
846
+ var tryUnlockedGit = (args, worktreePath) => Effect_exports.either(execGit([...NO_CONFIG_LOCK_FLAGS, ...args], worktreePath));
847
+ var fastForwardFromOrigin = (worktreePath, branch) => Effect_exports.gen(function* () {
848
+ const headRef = yield* execGit(
849
+ ["symbolic-ref", "--quiet", "HEAD"],
850
+ worktreePath
851
+ ).pipe(
852
+ Effect_exports.map((s) => s.trim()),
853
+ Effect_exports.orElseSucceed(() => "")
854
+ );
855
+ if (headRef !== `refs/heads/${branch}`) {
856
+ yield* Console_exports.log(
857
+ `Reusing worktree at ${worktreePath} (branch '${branch}') \u2014 HEAD is not on '${branch}', skipping origin refresh`
858
+ );
859
+ return;
860
+ }
861
+ const fetchResult = yield* tryUnlockedGit(
862
+ ["fetch", "origin", branch],
863
+ worktreePath
864
+ );
865
+ if (fetchResult._tag === "Left") {
866
+ yield* Console_exports.log(
867
+ `Could not fetch from origin (reusing worktree at ${worktreePath} as-is, branch '${branch}')`
868
+ );
869
+ return;
870
+ }
871
+ const before = yield* headSha(worktreePath);
872
+ const mergeResult = yield* tryUnlockedGit(
873
+ ["merge", "--ff-only", `origin/${branch}`],
874
+ worktreePath
875
+ );
876
+ if (mergeResult._tag === "Left") {
877
+ yield* Console_exports.log(
878
+ `Branch '${branch}' has diverged from origin (reusing worktree at ${worktreePath} as-is)`
879
+ );
880
+ return;
881
+ }
882
+ const after = yield* headSha(worktreePath);
883
+ yield* Console_exports.log(
884
+ before && after && before !== after ? `Fast-forwarded worktree at ${worktreePath} (branch '${branch}') to origin/${branch}` : `Reusing existing worktree at ${worktreePath} (branch '${branch}')`
885
+ );
886
+ });
887
+ var reuseCollidingWorktree = (collision, branch, worktreesDir) => Effect_exports.gen(function* () {
888
+ if (isManagedWorktreePath(collision.path, worktreesDir)) {
889
+ const dirty = yield* hasUncommittedChanges(collision.path);
890
+ yield* dirty ? Console_exports.warn(
891
+ `Reusing worktree at ${collision.path} (branch '${branch}') \u2014 worktree has uncommitted changes`
892
+ ) : fastForwardFromOrigin(collision.path, branch);
893
+ return { path: normalize(collision.path), branch };
894
+ }
895
+ return yield* new WorktreeError({
896
+ message: `Branch '${branch}' is already checked out in worktree at '${collision.path}'. Sandcastle's branch and merge-to-head strategies run the agent in a git worktree under .sandcastle/worktrees/, and git refuses to check out the same branch in two worktrees at once (HEAD would become ambiguous). Pick a different branch, or switch the main working tree to a different branch before re-running.`
897
+ });
898
+ });
899
+ var addBranchWorktree = (repoDir, worktreePath, target) => execGit(
900
+ [...NO_CONFIG_LOCK_FLAGS, "worktree", "add", worktreePath, target.branch],
901
+ repoDir
902
+ ).pipe(
903
+ Effect_exports.catchAll((e) => {
904
+ if (e.message.includes("invalid reference")) {
905
+ return execGit(
906
+ [
907
+ ...NO_CONFIG_LOCK_FLAGS,
908
+ "worktree",
909
+ "add",
910
+ "-b",
911
+ target.branch,
912
+ worktreePath,
913
+ target.baseBranch ?? "HEAD"
914
+ ],
915
+ repoDir
916
+ );
917
+ }
918
+ return Effect_exports.fail(e);
919
+ })
920
+ );
921
+ var addOrReuseBranchWorktree = (repoDir, worktreePath, target) => Effect_exports.gen(function* () {
922
+ const { branch, worktreesDir } = target;
923
+ const existing = yield* listWorktrees(repoDir);
924
+ const collision = findCollidingWorktree(existing, branch, worktreePath);
925
+ if (collision) {
926
+ return yield* reuseCollidingWorktree(collision, branch, worktreesDir);
927
+ }
928
+ yield* addBranchWorktree(repoDir, worktreePath, target);
929
+ return { path: worktreePath, branch };
930
+ });
931
+ var addTempBranchWorktree = (repoDir, worktreePath, branch) => execGit(
932
+ [
933
+ ...NO_CONFIG_LOCK_FLAGS,
934
+ "worktree",
935
+ "add",
936
+ "-b",
937
+ branch,
938
+ worktreePath,
939
+ "HEAD"
940
+ ],
941
+ repoDir
942
+ ).pipe(
943
+ Effect_exports.catchAll((e) => {
944
+ if (e.message.includes("already checked out") || e.message.includes("already exists")) {
945
+ return Effect_exports.fail(
946
+ new WorktreeError({
947
+ message: `Branch '${branch}' is already checked out in another worktree. Use a different branch name, or wait for the other run to finish.`
948
+ })
949
+ );
950
+ }
951
+ return Effect_exports.fail(e);
952
+ })
953
+ );
954
+ var create = (repoDir, opts) => Effect_exports.gen(function* () {
955
+ const fs = yield* FileSystem_exports.FileSystem;
956
+ const worktreesDir = join(repoDir, ".sandcastle", "worktrees");
957
+ yield* fs.makeDirectory(worktreesDir, { recursive: true }).pipe(Effect_exports.mapError((e) => new WorktreeError({ message: e.message })));
958
+ const explicitBranch = opts?.branch;
959
+ const hasExplicitBranch = explicitBranch !== void 0 && explicitBranch !== "";
960
+ const branch = hasExplicitBranch ? explicitBranch : opts?.tempBranch ?? generateTempBranchName(opts?.name);
961
+ const worktreePath = join(worktreesDir, branch.replaceAll("/", "-"));
962
+ if (hasExplicitBranch) {
963
+ return yield* addOrReuseBranchWorktree(repoDir, worktreePath, {
964
+ branch,
965
+ baseBranch: opts?.baseBranch,
966
+ worktreesDir
967
+ });
968
+ }
969
+ yield* addTempBranchWorktree(repoDir, worktreePath, branch);
970
+ return { path: worktreePath, branch };
971
+ }).pipe(
972
+ withTimeout(
973
+ WORKTREE_TIMEOUT_MS,
974
+ () => worktreeTimeout(repoDir, "create", "creation")
975
+ )
976
+ );
977
+ var hasUncommittedChanges = (worktreePath) => execGit(["status", "--porcelain"], worktreePath).pipe(
978
+ Effect_exports.map((output) => output.trim().length > 0)
979
+ );
980
+ var remove = (worktreePath) => {
981
+ const repoDir = join(worktreePath, "..", "..", "..");
982
+ return execGit(["worktree", "remove", "--force", worktreePath], repoDir).pipe(
983
+ Effect_exports.asVoid
984
+ );
985
+ };
986
+ var deleteTempBranchIfUnused = (repoDir, branch) => Effect_exports.gen(function* () {
987
+ const ref = `refs/heads/${branch}`;
988
+ const exists = yield* execGit(
989
+ ["show-ref", "--verify", "--quiet", ref],
990
+ repoDir
991
+ ).pipe(
992
+ Effect_exports.as(true),
993
+ Effect_exports.catchAll(() => Effect_exports.succeed(false))
994
+ );
995
+ if (!exists) {
996
+ return { unmergedCommits: 0 };
997
+ }
998
+ const count = yield* execGit(
999
+ // `--exclude` patterns for `--branches` are matched without `refs/heads/`.
1000
+ [
1001
+ "rev-list",
1002
+ "--count",
1003
+ ref,
1004
+ "--not",
1005
+ `--exclude=${branch}`,
1006
+ "--branches"
1007
+ ],
1008
+ repoDir
1009
+ );
1010
+ const unmergedCommits = Number.parseInt(count.trim(), 10) || 0;
1011
+ if (unmergedCommits > 0) {
1012
+ return { unmergedCommits };
1013
+ }
1014
+ yield* execGit(["branch", "-D", branch], repoDir);
1015
+ return { unmergedCommits: 0 };
1016
+ });
1017
+ var readEntriesIfPresent = (fs, dir) => fs.readDirectory(dir).pipe(
1018
+ Effect_exports.map((es) => es),
1019
+ Effect_exports.catchSome(
1020
+ (e) => e._tag === "SystemError" && e.reason === "NotFound" ? Option_exports.some(Effect_exports.succeed(null)) : Option_exports.none()
1021
+ ),
1022
+ Effect_exports.mapError((e) => new WorktreeError({ message: e.message }))
1023
+ );
1024
+ var listActiveWorktreePaths = (repoDir) => execGit(["worktree", "list", "--porcelain"], repoDir).pipe(
1025
+ Effect_exports.map(
1026
+ (worktreeList) => new Set(
1027
+ worktreeList.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length).trim())
1028
+ )
1029
+ )
1030
+ );
1031
+ var removeDir = (fs, dir) => fs.remove(dir, { recursive: true, force: true }).pipe(
1032
+ Effect_exports.mapError(
1033
+ (e) => new WorktreeError({
1034
+ message: `Failed to remove ${dir}: ${e.message}`
1035
+ })
1036
+ )
1037
+ );
1038
+ var pruneStale = (repoDir) => Effect_exports.gen(function* () {
1039
+ const fs = yield* FileSystem_exports.FileSystem;
1040
+ yield* execGit(["worktree", "prune"], repoDir);
1041
+ const worktreesDir = join(repoDir, ".sandcastle", "worktrees");
1042
+ const entries = yield* readEntriesIfPresent(fs, worktreesDir);
1043
+ if (entries === null) {
1044
+ return;
1045
+ }
1046
+ const realWorktreesDir = yield* fs.realPath(worktreesDir).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(worktreesDir)));
1047
+ const activeWorktreePaths = yield* listActiveWorktreePaths(repoDir);
1048
+ for (const entry of entries) {
1049
+ const entryPath = join(realWorktreesDir, entry);
1050
+ const isDir = yield* fs.stat(entryPath).pipe(
1051
+ Effect_exports.map((s) => s.type === "Directory"),
1052
+ Effect_exports.catchAll(() => Effect_exports.succeed(false))
1053
+ );
1054
+ if (isDir && isOrphanedWorktreePath(entryPath, activeWorktreePaths)) {
1055
+ yield* removeDir(fs, entryPath);
1056
+ }
1057
+ }
1058
+ }).pipe(
1059
+ withTimeout(
1060
+ WORKTREE_TIMEOUT_MS,
1061
+ () => worktreeTimeout(repoDir, "prune", "prune")
1062
+ )
1063
+ );
1064
+ var COPY_TO_WORKTREE_TIMEOUT_MS = 6e4;
1065
+ var getCopyOnWriteFlags = (platform) => platform === "darwin" ? ["-cR"] : ["-R", "--reflink=auto"];
1066
+ var createDir = (dir, relativePath) => Effect_exports.tryPromise({
1067
+ try: () => mkdir(dir, { recursive: true }),
1068
+ catch: (e) => {
1069
+ const message = e instanceof Error ? e.message : String(e);
1070
+ return new CopyToWorktreeError({
1071
+ message: `Failed to copy ${relativePath} to worktree: ${message}`,
1072
+ path: relativePath,
1073
+ stderr: message,
1074
+ exitCode: null
1075
+ });
1076
+ }
1077
+ });
1078
+ var copyFailed = (relativePath, error, stderr) => new CopyToWorktreeError({
1079
+ message: `Failed to copy ${relativePath} to worktree: ${stderr || error.message}`,
1080
+ path: relativePath,
1081
+ stderr: stderr || error.message,
1082
+ exitCode: typeof error.code === "number" ? error.code : null
1083
+ });
1084
+ var copyPath = (copy) => Effect_exports.async((resume) => {
1085
+ const { cowFlags, cpSrc, dest, relativePath } = copy;
1086
+ let child;
1087
+ let interrupted = false;
1088
+ child = execFile("cp", [...cowFlags, cpSrc, dest], (error) => {
1089
+ if (interrupted) {
1090
+ return;
1091
+ }
1092
+ if (!error) {
1093
+ resume(Effect_exports.void);
1094
+ return;
1095
+ }
1096
+ child = execFile(
1097
+ "cp",
1098
+ ["-R", cpSrc, dest],
1099
+ (fallbackError, _, stderr) => {
1100
+ resume(
1101
+ fallbackError ? Effect_exports.fail(copyFailed(relativePath, fallbackError, stderr)) : Effect_exports.void
1102
+ );
1103
+ }
1104
+ );
1105
+ });
1106
+ return Effect_exports.sync(() => {
1107
+ interrupted = true;
1108
+ child.kill("SIGKILL");
1109
+ });
1110
+ });
1111
+ var copyToWorktree = (paths, hostRepoDir, worktreePath, timeoutMs) => {
1112
+ const effectiveTimeout = timeoutMs ?? COPY_TO_WORKTREE_TIMEOUT_MS;
1113
+ return Effect_exports.gen(function* () {
1114
+ const cowFlags = getCopyOnWriteFlags(process.platform);
1115
+ for (const relativePath of paths) {
1116
+ const src = join(hostRepoDir, relativePath);
1117
+ const srcStats = yield* Effect_exports.promise(
1118
+ () => stat(src).catch(() => void 0)
1119
+ );
1120
+ if (srcStats === void 0) {
1121
+ continue;
1122
+ }
1123
+ const dest = join(worktreePath, relativePath);
1124
+ const isDirectory = srcStats.isDirectory();
1125
+ const dirToCreate = isDirectory ? dest : dirname(dest);
1126
+ const cpSrc = isDirectory ? `${src}${sep}.` : src;
1127
+ yield* createDir(dirToCreate, relativePath);
1128
+ yield* copyPath({ cowFlags, cpSrc, dest, relativePath });
1129
+ }
1130
+ }).pipe(
1131
+ withTimeout(
1132
+ effectiveTimeout,
1133
+ () => new CopyToWorktreeTimeoutError({
1134
+ message: `Copying files to worktree timed out after ${effectiveTimeout}ms`,
1135
+ timeoutMs: effectiveTimeout,
1136
+ paths
1137
+ })
1138
+ )
1139
+ );
1140
+ };
1141
+ var execHostShell = (command, options) => new Promise((resolve6, reject) => {
1142
+ const signals = options.signals.filter(
1143
+ (s) => s !== void 0
1144
+ );
1145
+ const aborted = signals.find((s) => s.aborted);
1146
+ if (aborted) {
1147
+ reject(abortError(command, aborted));
1148
+ return;
1149
+ }
1150
+ const usesProcessGroup = process.platform !== "win32";
1151
+ const child = spawn(command, {
1152
+ cwd: options.cwd,
1153
+ shell: true,
1154
+ detached: usesProcessGroup
1155
+ });
1156
+ const tree = treeKiller(child, usesProcessGroup);
1157
+ const stopListening = onAnyAbort(signals, (signal) => {
1158
+ tree.kill();
1159
+ reject(abortError(command, signal));
1160
+ });
1161
+ const unregisterShutdown = registerShutdown(tree.kill);
1162
+ const finish = () => {
1163
+ tree.markExited();
1164
+ stopListening();
1165
+ unregisterShutdown();
1166
+ };
1167
+ const output = collectOutput(child);
1168
+ child.on("error", (err) => {
1169
+ finish();
1170
+ reject(err);
1171
+ });
1172
+ child.on("close", (code, killSignal) => {
1173
+ finish();
1174
+ if (code === 0) {
1175
+ resolve6({ stdout: output.stdout, stderr: output.stderr });
1176
+ return;
1177
+ }
1178
+ reject(commandFailed(command, output, { code, signal: killSignal }));
1179
+ });
1180
+ });
1181
+ var treeKiller = (child, usesProcessGroup) => {
1182
+ let exited = false;
1183
+ const kill = () => {
1184
+ if (exited || child.pid === void 0) {
1185
+ return;
1186
+ }
1187
+ try {
1188
+ if (usesProcessGroup) {
1189
+ process.kill(-child.pid, "SIGKILL");
1190
+ } else {
1191
+ child.kill("SIGKILL");
1192
+ }
1193
+ } catch {
1194
+ }
1195
+ };
1196
+ const markExited = () => {
1197
+ exited = true;
1198
+ };
1199
+ return { kill, markExited };
1200
+ };
1201
+ var onAnyAbort = (signals, onAbort) => {
1202
+ const listeners = signals.map((signal) => {
1203
+ const listener = () => {
1204
+ onAbort(signal);
1205
+ };
1206
+ signal.addEventListener("abort", listener);
1207
+ return { signal, listener };
1208
+ });
1209
+ return () => {
1210
+ for (const { signal, listener } of listeners) {
1211
+ signal.removeEventListener("abort", listener);
1212
+ }
1213
+ };
1214
+ };
1215
+ var collectOutput = (child) => {
1216
+ const output = { stdout: "", stderr: "" };
1217
+ child.stdout?.setEncoding("utf8").on("data", (d) => {
1218
+ output.stdout += d;
1219
+ });
1220
+ child.stderr?.setEncoding("utf8").on("data", (d) => {
1221
+ output.stderr += d;
1222
+ });
1223
+ return output;
1224
+ };
1225
+ var commandFailed = (command, output, exit) => Object.assign(new Error(`Command failed: ${command}
1226
+ ${output.stderr}`), {
1227
+ code: exit.code,
1228
+ signal: exit.signal,
1229
+ stdout: output.stdout,
1230
+ stderr: output.stderr
1231
+ });
1232
+ var abortError = (command, signal) => Object.assign(
1233
+ new Error(`Command aborted: ${command} (${String(signal.reason)})`),
1234
+ { name: "AbortError" }
1235
+ );
1236
+
1237
+ // src/sandboxSetup.ts
1238
+ var HOOK_TIMEOUT_MS = 6e4;
1239
+ var GIT_SETUP_MAX_RETRIES = 2;
1240
+ var GIT_SETUP_RETRY_DELAY_MS = 250;
1241
+ var TRANSIENT_EXEC_EXIT_CODES = /* @__PURE__ */ new Set([126, 137]);
1242
+ var isTransientExecError = (err) => err._tag === "ExecError" && err.exitCode !== void 0 && TRANSIENT_EXEC_EXIT_CODES.has(err.exitCode);
1243
+ var execOk = (sandbox, command, options) => Effect_exports.flatMap(
1244
+ sandbox.exec(command, options),
1245
+ (result) => result.exitCode === 0 ? Effect_exports.succeed(result) : Effect_exports.fail(
1246
+ new ExecError({
1247
+ command,
1248
+ exitCode: result.exitCode,
1249
+ message: `Command failed (exit ${result.exitCode}): ${command}
1250
+ ${result.stderr}`
1251
+ })
1252
+ )
1253
+ );
1254
+ var execOkWithGitTimeout = (target, command, options) => execOk(target.sandbox, command, options).pipe(
1255
+ withTimeout(
1256
+ target.timeoutMs,
1257
+ () => new GitSetupTimeoutError({
1258
+ message: `Git command timed out after ${target.timeoutMs}ms: ${command}`,
1259
+ timeoutMs: target.timeoutMs,
1260
+ command
1261
+ })
1262
+ ),
1263
+ // Each attempt is bounded by its own timeout (above); retry only transient
1264
+ // exec races, so a genuine git error or a hung exec still fails fast.
1265
+ Effect_exports.retry({
1266
+ while: isTransientExecError,
1267
+ times: GIT_SETUP_MAX_RETRIES,
1268
+ schedule: Schedule_exports.spaced(Duration_exports.millis(GIT_SETUP_RETRY_DELAY_MS))
1269
+ })
1270
+ );
1271
+ var escapeDoubleQuotes = (value) => value.replaceAll('"', String.raw`\"`);
1272
+ var setUpSandboxGit = (setup) => Effect_exports.gen(function* () {
1273
+ const target = {
1274
+ sandbox: setup.sandbox,
1275
+ timeoutMs: setup.gitSetupTimeoutMs
1276
+ };
1277
+ const { name, email } = setup.identity;
1278
+ yield* execOkWithGitTimeout(
1279
+ target,
1280
+ `git config --global --add safe.directory "${setup.sandboxRepoDir}"`
1281
+ );
1282
+ if (name) {
1283
+ yield* execOkWithGitTimeout(
1284
+ target,
1285
+ `git config --global user.name "${escapeDoubleQuotes(name)}"`
1286
+ );
1287
+ }
1288
+ if (email) {
1289
+ yield* execOkWithGitTimeout(
1290
+ target,
1291
+ `git config --global user.email "${escapeDoubleQuotes(email)}"`
1292
+ );
1293
+ }
1294
+ const head = yield* execOkWithGitTimeout(
1295
+ target,
1296
+ "git rev-parse --abbrev-ref HEAD",
1297
+ { cwd: setup.sandboxRepoDir }
1298
+ );
1299
+ return head.stdout.trim();
1300
+ });
1301
+ var runHostHook = (hook, cwd, signal) => {
1302
+ const timeout = hook.timeoutMs ?? HOOK_TIMEOUT_MS;
1303
+ return Effect_exports.tryPromise({
1304
+ try: (effectSignal) => execHostShell(hook.command, {
1305
+ cwd,
1306
+ signals: [signal, effectSignal]
1307
+ }),
1308
+ catch: (err) => new ExecError({
1309
+ command: hook.command,
1310
+ message: `Host hook failed: ${hook.command}
1311
+ ${err instanceof Error ? err.message : String(err)}`
1312
+ })
1313
+ }).pipe(
1314
+ withTimeout(
1315
+ timeout,
1316
+ () => new HookTimeoutError({
1317
+ message: `Host hook '${hook.command}' timed out after ${timeout}ms`,
1318
+ timeoutMs: timeout,
1319
+ command: hook.command
1320
+ })
1321
+ )
1322
+ );
1323
+ };
1324
+ var abortError2 = (signal) => new ExecError({
1325
+ command: "abort",
1326
+ message: `Aborted: ${signal.reason}`
1327
+ });
1328
+ var raceAbort = (signal) => Effect_exports.gen(function* () {
1329
+ const aborted = yield* Deferred_exports.make();
1330
+ if (signal.aborted) {
1331
+ yield* Deferred_exports.fail(aborted, abortError2(signal));
1332
+ return { aborted };
1333
+ }
1334
+ const runFork = Runtime_exports.runFork(yield* Effect_exports.runtime());
1335
+ const onAbort = () => {
1336
+ runFork(Deferred_exports.fail(aborted, abortError2(signal)));
1337
+ };
1338
+ signal.addEventListener("abort", onAbort, { once: true });
1339
+ return {
1340
+ aborted,
1341
+ cleanup: () => {
1342
+ signal.removeEventListener("abort", onAbort);
1343
+ }
1344
+ };
1345
+ });
1346
+ var runSandboxHook = (hook, target) => {
1347
+ const timeout = hook.timeoutMs ?? HOOK_TIMEOUT_MS;
1348
+ return Effect_exports.raceFirst(
1349
+ execOk(target.sandbox, hook.command, {
1350
+ cwd: target.sandboxRepoDir,
1351
+ sudo: hook.sudo
1352
+ }).pipe(
1353
+ withTimeout(
1354
+ timeout,
1355
+ () => new HookTimeoutError({
1356
+ message: `Hook '${hook.command}' timed out after ${timeout}ms`,
1357
+ timeoutMs: timeout,
1358
+ command: hook.command
1359
+ })
1360
+ )
1361
+ ),
1362
+ Deferred_exports.await(target.aborted)
1363
+ );
1364
+ };
1365
+ var runOnSandboxReadyHooks = (hooks) => Effect_exports.gen(function* () {
1366
+ const { aborted, cleanup } = yield* raceAbort(hooks.signal);
1367
+ const target = {
1368
+ sandbox: hooks.sandbox,
1369
+ sandboxRepoDir: hooks.sandboxRepoDir,
1370
+ aborted
1371
+ };
1372
+ const all = [
1373
+ ...hooks.sandboxHooks.map((hook) => runSandboxHook(hook, target)),
1374
+ ...hooks.hostHooks.map(
1375
+ (hook) => runHostHook(hook, hooks.hostWorktreePath, hooks.signal)
1376
+ )
1377
+ ];
1378
+ const runAll = all.length > 0 ? Effect_exports.all(all, { concurrency: "unbounded" }) : Effect_exports.void;
1379
+ yield* runAll.pipe(Effect_exports.ensuring(Effect_exports.sync(() => cleanup?.())));
1380
+ });
1381
+
1382
+ // src/RecoveryMessage.ts
1383
+ var stepsWithChanges = (input) => {
1384
+ const steps = [
1385
+ { key: "commits", label: "committed changes", has: input.hasCommits },
1386
+ { key: "diff", label: "uncommitted changes", has: input.hasDiff },
1387
+ { key: "untracked", label: "untracked files", has: input.hasUntracked }
1388
+ ];
1389
+ return steps.filter((step) => step.has);
1390
+ };
1391
+ var gitAmResolution = (remaining) => [
1392
+ "Resolve conflicts, then continue with:",
1393
+ ` git am --continue`,
1394
+ ...remaining.length > 0 ? [
1395
+ "",
1396
+ "After all commits are applied, run the remaining steps:",
1397
+ formatCommandBlock(remaining)
1398
+ ] : []
1399
+ ];
1400
+ var applyResolution = (remaining) => remaining.length > 0 ? ["Run the remaining steps:", formatCommandBlock(remaining)] : [];
1401
+ var buildRecoveryMessage = (input) => {
1402
+ const { patchDir, failedStep, branch } = input;
1403
+ const hasBranch = branch !== void 0 && branch !== "";
1404
+ const cmdPatchDir = hasBranch ? `../../${patchDir}` : patchDir;
1405
+ const steps = stepsWithChanges(input);
1406
+ const failedIndex = steps.findIndex((s) => s.key === failedStep);
1407
+ const failedStepInfo = steps[failedIndex];
1408
+ if (failedStepInfo === void 0) {
1409
+ throw new Error(
1410
+ `Recovery step "${failedStep}" failed, but it had no changes to apply.`
1411
+ );
1412
+ }
1413
+ const preamble = hasBranch ? [
1414
+ "Set up worktree, then resolve:",
1415
+ formatCommandBlock([
1416
+ `git worktree add .sandcastle/worktree ${branch}`,
1417
+ `cd .sandcastle/worktree`
1418
+ ]),
1419
+ ""
1420
+ ] : [];
1421
+ const resolution = failedStep === "commits" ? gitAmResolution(
1422
+ buildRemainingCommands(cmdPatchDir, steps.slice(failedIndex + 1))
1423
+ ) : applyResolution(
1424
+ buildRemainingCommands(cmdPatchDir, steps.slice(failedIndex))
1425
+ );
1426
+ return [
1427
+ `Patch application failed at step ${failedIndex + 1} (${failedStepInfo.label}).`,
1428
+ "",
1429
+ ...preamble,
1430
+ ...resolution
1431
+ ].join("\n");
1432
+ };
1433
+ var buildRemainingCommands = (patchDir, steps) => {
1434
+ const commands = [];
1435
+ for (const step of steps) {
1436
+ if (!step.has) {
1437
+ continue;
1438
+ }
1439
+ if (step.key === "commits") {
1440
+ commands.push(`git am --3way ${patchDir}/*.patch`);
1441
+ } else if (step.key === "diff") {
1442
+ commands.push(`git apply ${patchDir}/changes.patch`);
1443
+ } else if (step.key === "untracked") {
1444
+ commands.push(`cp -r ${patchDir}/untracked/* .`);
1445
+ }
1446
+ }
1447
+ return commands;
1448
+ };
1449
+ var formatCommandBlock = (commands) => {
1450
+ if (commands.length === 1) {
1451
+ return ` ${commands[0]}`;
1452
+ }
1453
+ return commands.map((cmd, i) => i < commands.length - 1 ? ` ${cmd} && \\` : ` ${cmd}`).join("\n");
1454
+ };
1455
+ var refusal2 = (path, reason) => new SyncOutPathError({
1456
+ message: `Refusing to sync ${JSON.stringify(path)} out of the sandbox: ${reason}`,
1457
+ path
1458
+ });
1459
+ var isGitSegment = (segment) => segment.toLowerCase().replace(/[. ]+$/u, "") === ".git";
1460
+ var isAbsoluteAnywhere = (p) => posix.isAbsolute(p) || win32.isAbsolute(p) || /^[a-z]:/iu.test(p);
1461
+
1462
+ // src/patchFileChanges.ts
1463
+ var newChange = () => ({
1464
+ symlink: false,
1465
+ modeOnly: false,
1466
+ binary: false,
1467
+ deleted: false,
1468
+ path: void 0,
1469
+ oldPath: void 0,
1470
+ from: void 0,
1471
+ inHunk: false,
1472
+ newLines: []
1473
+ });
1474
+ var C_ESCAPES = {
1475
+ a: "\x07",
1476
+ b: "\b",
1477
+ f: "\f",
1478
+ n: "\n",
1479
+ r: "\r",
1480
+ t: " ",
1481
+ v: "\v"
1482
+ };
1483
+ var unquote = (raw) => {
1484
+ if (raw.length < 2 || !raw.startsWith('"') || !raw.endsWith('"')) {
1485
+ return raw;
1486
+ }
1487
+ const latin1 = raw.slice(1, -1).replaceAll(
1488
+ /\\(?<escaped>[0-7]{3}|.)/gu,
1489
+ (_match, escaped) => /^[0-7]{3}$/u.test(escaped) ? String.fromCodePoint(Number.parseInt(escaped, 8)) : C_ESCAPES[escaped] ?? escaped
1490
+ );
1491
+ return Buffer.from(latin1, "latin1").toString("utf8");
1492
+ };
1493
+ var stripPrefix = (raw) => {
1494
+ const path = unquote(raw.trim());
1495
+ const slash = path.indexOf("/");
1496
+ return slash === -1 ? path : path.slice(slash + 1);
1497
+ };
1498
+ var named = (match) => match.groups?.["p"] ?? "";
1499
+ var HEADER_RULES = [
1500
+ [
1501
+ /^new file mode 120000$/u,
1502
+ (c) => {
1503
+ c.symlink = true;
1504
+ }
1505
+ ],
1506
+ [
1507
+ /^new mode 120000$/u,
1508
+ (c) => {
1509
+ c.symlink = true;
1510
+ c.modeOnly = true;
1511
+ }
1512
+ ],
1513
+ [
1514
+ /^index [0-9a-f]+\.\.[0-9a-f]+ 120000$/u,
1515
+ (c) => {
1516
+ c.symlink = true;
1517
+ }
1518
+ ],
1519
+ [
1520
+ /^deleted file mode /u,
1521
+ (c) => {
1522
+ c.deleted = true;
1523
+ }
1524
+ ],
1525
+ [
1526
+ /^\+\+\+ (?<p>.*)$/u,
1527
+ (c, m) => {
1528
+ const raw = named(m);
1529
+ if (raw.trim() === "/dev/null") {
1530
+ c.deleted = true;
1531
+ } else {
1532
+ c.path = stripPrefix(raw);
1533
+ }
1534
+ }
1535
+ ],
1536
+ [
1537
+ /^--- (?<p>.*)$/u,
1538
+ (c, m) => {
1539
+ const raw = named(m);
1540
+ c.oldPath = raw.trim() === "/dev/null" ? void 0 : stripPrefix(raw);
1541
+ }
1542
+ ],
1543
+ [
1544
+ /^(?:rename|copy) to (?<p>.*)$/u,
1545
+ (c, m) => {
1546
+ c.path = unquote(named(m));
1547
+ }
1548
+ ],
1549
+ [
1550
+ /^(?:rename|copy) from (?<p>.*)$/u,
1551
+ (c, m) => {
1552
+ c.from = unquote(named(m));
1553
+ }
1554
+ ],
1555
+ [
1556
+ /^(?:GIT binary patch$|Binary files )/u,
1557
+ (c) => {
1558
+ c.binary = true;
1559
+ }
1560
+ ],
1561
+ [
1562
+ /^@@/u,
1563
+ (c) => {
1564
+ c.inHunk = true;
1565
+ c.modeOnly = false;
1566
+ }
1567
+ ]
1568
+ ];
1569
+ var applyHeaderLine = (change, line) => {
1570
+ for (const [pattern, apply] of HEADER_RULES) {
1571
+ const match = pattern.exec(line);
1572
+ if (match !== null) {
1573
+ apply(change, match);
1574
+ return;
1575
+ }
1576
+ }
1577
+ };
1578
+ var applyHunkLine = (change, line) => {
1579
+ if (/^[+ ]/u.test(line)) {
1580
+ change.newLines.push(line.slice(1));
1581
+ }
1582
+ return /^(?:[+\- \\]|@@)/u.test(line);
1583
+ };
1584
+ var parsePatch = (patch) => {
1585
+ const changes = [];
1586
+ let current;
1587
+ for (const raw of patch.split("\n")) {
1588
+ const line = raw.replace(/\r$/u, "");
1589
+ if (line.startsWith("diff --git ")) {
1590
+ current = newChange();
1591
+ changes.push(current);
1592
+ } else if (current !== void 0) {
1593
+ const stillInHunk = current.inHunk && applyHunkLine(current, line);
1594
+ if (!stillInHunk) {
1595
+ current.inHunk = false;
1596
+ applyHeaderLine(current, line);
1597
+ }
1598
+ }
1599
+ }
1600
+ return changes;
1601
+ };
1602
+
1603
+ // src/syncOutPatchSymlinks.ts
1604
+ var checkSymlinkTarget = (linkPath, target) => {
1605
+ if (target === "" || target.includes("\0")) {
1606
+ return Effect_exports.fail(refusal2(linkPath, "it is a symlink with no target"));
1607
+ }
1608
+ if (isAbsoluteAnywhere(target)) {
1609
+ return Effect_exports.fail(refusal2(linkPath, `it is a symlink to ${target}`));
1610
+ }
1611
+ const resolved = posix.normalize(
1612
+ posix.join(posix.dirname(linkPath), target.replaceAll("\\", "/"))
1613
+ );
1614
+ if (resolved === ".." || resolved.startsWith("../")) {
1615
+ return Effect_exports.fail(
1616
+ refusal2(linkPath, `it is a symlink to ${target}, outside the worktree`)
1617
+ );
1618
+ }
1619
+ return resolved.split("/").some((segment) => isGitSegment(segment)) ? Effect_exports.fail(refusal2(linkPath, `it is a symlink to ${target}, in .git`)) : Effect_exports.void;
1620
+ };
1621
+ var targetOf = (change, symlinkAt) => {
1622
+ if (change.newLines.length > 0) {
1623
+ return Effect_exports.succeed(
1624
+ change.newLines.length === 1 ? Option_exports.fromNullable(change.newLines[0]) : Option_exports.none()
1625
+ );
1626
+ }
1627
+ return change.from === void 0 ? Effect_exports.succeed(Option_exports.none()) : symlinkAt(change.from);
1628
+ };
1629
+ var checkChange = (change, path, symlinkAt) => Effect_exports.gen(function* () {
1630
+ const keepsType = !change.symlink && change.newLines.length === 0;
1631
+ if (!change.symlink && !(keepsType && change.from !== void 0)) {
1632
+ return Option_exports.none();
1633
+ }
1634
+ if (change.binary || change.modeOnly) {
1635
+ return yield* refusal2(path, "a symlink whose target can't be checked");
1636
+ }
1637
+ const target = yield* targetOf(change, symlinkAt);
1638
+ if (Option_exports.isNone(target)) {
1639
+ return change.symlink ? yield* refusal2(path, "a symlink whose target can't be checked") : Option_exports.none();
1640
+ }
1641
+ yield* checkSymlinkTarget(path, target.value);
1642
+ return target;
1643
+ });
1644
+ var checkPatchSymlinks = (patches, hostSymlinkAt2) => Effect_exports.gen(function* () {
1645
+ const made = /* @__PURE__ */ new Map();
1646
+ const symlinkAt = (relPath) => Option_exports.match(Option_exports.fromNullable(made.get(relPath)), {
1647
+ onNone: () => hostSymlinkAt2(relPath),
1648
+ onSome: (known) => Effect_exports.succeed(known)
1649
+ });
1650
+ for (const change of patches.flatMap((patch) => parsePatch(patch))) {
1651
+ const path = change.deleted ? change.path ?? change.oldPath : change.path;
1652
+ if (path === void 0) {
1653
+ if (change.symlink) {
1654
+ return yield* refusal2("(unknown)", "a symlink with no path");
1655
+ }
1656
+ continue;
1657
+ }
1658
+ made.set(
1659
+ path,
1660
+ change.deleted ? Option_exports.none() : yield* checkChange(change, path, symlinkAt)
1661
+ );
1662
+ }
1663
+ });
1664
+ var checkPatchFileSymlinks = (paths, hostSymlinkAt2) => Effect_exports.gen(function* () {
1665
+ const patches = yield* Effect_exports.all(
1666
+ paths.map(
1667
+ (path) => Effect_exports.async((resume) => {
1668
+ readFile(path, "utf8", (error, text) => {
1669
+ resume(
1670
+ error === null ? Effect_exports.succeed(text) : Effect_exports.fail(refusal2(path, "the patch can't be read"))
1671
+ );
1672
+ });
1673
+ })
1674
+ )
1675
+ );
1676
+ yield* checkPatchSymlinks(patches, hostSymlinkAt2);
1677
+ });
1678
+
1679
+ // src/syncOutPaths.ts
1680
+ var splitSegments = (path) => path.split(/[\\/]/u).filter((segment) => segment !== "" && segment !== ".");
1681
+ var relativePathProblem = (path, segments) => {
1682
+ if (path.includes("\0")) {
1683
+ return "it contains a NUL byte";
1684
+ }
1685
+ if (isAbsoluteAnywhere(path)) {
1686
+ return "it is an absolute path";
1687
+ }
1688
+ if (segments.includes("..")) {
1689
+ return "it has a '..' segment";
1690
+ }
1691
+ if (segments.some((segment) => isGitSegment(segment))) {
1692
+ return "it is inside .git";
1693
+ }
1694
+ return segments.length === 0 ? "it is empty" : void 0;
1695
+ };
1696
+ var checkRelativePath = (path) => {
1697
+ const segments = splitSegments(path);
1698
+ const problem = relativePathProblem(path, segments);
1699
+ return problem === void 0 ? Effect_exports.succeed(segments) : Effect_exports.fail(refusal2(path, problem));
1700
+ };
1701
+ var checkPatchName = (name) => /[\\/\0]/u.test(name) || name === "." || name === ".." || name === "" ? Effect_exports.fail(refusal2(name, "a patch name must be a single file name")) : Effect_exports.succeed(name);
1702
+ var attempt2 = (call) => Effect_exports.async((resume) => {
1703
+ call((error, value) => {
1704
+ resume(
1705
+ Effect_exports.succeed(error === null ? Option_exports.some(value) : Option_exports.none())
1706
+ );
1707
+ });
1708
+ });
1709
+ var lstatOf = (p) => attempt2((done) => {
1710
+ lstat(p, done);
1711
+ });
1712
+ var realPathOf = (p) => attempt2((done) => {
1713
+ realpath(p, done);
1714
+ });
1715
+ var readLinkOf = (p) => attempt2((done) => {
1716
+ readlink(p, done);
1717
+ });
1718
+ var realRootOf = (dir) => realPathOf(dir).pipe(
1719
+ Effect_exports.flatMap(
1720
+ (real) => Option_exports.isSome(real) ? Effect_exports.succeed(real.value) : Effect_exports.fail(refusal2(dir, "the host worktree can't be resolved"))
1721
+ )
1722
+ );
1723
+ var deepestExisting = (root, segments) => Effect_exports.gen(function* () {
1724
+ for (let depth = segments.length; depth > 0; depth--) {
1725
+ const candidate = join(root, ...segments.slice(0, depth));
1726
+ if (Option_exports.isSome(yield* lstatOf(candidate))) {
1727
+ return Option_exports.some(candidate);
1728
+ }
1729
+ }
1730
+ return Option_exports.none();
1731
+ });
1732
+ var isOutside = (rel) => rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel);
1733
+ var checkResolvesInside = (realRoot, relPath, existing) => Effect_exports.gen(function* () {
1734
+ const real = yield* realPathOf(existing);
1735
+ if (Option_exports.isNone(real)) {
1736
+ return yield* refusal2(relPath, `${existing} is a symlink to nowhere`);
1737
+ }
1738
+ const rel = relative(realRoot, real.value);
1739
+ if (isOutside(rel)) {
1740
+ return yield* refusal2(relPath, `${existing} leads outside the worktree`);
1741
+ }
1742
+ if (splitSegments(rel).some((segment) => isGitSegment(segment))) {
1743
+ return yield* refusal2(relPath, `${existing} leads inside .git`);
1744
+ }
1745
+ });
1746
+ var resolveHostDestination = (realRoot, relPath) => Effect_exports.gen(function* () {
1747
+ const segments = yield* checkRelativePath(relPath);
1748
+ const existing = yield* deepestExisting(realRoot, segments);
1749
+ if (Option_exports.isSome(existing)) {
1750
+ yield* checkResolvesInside(realRoot, relPath, existing.value);
1751
+ }
1752
+ return join(realRoot, ...segments);
1753
+ });
1754
+ var checkStagedFile = (staged, relPath) => lstatOf(staged).pipe(
1755
+ Effect_exports.flatMap(
1756
+ (stat5) => Option_exports.isSome(stat5) && stat5.value.isFile() ? Effect_exports.void : Effect_exports.fail(refusal2(relPath, "it is not a regular file"))
1757
+ )
1758
+ );
1759
+ var hostSymlinkAt = (realRoot) => (relPath) => Effect_exports.gen(function* () {
1760
+ const p = join(realRoot, ...splitSegments(relPath));
1761
+ const stat5 = yield* lstatOf(p);
1762
+ return Option_exports.isSome(stat5) && stat5.value.isSymbolicLink() ? yield* readLinkOf(p) : Option_exports.none();
1763
+ });
1764
+
1765
+ // src/syncOutExec.ts
1766
+ var execHostGit = (args, cwd) => hostGit(args, cwd).pipe(
1767
+ Effect_exports.mapError(
1768
+ (e) => new SyncError({
1769
+ message: `Host command failed: git ${args.join(" ")}
1770
+ ${e.message}`
1771
+ })
1772
+ )
1773
+ );
1774
+ var execOk2 = (handle, command, options) => Effect_exports.tryPromise({
1775
+ try: () => handle.exec(command, options),
1776
+ catch: (e) => new SyncError({
1777
+ message: `Sandbox exec failed: ${command}
1778
+ ${e instanceof Error ? e.message : String(e)}`
1779
+ })
1780
+ }).pipe(
1781
+ Effect_exports.flatMap(
1782
+ (result) => result.exitCode === 0 ? Effect_exports.succeed(result) : Effect_exports.fail(
1783
+ new SyncError({
1784
+ message: `Sandbox command failed (exit ${result.exitCode}): ${command}
1785
+ ${result.stderr}`
1786
+ })
1787
+ )
1788
+ )
1789
+ );
1790
+ var execSandbox = (handle, command, options) => Effect_exports.tryPromise({
1791
+ try: () => handle.exec(command, options),
1792
+ catch: (e) => new SyncError({
1793
+ message: `Sandbox exec failed: ${command}
1794
+ ${e instanceof Error ? e.message : String(e)}`
1795
+ })
1796
+ });
1797
+
1798
+ // src/syncOutInspect.ts
1799
+ var SYNC_BASE_REF = "refs/sandcastle/sync-base";
1800
+ var countCommitsToSync = (sandbox, cwd, hostHead) => Effect_exports.gen(function* () {
1801
+ const baseResult = yield* sandbox.exec(`git rev-parse --verify --quiet ${SYNC_BASE_REF}`, { cwd }).pipe(
1802
+ Effect_exports.catchAll(
1803
+ () => Effect_exports.succeed({
1804
+ stdout: "",
1805
+ stderr: "",
1806
+ exitCode: 1
1807
+ })
1808
+ )
1809
+ );
1810
+ const base = baseResult.exitCode === 0 && baseResult.stdout.trim().length > 0 ? baseResult.stdout.trim() : hostHead;
1811
+ const countResult = yield* sandbox.exec(`git rev-list "${base}..HEAD" --count`, { cwd }).pipe(
1812
+ Effect_exports.catchAll(
1813
+ () => Effect_exports.succeed({
1814
+ stdout: "0",
1815
+ stderr: "",
1816
+ exitCode: 1
1817
+ })
1818
+ )
1819
+ );
1820
+ if (countResult.exitCode !== 0) {
1821
+ return 0;
1822
+ }
1823
+ const parsed = Number(countResult.stdout.trim());
1824
+ return Number.isInteger(parsed) ? parsed : 0;
1825
+ });
1826
+ var readSyncBase = (handle, hostHead) => execSandbox(handle, `git rev-parse --verify --quiet ${SYNC_BASE_REF}`, {
1827
+ cwd: handle.worktreePath
1828
+ }).pipe(
1829
+ Effect_exports.map(
1830
+ (result) => result.exitCode === 0 && result.stdout.trim().length > 0 ? result.stdout.trim() : hostHead
1831
+ )
1832
+ );
1833
+ var listUntracked = (handle) => execSandbox(handle, "git ls-files --others --exclude-standard", {
1834
+ cwd: handle.worktreePath
1835
+ }).pipe(
1836
+ Effect_exports.map(
1837
+ (result) => result.exitCode === 0 && result.stdout.trim().length > 0 ? result.stdout.trim().split("\n").filter((f) => f.length > 0) : []
1838
+ )
1839
+ );
1840
+ var inspectSandbox = (hostRepoDir, handle) => Effect_exports.gen(function* () {
1841
+ const hostHead = (yield* execHostGit(
1842
+ ["rev-parse", "HEAD"],
1843
+ hostRepoDir
1844
+ )).trim();
1845
+ const sandboxHead = (yield* execOk2(handle, "git rev-parse HEAD", {
1846
+ cwd: handle.worktreePath
1847
+ })).stdout.trim();
1848
+ const base = yield* readSyncBase(handle, hostHead);
1849
+ const diffResult = yield* execSandbox(handle, "git diff HEAD", {
1850
+ cwd: handle.worktreePath
1851
+ });
1852
+ const untrackedFiles = yield* listUntracked(handle);
1853
+ return {
1854
+ base,
1855
+ sandboxHead,
1856
+ hasCommits: base !== sandboxHead,
1857
+ hasDiff: diffResult.exitCode === 0 && diffResult.stdout.trim().length > 0,
1858
+ diff: diffResult.stdout,
1859
+ hasUntracked: untrackedFiles.length > 0,
1860
+ untrackedFiles
1861
+ };
1862
+ });
1863
+ var isEmptyPatch = (patchPath) => Effect_exports.tryPromise({
1864
+ try: async () => {
1865
+ const info = await stat(patchPath);
1866
+ if (info.size === 0) {
1867
+ return true;
1868
+ }
1869
+ const content = await readFile$1(patchPath, "utf8");
1870
+ return !content.includes("diff --git");
1871
+ },
1872
+ catch: (e) => new SyncError({
1873
+ message: `Failed to check patch ${patchPath}: ${e instanceof Error ? e.message : String(e)}`
1874
+ })
1875
+ });
1876
+ var pad2 = (n) => String(n).padStart(2, "0");
1877
+ var createPatchDir = (hostRepoDir) => DateTime_exports.now.pipe(
1878
+ // Local time, as the directory name has always used.
1879
+ Effect_exports.map(
1880
+ (now) => DateTime_exports.toParts(DateTime_exports.setZone(now, DateTime_exports.zoneMakeLocal()))
1881
+ ),
1882
+ Effect_exports.flatMap(
1883
+ (now) => Effect_exports.tryPromise({
1884
+ try: async () => {
1885
+ const base = `${now.year}${pad2(now.month)}${pad2(now.day)}-${pad2(now.hours)}${pad2(now.minutes)}${pad2(now.seconds)}`;
1886
+ const patchesRoot = join(hostRepoDir, ".sandcastle", "patches");
1887
+ await mkdir(patchesRoot, { recursive: true });
1888
+ const taken = new Set(await readdir(patchesRoot));
1889
+ let dirName = base;
1890
+ let counter = 0;
1891
+ while (taken.has(dirName)) {
1892
+ counter++;
1893
+ dirName = `${base}-${counter}`;
1894
+ }
1895
+ const patchDir = join(patchesRoot, dirName);
1896
+ await mkdir(patchDir, { recursive: true });
1897
+ return patchDir;
1898
+ },
1899
+ catch: (e) => new SyncError({
1900
+ message: `Failed to create patch directory: ${e instanceof Error ? e.message : String(e)}`
1901
+ })
1902
+ })
1903
+ )
1904
+ );
1905
+ var diffPathOf = (run) => join(run.patchDir, "changes.patch");
1906
+ var stagedUntrackedPath = (run, i) => join(run.untrackedDir, ...run.untrackedSegments[i] ?? []);
1907
+ var saveCommitPatches = (run) => Effect_exports.gen(function* () {
1908
+ const { handle } = run;
1909
+ const mkTempResult = yield* execOk2(
1910
+ handle,
1911
+ "mktemp -d -t sandcastle-patches-XXXXXX"
1912
+ );
1913
+ const sandboxPatchDir = mkTempResult.stdout.trim();
1914
+ const nonEmptyPatches = [];
1915
+ try {
1916
+ yield* execOk2(
1917
+ handle,
1918
+ `git format-patch "${run.changes.base}..HEAD" -o "${sandboxPatchDir}"`,
1919
+ { cwd: handle.worktreePath }
1920
+ );
1921
+ const lsResult = yield* execOk2(handle, `ls -1 "${sandboxPatchDir}"`);
1922
+ const patchNames = lsResult.stdout.trim().split("\n").filter((name) => name.length > 0);
1923
+ for (const patchName of patchNames) {
1924
+ yield* checkPatchName(patchName);
1925
+ const sandboxPatchPath = `${sandboxPatchDir}/${patchName}`;
1926
+ const hostPatchPath = join(run.patchDir, patchName);
1927
+ yield* Effect_exports.tryPromise({
1928
+ try: () => handle.copyFileOut(sandboxPatchPath, hostPatchPath),
1929
+ catch: (e) => new SyncError({
1930
+ message: `Failed to copy patch ${patchName}: ${e instanceof Error ? e.message : String(e)}`
1931
+ })
1932
+ });
1933
+ if (!(yield* isEmptyPatch(hostPatchPath))) {
1934
+ nonEmptyPatches.push(hostPatchPath);
1935
+ }
1936
+ }
1937
+ } finally {
1938
+ yield* execSandbox(handle, `rm -rf "${sandboxPatchDir}"`);
1939
+ }
1940
+ return nonEmptyPatches;
1941
+ });
1942
+ var saveDiff = (run) => Effect_exports.tryPromise({
1943
+ try: () => writeFile(diffPathOf(run), run.changes.diff),
1944
+ catch: (e) => new SyncError({
1945
+ message: `Failed to write diff patch: ${e instanceof Error ? e.message : String(e)}`
1946
+ })
1947
+ });
1948
+ var saveUntracked = (run) => Effect_exports.gen(function* () {
1949
+ for (const [i, relPath] of run.changes.untrackedFiles.entries()) {
1950
+ const sandboxFilePath = `${run.handle.worktreePath}/${relPath}`;
1951
+ const hostFilePath = stagedUntrackedPath(run, i);
1952
+ yield* Effect_exports.tryPromise({
1953
+ try: async () => {
1954
+ await mkdir(dirname(hostFilePath), { recursive: true });
1955
+ await run.handle.copyFileOut(sandboxFilePath, hostFilePath);
1956
+ },
1957
+ catch: (e) => new SyncError({
1958
+ message: `Failed to save untracked file ${relPath}: ${e instanceof Error ? e.message : String(e)}`
1959
+ })
1960
+ });
1961
+ }
1962
+ });
1963
+ var checkUntrackedDestinations = (run) => Effect_exports.all(
1964
+ run.changes.untrackedFiles.map(
1965
+ (relPath, i) => checkStagedFile(stagedUntrackedPath(run, i), relPath).pipe(
1966
+ Effect_exports.andThen(() => resolveHostDestination(run.realRoot, relPath))
1967
+ )
1968
+ )
1969
+ );
1970
+ var saveAndCheck = (run) => Effect_exports.gen(function* () {
1971
+ const { changes } = run;
1972
+ const nonEmptyPatches = changes.hasCommits ? yield* saveCommitPatches(run) : [];
1973
+ if (changes.hasDiff) {
1974
+ yield* saveDiff(run);
1975
+ }
1976
+ if (changes.hasUntracked) {
1977
+ yield* saveUntracked(run);
1978
+ }
1979
+ yield* checkUntrackedDestinations(run);
1980
+ yield* checkPatchFileSymlinks(
1981
+ [...nonEmptyPatches, ...changes.hasDiff ? [diffPathOf(run)] : []],
1982
+ hostSymlinkAt(run.realRoot)
1983
+ );
1984
+ return nonEmptyPatches;
1985
+ });
1986
+
1987
+ // src/syncOut.ts
1988
+ var removePatchDir = (hostRepoDir, patchDir) => Effect_exports.tryPromise({
1989
+ try: async () => {
1990
+ await rm(patchDir, { recursive: true, force: true });
1991
+ const patchesRoot = join(hostRepoDir, ".sandcastle", "patches");
1992
+ try {
1993
+ const remaining = await readdir(patchesRoot);
1994
+ if (remaining.length === 0) {
1995
+ await rm(patchesRoot, {
1996
+ recursive: true,
1997
+ force: true
1998
+ });
1999
+ }
2000
+ } catch {
2001
+ }
2002
+ },
2003
+ catch: () => new SyncError({ message: "Failed to clean up patch directory" })
2004
+ });
2005
+ var copyUntrackedToHost = (run, destinations) => Effect_exports.tryPromise({
2006
+ try: async () => {
2007
+ for (const [i, destPath] of destinations.entries()) {
2008
+ const srcPath = stagedUntrackedPath(run, i);
2009
+ await mkdir(dirname(destPath), { recursive: true });
2010
+ const content = await readFile$1(srcPath);
2011
+ await writeFile(destPath, content);
2012
+ }
2013
+ },
2014
+ catch: (e) => new SyncError({
2015
+ message: `Failed to copy untracked files: ${e instanceof Error ? e.message : String(e)}`
2016
+ })
2017
+ });
2018
+ var failed = (effect) => Effect_exports.either(effect).pipe(Effect_exports.map((result) => result._tag === "Left"));
2019
+ var applySaved = (run, nonEmptyPatches) => Effect_exports.gen(function* () {
2020
+ const { hostRepoDir, changes } = run;
2021
+ if (nonEmptyPatches.length > 0) {
2022
+ yield* Effect_exports.either(execHostGit(["am", "--abort"], hostRepoDir));
2023
+ if (yield* failed(
2024
+ execHostGit(["am", "--3way", ...nonEmptyPatches], hostRepoDir)
2025
+ )) {
2026
+ return "commits";
2027
+ }
2028
+ }
2029
+ if (changes.hasDiff && (yield* failed(execHostGit(["apply", diffPathOf(run)], hostRepoDir)))) {
2030
+ return "diff";
2031
+ }
2032
+ if (changes.hasUntracked) {
2033
+ const destinations = yield* checkUntrackedDestinations(run);
2034
+ if (yield* failed(copyUntrackedToHost(run, destinations))) {
2035
+ return "untracked";
2036
+ }
2037
+ }
2038
+ return void 0;
2039
+ });
2040
+ var completeSyncOut = (run, nonEmptyPatches, failedStep) => Effect_exports.gen(function* () {
2041
+ const { changes } = run;
2042
+ if (changes.hasCommits && failedStep !== "commits") {
2043
+ yield* execOk2(
2044
+ run.handle,
2045
+ `git update-ref ${SYNC_BASE_REF} ${changes.sandboxHead}`,
2046
+ { cwd: run.handle.worktreePath }
2047
+ );
2048
+ }
2049
+ if (failedStep) {
2050
+ const msg = buildRecoveryMessage({
2051
+ patchDir: join(".sandcastle", "patches", basename(run.patchDir)),
2052
+ failedStep,
2053
+ hasCommits: nonEmptyPatches.length > 0,
2054
+ hasDiff: changes.hasDiff,
2055
+ hasUntracked: changes.hasUntracked
2056
+ });
2057
+ yield* Console_exports.error(`
2058
+ ${msg}`);
2059
+ } else {
2060
+ yield* removePatchDir(run.hostRepoDir, run.patchDir);
2061
+ }
2062
+ });
2063
+ var syncOut = (hostRepoDir, handle) => {
2064
+ let createdPatchDir;
2065
+ return Effect_exports.gen(function* () {
2066
+ const realRoot = yield* realRootOf(hostRepoDir);
2067
+ const changes = yield* inspectSandbox(hostRepoDir, handle);
2068
+ if (!changes.hasCommits && !changes.hasDiff && !changes.hasUntracked) {
2069
+ return;
2070
+ }
2071
+ const untrackedSegments = yield* Effect_exports.all(
2072
+ changes.untrackedFiles.map((relPath) => checkRelativePath(relPath))
2073
+ );
2074
+ const patchDir = yield* createPatchDir(hostRepoDir);
2075
+ createdPatchDir = patchDir;
2076
+ yield* resolveHostDestination(realRoot, relative(hostRepoDir, patchDir));
2077
+ const run = {
2078
+ hostRepoDir,
2079
+ handle,
2080
+ realRoot,
2081
+ changes,
2082
+ untrackedSegments,
2083
+ patchDir,
2084
+ untrackedDir: join(patchDir, "untracked")
2085
+ };
2086
+ const nonEmptyPatches = yield* saveAndCheck(run);
2087
+ const failedStep = yield* applySaved(run, nonEmptyPatches);
2088
+ yield* completeSyncOut(run, nonEmptyPatches, failedStep);
2089
+ }).pipe(
2090
+ // A refused path leaves nothing the sandbox wrote behind on the host.
2091
+ Effect_exports.tapError(
2092
+ (e) => e._tag === "SyncOutPathError" && createdPatchDir !== void 0 ? removePatchDir(hostRepoDir, createdPatchDir).pipe(Effect_exports.ignore) : Effect_exports.void
2093
+ )
2094
+ );
2095
+ };
2096
+
2097
+ // src/lifecycleHostGit.ts
2098
+ var readHostCurrentBranch = (options) => options.branch !== void 0 && options.branch !== "" ? Effect_exports.succeed(null) : hostGit(["rev-parse", "--abbrev-ref", "HEAD"], options.hostRepoDir).pipe(
2099
+ Effect_exports.map((stdout) => stdout.trim()),
2100
+ Effect_exports.orDie
2101
+ );
2102
+ var readHostIdentity = (hostRepoDir) => {
2103
+ const readIdentity = (key) => hostGit(["config", key], hostRepoDir).pipe(
2104
+ Effect_exports.map((stdout) => stdout.trim()),
2105
+ Effect_exports.orElseSucceed(() => "")
2106
+ );
2107
+ return Effect_exports.all([readIdentity("user.name"), readIdentity("user.email")], {
2108
+ concurrency: "unbounded"
2109
+ }).pipe(Effect_exports.map(([name, email]) => ({ name, email })));
2110
+ };
2111
+ var collectCommits = (range, hostRepoDir) => hostGit(["rev-list", ...range, "--reverse"], hostRepoDir).pipe(
2112
+ Effect_exports.map((stdout) => {
2113
+ const lines = stdout.trim();
2114
+ return lines === "" ? [] : lines.split("\n").map((sha) => ({ sha }));
2115
+ }),
2116
+ Effect_exports.orElseSucceed(() => [])
2117
+ );
2118
+ var mergeToHost = (sourceBranch, targetBranch, hostRepoDir) => (
2119
+ // `--`: the branch name comes from the sandbox.
2120
+ hostGit(["merge", "--", sourceBranch], hostRepoDir).pipe(
2121
+ Effect_exports.asVoid,
2122
+ Effect_exports.catchAll(
2123
+ (e) => Effect_exports.gen(function* () {
2124
+ const gitOutput = [e.stdout, e.stderr].map((s) => s.trim()).filter((s) => s !== "").join("\n");
2125
+ const mergeStarted = yield* hostGit(
2126
+ ["rev-parse", "-q", "--verify", "MERGE_HEAD"],
2127
+ hostRepoDir
2128
+ ).pipe(
2129
+ Effect_exports.as(true),
2130
+ Effect_exports.orElseSucceed(() => false)
2131
+ );
2132
+ if (mergeStarted) {
2133
+ yield* hostGit(["merge", "--abort"], hostRepoDir).pipe(Effect_exports.ignore);
2134
+ }
2135
+ return yield* new SyncError({
2136
+ message: `Merge of '${sourceBranch}' onto '${targetBranch}' failed${mergeStarted ? " and was aborted" : ""}, so '${targetBranch}' is unchanged.${gitOutput === "" ? " " : `
2137
+ git merge said:
2138
+ ${gitOutput}
2139
+ `}The temporary branch '${sourceBranch}' has been preserved. To retry: git merge ${sourceBranch} (resolve any conflicts and commit), then clean up: git branch -D ${sourceBranch}`
2140
+ });
2141
+ })
2142
+ )
2143
+ )
2144
+ );
2145
+ var collectCommitsLogged = (range, hostRepoDir, timeoutMs) => Effect_exports.gen(function* () {
2146
+ const display = yield* Display;
2147
+ return yield* display.taskLog(
2148
+ "Collecting commits",
2149
+ () => collectCommits([range], hostRepoDir).pipe(
2150
+ withTimeout(
2151
+ timeoutMs,
2152
+ () => new CommitCollectionTimeoutError({
2153
+ message: `Commit collection timed out after ${timeoutMs}ms`,
2154
+ timeoutMs
2155
+ })
2156
+ )
2157
+ )
2158
+ );
2159
+ });
2160
+ var mergeToHostWithTimeout = (merge) => mergeToHost(merge.tempBranch, merge.hostBranch, merge.hostRepoDir).pipe(
2161
+ withTimeout(
2162
+ merge.mergeToHostTimeoutMs,
2163
+ () => new MergeToHostTimeoutError({
2164
+ message: `Merge of '${merge.tempBranch}' to '${merge.hostBranch}' timed out after ${merge.mergeToHostTimeoutMs}ms`,
2165
+ timeoutMs: merge.mergeToHostTimeoutMs,
2166
+ sourceBranch: merge.tempBranch,
2167
+ targetBranch: merge.hostBranch
2168
+ })
2169
+ )
2170
+ );
2171
+ var mergeTempBranch = (merge) => Effect_exports.gen(function* () {
2172
+ const display = yield* Display;
2173
+ if (!merge.keepSourceBranch) {
2174
+ yield* execOk(merge.sandbox, "git checkout --detach", {
2175
+ cwd: merge.sandboxRepoDir
2176
+ });
2177
+ }
2178
+ if (merge.hasNewCommits) {
2179
+ yield* display.taskLog(
2180
+ `Merging to ${merge.hostBranch}`,
2181
+ () => mergeToHostWithTimeout(merge)
2182
+ );
2183
+ }
2184
+ if (!merge.keepSourceBranch) {
2185
+ yield* hostGit(
2186
+ ["branch", "-D", "--", merge.tempBranch],
2187
+ merge.hostRepoDir
2188
+ ).pipe(Effect_exports.ignore);
2189
+ }
2190
+ });
2191
+
2192
+ // src/SandboxLifecycle.ts
2193
+ var GIT_SETUP_TIMEOUT_MS = 1e4;
2194
+ var COMMIT_COLLECTION_TIMEOUT_MS = 3e4;
2195
+ var MERGE_TO_HOST_TIMEOUT_MS = 3e4;
2196
+ var runHostHooks = (hooks, cwd, signal) => Effect_exports.gen(function* () {
2197
+ for (const hook of hooks) {
2198
+ yield* runHostHook(hook, cwd, signal);
2199
+ }
2200
+ });
2201
+ var resolveRun = (options, sandbox) => ({
2202
+ options,
2203
+ sandbox,
2204
+ // Resolve effective timeouts, falling back to the built-in defaults.
2205
+ gitSetupTimeoutMs: options.timeouts?.gitSetupMs ?? GIT_SETUP_TIMEOUT_MS,
2206
+ commitCollectionTimeoutMs: options.timeouts?.commitCollectionMs ?? COMMIT_COLLECTION_TIMEOUT_MS,
2207
+ mergeToHostTimeoutMs: options.timeouts?.mergeToHostMs ?? MERGE_TO_HOST_TIMEOUT_MS,
2208
+ signal: options.signal ?? new AbortController().signal,
2209
+ hostSideWorktreePath: options.hostWorktreePath ?? options.sandboxRepoDir
2210
+ });
2211
+ var setUpSandbox = (run, identity) => Effect_exports.gen(function* () {
2212
+ const display = yield* Display;
2213
+ const { sandbox, options } = run;
2214
+ const { sandboxRepoDir, hooks } = options;
2215
+ return yield* display.taskLog(
2216
+ "Setting up sandbox",
2217
+ (message) => Effect_exports.gen(function* () {
2218
+ const resolvedBranch = yield* setUpSandboxGit({
2219
+ sandbox,
2220
+ sandboxRepoDir,
2221
+ gitSetupTimeoutMs: run.gitSetupTimeoutMs,
2222
+ identity
2223
+ });
2224
+ const sandboxHooks = hooks?.sandbox?.onSandboxReady ?? [];
2225
+ const hostHooks = hooks?.host?.onSandboxReady ?? [];
2226
+ for (const hook of sandboxHooks) {
2227
+ message(hook.command);
2228
+ }
2229
+ for (const hook of hostHooks) {
2230
+ message(`[host] ${hook.command}`);
2231
+ }
2232
+ yield* runOnSandboxReadyHooks({
2233
+ sandbox,
2234
+ sandboxRepoDir,
2235
+ hostWorktreePath: run.hostSideWorktreePath,
2236
+ signal: run.signal,
2237
+ sandboxHooks,
2238
+ hostHooks
2239
+ });
2240
+ return resolvedBranch;
2241
+ })
2242
+ );
2243
+ });
2244
+ var syncToHost = (run, baseHead) => Effect_exports.gen(function* () {
2245
+ const { applyToHost, sandboxRepoDir } = run.options;
2246
+ if (!applyToHost) {
2247
+ return;
2248
+ }
2249
+ const display = yield* Display;
2250
+ const commitCount = yield* countCommitsToSync(
2251
+ run.sandbox,
2252
+ sandboxRepoDir,
2253
+ baseHead
2254
+ );
2255
+ yield* display.taskLog(
2256
+ commitCount > 0 ? `Syncing ${commitCount} commit${commitCount === 1 ? "" : "s"} to host` : "No commits to sync out",
2257
+ () => applyToHost()
2258
+ );
2259
+ });
2260
+ var mergeBack = (run, branches) => Effect_exports.gen(function* () {
2261
+ const { baseHead } = branches;
2262
+ const hasNewCommits = yield* hostGit(
2263
+ ["rev-list", `${baseHead}..HEAD`, "--count"],
2264
+ run.hostSideWorktreePath
2265
+ ).pipe(
2266
+ Effect_exports.map((stdout) => Number(stdout.trim()) > 0),
2267
+ Effect_exports.orElseSucceed(() => false)
2268
+ );
2269
+ yield* mergeTempBranch({
2270
+ sandbox: run.sandbox,
2271
+ sandboxRepoDir: run.options.sandboxRepoDir,
2272
+ hostRepoDir: run.options.hostRepoDir,
2273
+ keepSourceBranch: run.options.keepSourceBranch === true,
2274
+ mergeToHostTimeoutMs: run.mergeToHostTimeoutMs,
2275
+ hasNewCommits,
2276
+ tempBranch: branches.tempBranch,
2277
+ hostBranch: branches.hostBranch
2278
+ });
2279
+ return yield* collectCommitsLogged(
2280
+ `${baseHead}..HEAD`,
2281
+ run.options.hostRepoDir,
2282
+ run.commitCollectionTimeoutMs
2283
+ );
2284
+ });
2285
+ var withSandboxLifecycle = (options, sandbox, work) => Effect_exports.gen(function* () {
2286
+ const run = resolveRun(options, sandbox);
2287
+ const { sandboxRepoDir } = options;
2288
+ const hostCurrentBranch = yield* readHostCurrentBranch(options);
2289
+ const identity = yield* readHostIdentity(options.hostRepoDir);
2290
+ const resolvedBranch = yield* setUpSandbox(run, identity);
2291
+ const targetBranch = options.branch ?? resolvedBranch;
2292
+ const baseHead = yield* hostGit(
2293
+ ["rev-parse", "HEAD"],
2294
+ run.hostSideWorktreePath
2295
+ ).pipe(
2296
+ Effect_exports.map((stdout) => stdout.trim()),
2297
+ Effect_exports.orDie
2298
+ );
2299
+ const result = yield* work({ sandbox, sandboxRepoDir, baseHead });
2300
+ yield* syncToHost(run, baseHead);
2301
+ if (hostCurrentBranch === null) {
2302
+ const commits2 = yield* collectCommitsLogged(
2303
+ `${baseHead}..refs/heads/${targetBranch}`,
2304
+ options.hostRepoDir,
2305
+ run.commitCollectionTimeoutMs
2306
+ );
2307
+ return { result, branch: targetBranch, commits: commits2 };
2308
+ }
2309
+ const commits = yield* mergeBack(run, {
2310
+ baseHead,
2311
+ tempBranch: resolvedBranch,
2312
+ hostBranch: hostCurrentBranch
2313
+ });
2314
+ return { result, branch: hostCurrentBranch, commits };
2315
+ });
2316
+ var execHostGit2 = (args, cwd) => hostGit(args, cwd).pipe(
2317
+ Effect_exports.mapError(
2318
+ (e) => new SyncError({
2319
+ message: `Host command failed: git ${args.join(" ")}
2320
+ ${e.message}`
2321
+ })
2322
+ )
2323
+ );
2324
+ var execOk3 = (handle, command, options) => Effect_exports.tryPromise({
2325
+ try: () => handle.exec(command, options),
2326
+ catch: (e) => new SyncError({
2327
+ message: `Sandbox exec failed: ${command}
2328
+ ${e instanceof Error ? e.message : String(e)}`
2329
+ })
2330
+ }).pipe(
2331
+ Effect_exports.flatMap(
2332
+ (result) => result.exitCode === 0 ? Effect_exports.succeed(result) : Effect_exports.fail(
2333
+ new SyncError({
2334
+ message: `Sandbox command failed (exit ${result.exitCode}): ${command}
2335
+ ${result.stderr}`
2336
+ })
2337
+ )
2338
+ )
2339
+ );
2340
+ var copyBundleIn = (handle, bundleHostPath) => Effect_exports.gen(function* () {
2341
+ const mkTempResult = yield* execOk3(
2342
+ handle,
2343
+ "mktemp -d -t sandcastle-XXXXXX"
2344
+ );
2345
+ const sandboxTmpDir = mkTempResult.stdout.trim();
2346
+ const bundleSandboxPath = `${sandboxTmpDir}/repo.bundle`;
2347
+ yield* Effect_exports.tryPromise({
2348
+ try: () => handle.copyIn(bundleHostPath, bundleSandboxPath),
2349
+ catch: (e) => new SyncError({
2350
+ message: `Failed to copy bundle into sandbox: ${e instanceof Error ? e.message : String(e)}`
2351
+ })
2352
+ });
2353
+ return { sandboxTmpDir, bundleSandboxPath };
2354
+ });
2355
+ var verifyHeadsMatch = (hostRepoDir, handle) => Effect_exports.gen(function* () {
2356
+ const hostHead = (yield* execHostGit2(
2357
+ ["rev-parse", "HEAD"],
2358
+ hostRepoDir
2359
+ )).trim();
2360
+ const sandboxHead = (yield* execOk3(handle, "git rev-parse HEAD", {
2361
+ cwd: handle.worktreePath
2362
+ })).stdout.trim();
2363
+ return yield* hostHead === sandboxHead ? Effect_exports.void : new SyncError({
2364
+ message: `HEAD mismatch after sync-in: host=${hostHead} sandbox=${sandboxHead}`
2365
+ });
2366
+ });
2367
+ var cloneViaBundle = (hostRepoDir, handle, { bundleHostPath, branch }) => Effect_exports.gen(function* () {
2368
+ yield* execHostGit2(
2369
+ ["bundle", "create", bundleHostPath, "--all"],
2370
+ hostRepoDir
2371
+ );
2372
+ const { sandboxTmpDir, bundleSandboxPath } = yield* copyBundleIn(
2373
+ handle,
2374
+ bundleHostPath
2375
+ );
2376
+ const { worktreePath } = handle;
2377
+ yield* execOk3(
2378
+ handle,
2379
+ `git clone "${bundleSandboxPath}" "${worktreePath}_clone"`
2380
+ );
2381
+ yield* execOk3(
2382
+ handle,
2383
+ `rm -rf "${worktreePath}" && mv "${worktreePath}_clone" "${worktreePath}"`
2384
+ );
2385
+ yield* execOk3(handle, `git checkout "${branch}"`, {
2386
+ cwd: worktreePath
2387
+ });
2388
+ yield* Effect_exports.tryPromise({
2389
+ try: () => handle.exec(`rm -rf "${sandboxTmpDir}"`),
2390
+ catch: () => new SyncError({ message: "Failed to clean up sandbox temp dir" })
2391
+ });
2392
+ yield* verifyHeadsMatch(hostRepoDir, handle);
2393
+ });
2394
+ var syncIn = (hostRepoDir, handle) => Effect_exports.gen(function* () {
2395
+ const branch = (yield* execHostGit2(
2396
+ ["rev-parse", "--abbrev-ref", "HEAD"],
2397
+ hostRepoDir
2398
+ )).trim();
2399
+ const bundleDir = yield* Effect_exports.tryPromise({
2400
+ try: () => mkdtemp(join(tmpdir(), "sandcastle-bundle-")),
2401
+ catch: (e) => new SyncError({
2402
+ message: `Failed to create temp dir: ${e instanceof Error ? e.message : String(e)}`
2403
+ })
2404
+ });
2405
+ yield* Effect_exports.ensuring(
2406
+ cloneViaBundle(hostRepoDir, handle, {
2407
+ bundleHostPath: join(bundleDir, "repo.bundle"),
2408
+ branch
2409
+ }),
2410
+ // Clean up host-side bundle temp dir (runs regardless of success/failure)
2411
+ Effect_exports.promise(() => rm(bundleDir, { recursive: true, force: true }))
2412
+ );
2413
+ return { branch };
2414
+ });
2415
+
2416
+ // src/createClosingIfAbandoned.ts
2417
+ var createClosingIfAbandoned = (create2, onError) => Effect_exports.suspend(() => {
2418
+ let pending;
2419
+ return Effect_exports.tryPromise({
2420
+ try: () => pending = create2(),
2421
+ catch: onError
2422
+ }).pipe(
2423
+ Effect_exports.onInterrupt(
2424
+ () => Effect_exports.sync(() => {
2425
+ pending?.then((handle) => handle.close()).catch(() => void 0);
2426
+ })
2427
+ )
2428
+ );
2429
+ });
2430
+ var attempt3 = (call) => Effect_exports.async((resume) => {
2431
+ call((error, value) => {
2432
+ resume(
2433
+ Effect_exports.succeed(error === null ? Option_exports.some(value) : Option_exports.none())
2434
+ );
2435
+ });
2436
+ });
2437
+ var realPath2 = (p) => attempt3((done) => {
2438
+ realpath(p, done);
2439
+ });
2440
+ var readText2 = (p) => attempt3((done) => {
2441
+ readFile(p, "utf8", done);
2442
+ });
2443
+ var statOf2 = (p) => attempt3((done) => {
2444
+ lstat(p, done);
2445
+ });
2446
+ var ensureDir = (p) => attempt3((done) => {
2447
+ mkdir$1(p, { recursive: true }, done);
2448
+ });
2449
+ var listDir = (p) => attempt3((done) => {
2450
+ readdir$1(p, done);
2451
+ });
2452
+ var ensureFile = (p) => attempt3((done) => {
2453
+ writeFile$1(p, "", { flag: "wx" }, (error) => {
2454
+ done(error, void 0);
2455
+ });
2456
+ });
2457
+
2458
+ // src/protectGitMounts.ts
2459
+ var GITDIR_LINE2 = /^gitdir: (?<path>.+)$/u;
2460
+ var toMountPath = (p) => process.platform === "win32" ? p.replaceAll("\\", "/") : p;
2461
+ var relativeWithin = (child, parent) => {
2462
+ const rel = relative(parent, child);
2463
+ return rel.startsWith("..") || isAbsolute(rel) ? Option_exports.none() : Option_exports.some(rel);
2464
+ };
2465
+ var worktreeConfigIn = (dir) => Effect_exports.gen(function* () {
2466
+ yield* ensureFile(join(dir, "config.worktree"));
2467
+ const real = yield* realPath2(join(dir, "config.worktree"));
2468
+ if (Option_exports.isNone(real)) {
2469
+ return [];
2470
+ }
2471
+ const stat5 = yield* statOf2(real.value);
2472
+ return Option_exports.isSome(stat5) && stat5.value.isFile() ? [real.value] : [];
2473
+ });
2474
+ var adminDirsOf = (commonDir) => Effect_exports.gen(function* () {
2475
+ const worktrees = join(commonDir, "worktrees");
2476
+ const names = yield* listDir(worktrees);
2477
+ const dirs = [];
2478
+ for (const name of Option_exports.getOrElse(names, () => [])) {
2479
+ const stat5 = yield* statOf2(join(worktrees, name));
2480
+ if (Option_exports.isSome(stat5) && stat5.value.isDirectory()) {
2481
+ dirs.push(join(worktrees, name));
2482
+ }
2483
+ }
2484
+ return dirs;
2485
+ });
2486
+ var commonDirControlPaths = (commonDir) => Effect_exports.gen(function* () {
2487
+ yield* ensureDir(join(commonDir, "hooks"));
2488
+ yield* ensureDir(join(commonDir, "info"));
2489
+ const worktreeConfigs = yield* worktreeConfigIn(commonDir);
2490
+ for (const adminDir of yield* adminDirsOf(commonDir)) {
2491
+ worktreeConfigs.push(...yield* worktreeConfigIn(adminDir));
2492
+ }
2493
+ return [
2494
+ ...["config", "hooks", "info"].map((name) => join(commonDir, name)),
2495
+ ...worktreeConfigs
2496
+ ];
2497
+ });
2498
+ var linkedWorktreeControlPaths = (dir, gitdir) => Effect_exports.gen(function* () {
2499
+ const dotGit = yield* realPath2(join(dir, ".git"));
2500
+ const adminDir = yield* realPath2(resolve(dir, gitdir));
2501
+ if (Option_exports.isNone(dotGit) || Option_exports.isNone(adminDir)) {
2502
+ return [];
2503
+ }
2504
+ const commondirFile = join(adminDir.value, "commondir");
2505
+ const commondir = yield* readText2(commondirFile);
2506
+ if (Option_exports.isNone(commondir)) {
2507
+ return [dotGit.value];
2508
+ }
2509
+ const commonDir = yield* realPath2(
2510
+ resolve(adminDir.value, commondir.value.trim())
2511
+ );
2512
+ return [
2513
+ dotGit.value,
2514
+ commondirFile,
2515
+ ...Option_exports.isSome(commonDir) ? yield* commonDirControlPaths(commonDir.value) : []
2516
+ ];
2517
+ });
2518
+ var controlPathsOf = (dir) => Effect_exports.gen(function* () {
2519
+ const dotGit = join(dir, ".git");
2520
+ const stat5 = yield* statOf2(dotGit);
2521
+ if (Option_exports.isNone(stat5)) {
2522
+ return [];
2523
+ }
2524
+ if (stat5.value.isDirectory()) {
2525
+ const real = yield* realPath2(dotGit);
2526
+ return Option_exports.isSome(real) ? yield* commonDirControlPaths(real.value) : [];
2527
+ }
2528
+ const pointer = yield* readText2(dotGit);
2529
+ const gitdir = pointer.pipe(
2530
+ Option_exports.flatMap(
2531
+ (text) => Option_exports.fromNullable(GITDIR_LINE2.exec(text.trim())?.groups?.["path"])
2532
+ )
2533
+ );
2534
+ return Option_exports.isSome(gitdir) ? yield* linkedWorktreeControlPaths(dir, gitdir.value) : [];
2535
+ });
2536
+ var reposOf = (mounts, worktreeOrRepoPath) => [
2537
+ .../* @__PURE__ */ new Set([
2538
+ worktreeOrRepoPath,
2539
+ ...mounts.filter((m) => posix.basename(toMountPath(m.hostPath)) === ".git").map((m) => dirname(m.hostPath))
2540
+ ])
2541
+ ];
2542
+ var protectAt = (result, hostPath, sandboxPath) => result.some((m) => m.sandboxPath === sandboxPath) ? result.map(
2543
+ (m) => m.sandboxPath === sandboxPath ? { ...m, readonly: true } : m
2544
+ ) : [
2545
+ ...result,
2546
+ { hostPath: toMountPath(hostPath), sandboxPath, readonly: true }
2547
+ ];
2548
+ var anchorsWithin = (mount, realMountPath, rel) => {
2549
+ if (mount.readonly === true) {
2550
+ return [];
2551
+ }
2552
+ const parts = rel.split(sep);
2553
+ return parts.slice(1).map((_, i) => {
2554
+ const dir = parts.slice(0, i + 1).join(sep);
2555
+ return {
2556
+ hostPath: toMountPath(join(realMountPath, dir)),
2557
+ sandboxPath: posix.join(mount.sandboxPath, toMountPath(dir))
2558
+ };
2559
+ });
2560
+ };
2561
+ var protectGitControlFiles = (mounts, worktreeOrRepoPath) => Effect_exports.gen(function* () {
2562
+ const controlPaths = new Set(
2563
+ (yield* Effect_exports.forEach(
2564
+ reposOf(mounts, worktreeOrRepoPath),
2565
+ (repo) => controlPathsOf(repo)
2566
+ )).flat()
2567
+ );
2568
+ const withRealPaths = yield* Effect_exports.all(
2569
+ mounts.map(
2570
+ (mount) => realPath2(mount.hostPath).pipe(Effect_exports.map((real) => ({ mount, real })))
2571
+ )
2572
+ );
2573
+ let result = mounts.map((m) => ({
2574
+ hostPath: m.hostPath,
2575
+ sandboxPath: m.sandboxPath,
2576
+ readonly: m.readonly
2577
+ }));
2578
+ const anchors = /* @__PURE__ */ new Map();
2579
+ for (const controlPath of controlPaths) {
2580
+ for (const { mount, real } of withRealPaths) {
2581
+ const rel = real.pipe(
2582
+ Option_exports.flatMap((path) => relativeWithin(controlPath, path))
2583
+ );
2584
+ if (Option_exports.isSome(rel) && Option_exports.isSome(real)) {
2585
+ for (const anchor of anchorsWithin(mount, real.value, rel.value)) {
2586
+ anchors.set(anchor.sandboxPath, anchor);
2587
+ }
2588
+ const sandboxPath = rel.value === "" ? mount.sandboxPath : posix.join(mount.sandboxPath, toMountPath(rel.value));
2589
+ result = protectAt(result, controlPath, sandboxPath);
2590
+ }
2591
+ }
2592
+ }
2593
+ const taken = new Set(result.map((m) => m.sandboxPath));
2594
+ return [
2595
+ ...result.slice(0, mounts.length),
2596
+ ...[...anchors.values()].filter((a) => !taken.has(a.sandboxPath)),
2597
+ ...result.slice(mounts.length)
2598
+ ];
2599
+ });
2600
+
2601
+ // src/startSandbox.ts
2602
+ var CONTAINER_START_TIMEOUT_MS = 12e4;
2603
+ var SYNC_IN_TIMEOUT_MS = 12e4;
2604
+ var COPY_PATHS_TIMEOUT_MS = 12e4;
2605
+ var toResult = (handle) => ({
2606
+ handle,
2607
+ sandbox: makeSandboxFromHandle(handle),
2608
+ worktreePath: handle.worktreePath
2609
+ });
2610
+ var isBindMountOptions = (options) => options.provider.tag === "bind-mount";
2611
+ var isNoSandboxOptions = (options) => options.provider.tag === "none";
2612
+ var startSandbox = (options) => {
2613
+ if (isBindMountOptions(options)) {
2614
+ return startBindMountSandbox(options);
2615
+ }
2616
+ if (isNoSandboxOptions(options)) {
2617
+ return startNoSandbox(options);
2618
+ }
2619
+ return startIsolatedSandbox(options);
2620
+ };
2621
+ var startNoSandbox = (options) => Effect_exports.tryPromise({
2622
+ try: () => options.provider.create({
2623
+ worktreePath: options.worktreeOrRepoPath,
2624
+ env: options.env
2625
+ }),
2626
+ catch: (e) => new WorktreeError({
2627
+ message: `Provider '${options.provider.name}' create failed: ${e instanceof Error ? e.message : String(e)}`
2628
+ })
2629
+ }).pipe(Effect_exports.map((handle) => toResult(handle)));
2630
+ var startBindMountSandbox = (options) => {
2631
+ const { worktreeOrRepoPath, provider } = options;
2632
+ const rawMounts = [
2633
+ { hostPath: worktreeOrRepoPath, sandboxPath: options.repoDir },
2634
+ ...options.gitMounts
2635
+ ];
2636
+ return protectGitControlFiles(
2637
+ normalizeMounts(rawMounts, {
2638
+ worktreeHostPath: worktreeOrRepoPath,
2639
+ sandboxRepoDir: SANDBOX_REPO_DIR
2640
+ }),
2641
+ worktreeOrRepoPath
2642
+ ).pipe(
2643
+ Effect_exports.flatMap(
2644
+ (mounts) => createClosingIfAbandoned(
2645
+ () => provider.create({
2646
+ worktreePath: process.platform === "win32" ? worktreeOrRepoPath.replaceAll("\\", "/") : worktreeOrRepoPath,
2647
+ hostRepoPath: options.hostRepoDir,
2648
+ mounts,
2649
+ env: options.env
2650
+ }),
2651
+ (e) => new WorktreeError({
2652
+ message: `Provider '${provider.name}' create failed: ${e instanceof Error ? e.message : String(e)}`
2653
+ })
2654
+ )
2655
+ ),
2656
+ Effect_exports.map((handle) => toResult(handle)),
2657
+ withTimeout(
2658
+ CONTAINER_START_TIMEOUT_MS,
2659
+ () => new ContainerStartTimeoutError({
2660
+ message: `Sandbox container start timed out after ${CONTAINER_START_TIMEOUT_MS}ms`,
2661
+ timeoutMs: CONTAINER_START_TIMEOUT_MS
2662
+ })
2663
+ )
2664
+ );
2665
+ };
2666
+ var copyPathsIn = (handle, paths, sourceDir) => Effect_exports.gen(function* () {
2667
+ for (const relativePath of paths) {
2668
+ const hostPath = join(sourceDir, relativePath);
2669
+ const exists = yield* Effect_exports.promise(
2670
+ () => access(hostPath).then(
2671
+ () => true,
2672
+ () => false
2673
+ )
2674
+ );
2675
+ if (!exists) {
2676
+ continue;
2677
+ }
2678
+ const sandboxPath = posix.join(handle.worktreePath, relativePath);
2679
+ yield* Effect_exports.tryPromise({
2680
+ try: () => handle.copyIn(hostPath, sandboxPath),
2681
+ catch: (e) => new WorktreeError({
2682
+ message: `Failed to copy ${relativePath} into sandbox: ${e instanceof Error ? e.message : String(e)}`
2683
+ })
2684
+ });
2685
+ }
2686
+ }).pipe(
2687
+ withTimeout(
2688
+ COPY_PATHS_TIMEOUT_MS,
2689
+ () => new CopyToWorktreeTimeoutError({
2690
+ message: `Copying paths to worktree timed out after ${COPY_PATHS_TIMEOUT_MS}ms`,
2691
+ timeoutMs: COPY_PATHS_TIMEOUT_MS,
2692
+ paths
2693
+ })
2694
+ )
2695
+ );
2696
+ var startIsolatedSandbox = (options) => Effect_exports.gen(function* () {
2697
+ const handle = yield* createClosingIfAbandoned(
2698
+ () => options.provider.create({ env: options.env }),
2699
+ (e) => new WorktreeError({
2700
+ message: `Isolated provider '${options.provider.name}' setup failed: ${e instanceof Error ? e.message : String(e)}`
2701
+ })
2702
+ ).pipe(
2703
+ withTimeout(
2704
+ CONTAINER_START_TIMEOUT_MS,
2705
+ () => new ContainerStartTimeoutError({
2706
+ message: `Isolated sandbox container start timed out after ${CONTAINER_START_TIMEOUT_MS}ms`,
2707
+ timeoutMs: CONTAINER_START_TIMEOUT_MS
2708
+ })
2709
+ )
2710
+ );
2711
+ yield* Effect_exports.gen(function* () {
2712
+ yield* syncIn(options.hostRepoDir, handle).pipe(
2713
+ withTimeout(
2714
+ SYNC_IN_TIMEOUT_MS,
2715
+ () => new SyncInTimeoutError({
2716
+ message: `Sync-in timed out after ${SYNC_IN_TIMEOUT_MS}ms`,
2717
+ timeoutMs: SYNC_IN_TIMEOUT_MS
2718
+ })
2719
+ )
2720
+ );
2721
+ if (options.copyPaths && options.copyPaths.length > 0) {
2722
+ yield* copyPathsIn(handle, options.copyPaths, options.copySourceDir);
2723
+ }
2724
+ }).pipe(
2725
+ Effect_exports.onError(
2726
+ () => Effect_exports.tryPromise(() => handle.close()).pipe(Effect_exports.ignore)
2727
+ )
2728
+ );
2729
+ return toResult(handle);
2730
+ });
2731
+ var SandboxFactory = class extends Context_exports.Tag(
2732
+ "@ai-hero/sandcastle/SandboxFactory"
2733
+ )() {
2734
+ };
2735
+ var reuseSandboxFactoryLayer = (info, sandbox) => Layer_exports.succeed(SandboxFactory, {
2736
+ withSandbox: (makeEffect) => makeEffect(info, sandbox).pipe(
2737
+ Effect_exports.map((value) => ({ value, preservedWorktreePath: void 0 }))
2738
+ )
2739
+ });
2740
+ var SandboxConfig = class extends Context_exports.Tag(
2741
+ "@ai-hero/sandcastle/SandboxFactory/SandboxConfig"
2742
+ )() {
2743
+ };
2744
+ var printWorktreePreservedMessage = (worktreePath, reason) => {
2745
+ console.error(`
2746
+ ${reason}`);
2747
+ console.error(` To review: cd ${worktreePath}`);
2748
+ console.error(` To clean up: git worktree remove --force ${worktreePath}`);
2749
+ };
2750
+ var cleanupTempBranch = (hostRepoDir, tempBranch) => deleteTempBranchIfUnused(hostRepoDir, tempBranch).pipe(
2751
+ Effect_exports.tap(({ unmergedCommits }) => {
2752
+ if (unmergedCommits === 0) {
2753
+ return Effect_exports.void;
2754
+ }
2755
+ const s = unmergedCommits === 1 ? "" : "s";
2756
+ return Effect_exports.all([
2757
+ Console_exports.error(
2758
+ `
2759
+ Temporary branch '${tempBranch}' kept: it has ${unmergedCommits} commit${s} not on any other branch.`
2760
+ ),
2761
+ Console_exports.error(` To merge: git merge ${tempBranch}`),
2762
+ Console_exports.error(` To discard: git branch -D ${tempBranch}`)
2763
+ ]);
2764
+ }),
2765
+ Effect_exports.asVoid,
2766
+ Effect_exports.catchAll(() => Effect_exports.void)
2767
+ );
2768
+ var cleanupWorktree = (worktreePath, exit, options) => {
2769
+ const { signal, temp } = options;
2770
+ if (!Exit_exports.isSuccess(exit) && signal?.aborted === true) {
2771
+ printWorktreePreservedMessage(
2772
+ worktreePath,
2773
+ `Worktree preserved at ${worktreePath}`
2774
+ );
2775
+ return Effect_exports.succeed(worktreePath);
2776
+ }
2777
+ return hasUncommittedChanges(worktreePath).pipe(
2778
+ Effect_exports.catchAll(() => Effect_exports.succeed(false)),
2779
+ Effect_exports.flatMap((isDirty) => {
2780
+ if (isDirty) {
2781
+ printWorktreePreservedMessage(
2782
+ worktreePath,
2783
+ Exit_exports.isSuccess(exit) ? `Run succeeded but worktree has uncommitted changes at ${worktreePath}` : `Worktree preserved at ${worktreePath}`
2784
+ );
2785
+ return Effect_exports.succeed(worktreePath);
2786
+ }
2787
+ const announceRemoval = Exit_exports.isSuccess(exit) ? Effect_exports.void : Console_exports.error(`
2788
+ Worktree removed (no uncommitted changes)`);
2789
+ return announceRemoval.pipe(
2790
+ Effect_exports.andThen(remove(worktreePath)),
2791
+ Effect_exports.andThen(
2792
+ temp ? cleanupTempBranch(temp.hostRepoDir, temp.branch) : Effect_exports.void
2793
+ ),
2794
+ Effect_exports.map(() => void 0)
2795
+ );
2796
+ })
2797
+ );
2798
+ };
2799
+ var attachPreservedPath = (path, e) => {
2800
+ if (path !== void 0) {
2801
+ if (e instanceof AgentIdleTimeoutError) {
2802
+ return new AgentIdleTimeoutError({
2803
+ message: e.message,
2804
+ timeoutMs: e.timeoutMs,
2805
+ preservedWorktreePath: path
2806
+ });
2807
+ }
2808
+ if (e instanceof AgentError) {
2809
+ return new AgentError({
2810
+ message: e.message,
2811
+ preservedWorktreePath: path
2812
+ });
2813
+ }
2814
+ }
2815
+ return e;
2816
+ };
2817
+ var resolveGitMounts = (gitPath) => Effect_exports.gen(function* () {
2818
+ const fs = yield* FileSystem_exports.FileSystem;
2819
+ const stat5 = yield* fs.stat(gitPath);
2820
+ if (stat5.type === "Directory") {
2821
+ return [{ hostPath: gitPath, sandboxPath: gitPath }];
2822
+ }
2823
+ const content = (yield* fs.readFileString(gitPath)).trim();
2824
+ const gitdirPath = /^gitdir:\s*(?<gitdir>.+)$/u.exec(content)?.groups?.["gitdir"];
2825
+ if (gitdirPath === void 0) {
2826
+ return [{ hostPath: gitPath, sandboxPath: gitPath }];
2827
+ }
2828
+ const parentGitDir = resolve(gitdirPath, "..", "..");
2829
+ return [
2830
+ { hostPath: gitPath, sandboxPath: gitPath },
2831
+ { hostPath: parentGitDir, sandboxPath: parentGitDir }
2832
+ ];
2833
+ });
2834
+ var WorktreeDockerSandboxFactory = {
2835
+ layer: Layer_exports.effect(
2836
+ SandboxFactory,
2837
+ Effect_exports.gen(function* () {
2838
+ const {
2839
+ env,
2840
+ hostRepoDir,
2841
+ copyToWorktree: copyPaths,
2842
+ name,
2843
+ tempBranch,
2844
+ sandboxProvider,
2845
+ branchStrategy,
2846
+ hooks,
2847
+ signal,
2848
+ timeouts
2849
+ } = yield* SandboxConfig;
2850
+ const onWorktreeReady = hooks?.host?.onWorktreeReady ?? [];
2851
+ const isHeadMode = branchStrategy.type === "head";
2852
+ const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
2853
+ const baseBranch = branchStrategy.type === "branch" ? branchStrategy.baseBranch : void 0;
2854
+ const fileSystem = yield* FileSystem_exports.FileSystem;
2855
+ const display = yield* Display;
2856
+ const tempBranchOf = (worktreeInfo) => branch === void 0 ? { hostRepoDir, branch: worktreeInfo.branch } : void 0;
2857
+ const pruneAndCreate = () => pruneStale(hostRepoDir).pipe(
2858
+ Effect_exports.catchAll(
2859
+ (e) => Console_exports.error(
2860
+ "[sandcastle] Warning: failed to prune stale worktrees:",
2861
+ e.message
2862
+ )
2863
+ ),
2864
+ Effect_exports.andThen(
2865
+ branch !== void 0 && branch !== "" ? create(hostRepoDir, { branch, baseBranch }) : create(hostRepoDir, { name, tempBranch })
2866
+ ),
2867
+ Effect_exports.provideService(FileSystem_exports.FileSystem, fileSystem),
2868
+ // A SIGINT/SIGTERM exits the process before the release below runs,
2869
+ // so the worktree stays on disk. Say where it is, as createSandbox()
2870
+ // does, instead of leaving it behind silently.
2871
+ Effect_exports.map((info) => ({
2872
+ ...info,
2873
+ unregisterShutdown: registerShutdown(() => {
2874
+ printWorktreePreservedMessage(
2875
+ info.path,
2876
+ `Worktree preserved at ${info.path}`
2877
+ );
2878
+ })
2879
+ }))
2880
+ );
2881
+ const prepareWorktree = (worktreePath) => (copyPaths && copyPaths.length > 0 ? display.spinner(
2882
+ "Copying to worktree",
2883
+ copyToWorktree(
2884
+ copyPaths,
2885
+ hostRepoDir,
2886
+ worktreePath,
2887
+ timeouts?.copyToWorktreeMs
2888
+ )
2889
+ ) : Effect_exports.void).pipe(
2890
+ Effect_exports.andThen(
2891
+ onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, worktreePath, signal) : Effect_exports.void
2892
+ ),
2893
+ Effect_exports.andThen(
2894
+ resolveGitMounts(join(hostRepoDir, ".git")).pipe(
2895
+ Effect_exports.provideService(FileSystem_exports.FileSystem, fileSystem),
2896
+ Effect_exports.mapError(
2897
+ (e) => new WorktreeError({
2898
+ message: `Failed to resolve git mounts: ${String(e)}`
2899
+ })
2900
+ )
2901
+ )
2902
+ ),
2903
+ Effect_exports.flatMap(
2904
+ (gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
2905
+ )
2906
+ );
2907
+ const releaseWorktree = (worktreeInfo, exit) => Effect_exports.sync(worktreeInfo.unregisterShutdown).pipe(
2908
+ Effect_exports.andThen(
2909
+ cleanupWorktree(worktreeInfo.path, exit, {
2910
+ signal,
2911
+ temp: tempBranchOf(worktreeInfo)
2912
+ })
2913
+ )
2914
+ );
2915
+ return {
2916
+ withSandbox: (makeEffect) => {
2917
+ if (sandboxProvider.tag === "none") {
2918
+ let preservedPath;
2919
+ if (isHeadMode) {
2920
+ return (onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, hostRepoDir, signal) : Effect_exports.void).pipe(
2921
+ Effect_exports.andThen(
2922
+ Effect_exports.acquireUseRelease(
2923
+ startSandbox({
2924
+ provider: sandboxProvider,
2925
+ hostRepoDir,
2926
+ env,
2927
+ worktreeOrRepoPath: hostRepoDir
2928
+ }),
2929
+ ({ sandbox, worktreePath }) => makeEffect(
2930
+ {
2931
+ hostWorktreePath: hostRepoDir,
2932
+ sandboxRepoPath: worktreePath
2933
+ },
2934
+ sandbox
2935
+ ),
2936
+ ({ handle }) => Effect_exports.tryPromise({
2937
+ try: () => handle.close(),
2938
+ catch: () => void 0
2939
+ }).pipe(Effect_exports.orDie)
2940
+ ).pipe(
2941
+ Effect_exports.map((value) => ({
2942
+ value,
2943
+ preservedWorktreePath: void 0
2944
+ }))
2945
+ )
2946
+ )
2947
+ );
2948
+ }
2949
+ return Effect_exports.acquireUseRelease(
2950
+ pruneAndCreate(),
2951
+ (worktreeInfo) => (copyPaths && copyPaths.length > 0 ? display.spinner(
2952
+ "Copying to worktree",
2953
+ copyToWorktree(
2954
+ copyPaths,
2955
+ hostRepoDir,
2956
+ worktreeInfo.path,
2957
+ timeouts?.copyToWorktreeMs
2958
+ )
2959
+ ) : Effect_exports.void).pipe(
2960
+ Effect_exports.andThen(
2961
+ onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, worktreeInfo.path, signal) : Effect_exports.void
2962
+ ),
2963
+ Effect_exports.andThen(
2964
+ Effect_exports.acquireUseRelease(
2965
+ startSandbox({
2966
+ provider: sandboxProvider,
2967
+ hostRepoDir,
2968
+ env,
2969
+ worktreeOrRepoPath: worktreeInfo.path
2970
+ }),
2971
+ ({ sandbox, worktreePath }) => makeEffect(
2972
+ {
2973
+ hostWorktreePath: worktreeInfo.path,
2974
+ sandboxRepoPath: worktreePath
2975
+ },
2976
+ sandbox
2977
+ ),
2978
+ ({ handle }) => Effect_exports.tryPromise({
2979
+ try: () => handle.close(),
2980
+ catch: () => void 0
2981
+ }).pipe(Effect_exports.orDie)
2982
+ )
2983
+ )
2984
+ ),
2985
+ (worktreeInfo, exit) => releaseWorktree(worktreeInfo, exit).pipe(
2986
+ Effect_exports.tap((p) => {
2987
+ preservedPath = p;
2988
+ }),
2989
+ Effect_exports.asVoid,
2990
+ Effect_exports.orDie
2991
+ )
2992
+ ).pipe(
2993
+ Effect_exports.map((value) => ({
2994
+ value,
2995
+ preservedWorktreePath: preservedPath
2996
+ })),
2997
+ Effect_exports.mapError(
2998
+ (e) => attachPreservedPath(preservedPath, e)
2999
+ )
3000
+ );
3001
+ }
3002
+ if (sandboxProvider.tag === "isolated") {
3003
+ let preservedPath;
3004
+ return Effect_exports.acquireUseRelease(
3005
+ pruneAndCreate(),
3006
+ (worktreeInfo) => (onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, worktreeInfo.path, signal) : Effect_exports.void).pipe(
3007
+ Effect_exports.andThen(
3008
+ Effect_exports.acquireUseRelease(
3009
+ startIsolatedSandbox({
3010
+ provider: sandboxProvider,
3011
+ hostRepoDir: worktreeInfo.path,
3012
+ env,
3013
+ copyPaths,
3014
+ copySourceDir: hostRepoDir
3015
+ }),
3016
+ ({ sandbox, worktreePath, handle }) => makeEffect(
3017
+ {
3018
+ hostWorktreePath: worktreeInfo.path,
3019
+ sandboxRepoPath: worktreePath,
3020
+ applyToHost: () => syncOut(worktreeInfo.path, handle)
3021
+ },
3022
+ sandbox
3023
+ ),
3024
+ ({ handle }) => Effect_exports.tryPromise({
3025
+ try: () => handle.close(),
3026
+ catch: () => void 0
3027
+ }).pipe(Effect_exports.orDie)
3028
+ )
3029
+ )
3030
+ ),
3031
+ (worktreeInfo, exit) => releaseWorktree(worktreeInfo, exit).pipe(
3032
+ Effect_exports.tap((p) => {
3033
+ preservedPath = p;
3034
+ }),
3035
+ Effect_exports.asVoid,
3036
+ Effect_exports.orDie
3037
+ )
3038
+ ).pipe(
3039
+ Effect_exports.map((value) => ({
3040
+ value,
3041
+ preservedWorktreePath: preservedPath
3042
+ })),
3043
+ Effect_exports.mapError(
3044
+ (e) => attachPreservedPath(preservedPath, e)
3045
+ )
3046
+ );
3047
+ }
3048
+ if (isHeadMode) {
3049
+ const gitPath = join(hostRepoDir, ".git");
3050
+ return (onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, hostRepoDir, signal) : Effect_exports.void).pipe(
3051
+ Effect_exports.andThen(resolveGitMounts(gitPath)),
3052
+ Effect_exports.provideService(FileSystem_exports.FileSystem, fileSystem),
3053
+ Effect_exports.mapError(
3054
+ (e) => new WorktreeError({
3055
+ message: `Failed to resolve git mounts: ${String(e)}`
3056
+ })
3057
+ ),
3058
+ Effect_exports.flatMap(
3059
+ (gitMounts) => (
3060
+ // Patch git mounts for Windows worktree compatibility (ADR-0006)
3061
+ patchGitMountsForWindows(
3062
+ gitMounts,
3063
+ hostRepoDir,
3064
+ SANDBOX_REPO_DIR
3065
+ )
3066
+ )
3067
+ ),
3068
+ Effect_exports.flatMap(
3069
+ (gitMounts) => Effect_exports.acquireUseRelease(
3070
+ startBindMountSandbox({
3071
+ provider: sandboxProvider,
3072
+ hostRepoDir,
3073
+ env,
3074
+ worktreeOrRepoPath: hostRepoDir,
3075
+ gitMounts,
3076
+ repoDir: SANDBOX_REPO_DIR
3077
+ }),
3078
+ // Use
3079
+ ({ sandbox, worktreePath, handle }) => makeEffect(
3080
+ {
3081
+ hostWorktreePath: hostRepoDir,
3082
+ sandboxRepoPath: worktreePath,
3083
+ bindMountHandle: handle
3084
+ },
3085
+ sandbox
3086
+ ),
3087
+ // Release
3088
+ ({ handle }) => Effect_exports.tryPromise({
3089
+ try: () => handle.close(),
3090
+ catch: () => void 0
3091
+ }).pipe(Effect_exports.orDie)
3092
+ ).pipe(
3093
+ Effect_exports.ensuring(removeMountTempDirs(gitMounts)),
3094
+ Effect_exports.map((value) => ({
3095
+ value,
3096
+ preservedWorktreePath: void 0
3097
+ }))
3098
+ )
3099
+ )
3100
+ );
3101
+ }
3102
+ let preservedWorktreePath;
3103
+ return Effect_exports.acquireUseRelease(
3104
+ // Acquire: prune stale worktrees (best-effort), then create the worktree.
3105
+ pruneAndCreate(),
3106
+ // Use: copy files, run host hooks, resolve+patch git mounts, then start
3107
+ // the sandbox under a nested acquireUseRelease.
3108
+ (worktreeInfo) => prepareWorktree(worktreeInfo.path).pipe(
3109
+ Effect_exports.flatMap(
3110
+ (gitMounts) => Effect_exports.acquireUseRelease(
3111
+ // sandboxProvider is guaranteed bind-mount here
3112
+ // (isolated providers return early above)
3113
+ startBindMountSandbox({
3114
+ provider: sandboxProvider,
3115
+ hostRepoDir,
3116
+ env,
3117
+ worktreeOrRepoPath: worktreeInfo.path,
3118
+ gitMounts,
3119
+ repoDir: SANDBOX_REPO_DIR
3120
+ }),
3121
+ ({ sandbox, worktreePath, handle }) => makeEffect(
3122
+ {
3123
+ hostWorktreePath: worktreeInfo.path,
3124
+ sandboxRepoPath: worktreePath,
3125
+ bindMountHandle: handle
3126
+ },
3127
+ sandbox
3128
+ ),
3129
+ ({ handle }) => Effect_exports.tryPromise({
3130
+ try: () => handle.close(),
3131
+ catch: () => void 0
3132
+ }).pipe(Effect_exports.orDie)
3133
+ ).pipe(Effect_exports.ensuring(removeMountTempDirs(gitMounts)))
3134
+ )
3135
+ ),
3136
+ // Release: remove or preserve the worktree based on dirty state.
3137
+ (worktreeInfo, exit) => releaseWorktree(worktreeInfo, exit).pipe(
3138
+ Effect_exports.tap((p) => {
3139
+ preservedWorktreePath = p;
3140
+ }),
3141
+ Effect_exports.asVoid,
3142
+ Effect_exports.orDie
3143
+ )
3144
+ ).pipe(
3145
+ Effect_exports.map((value) => ({
3146
+ value,
3147
+ preservedWorktreePath
3148
+ })),
3149
+ Effect_exports.mapError(
3150
+ (e) => attachPreservedPath(preservedWorktreePath, e)
3151
+ )
3152
+ );
3153
+ }
3154
+ };
3155
+ })
3156
+ )
3157
+ };
3158
+
3159
+ export { ClackDisplay, Display, FileDisplay, SandboxConfig, SandboxFactory, SilentDisplay, WorktreeDockerSandboxFactory, copyToWorktree, create, deleteTempBranchIfUnused, execOk, formatErrorMessage, generateTempBranchName, getCurrentBranch, hasUncommittedChanges, pruneStale, remove, resolveGitMounts, reuseSandboxFactoryLayer, runHostHooks, startBindMountSandbox, startIsolatedSandbox, startSandbox, syncOut, withFriendlyErrors, withSandboxLifecycle };
3160
+ //# sourceMappingURL=chunk-EM4QNWKF.js.map
3161
+ //# sourceMappingURL=chunk-EM4QNWKF.js.map