@ai-hero/sandcastle 0.12.0 → 0.14.0

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