@ai-hero/sandcastle 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
  2. package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
  3. package/dist/chunk-4BB7DNPW.js.map +1 -0
  4. package/dist/chunk-4GZMUHVO.js +60 -0
  5. package/dist/chunk-4GZMUHVO.js.map +1 -0
  6. package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
  7. package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
  8. package/dist/chunk-7PHPLDVS.js +284 -0
  9. package/dist/chunk-7PHPLDVS.js.map +1 -0
  10. package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
  11. package/dist/chunk-BXLS4HRY.js.map +1 -0
  12. package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
  13. package/dist/chunk-EM4QNWKF.js.map +1 -0
  14. package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
  15. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  16. package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
  17. package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
  18. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  19. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  20. package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
  21. package/dist/chunk-SAQXFLO2.js.map +1 -0
  22. package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
  23. package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
  24. package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
  25. package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
  26. package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
  27. package/dist/chunk-WYOGXC72.js.map +1 -0
  28. package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
  29. package/dist/chunk-YDQW5IOY.js.map +1 -0
  30. package/dist/index.d.ts +47 -4
  31. package/dist/index.js +536 -445
  32. package/dist/index.js.map +1 -1
  33. package/dist/main.js +72 -16
  34. package/dist/main.js.map +1 -1
  35. package/dist/sandboxes/bwrap.d.ts +1 -1
  36. package/dist/sandboxes/bwrap.js +9 -17
  37. package/dist/sandboxes/bwrap.js.map +1 -1
  38. package/dist/sandboxes/daytona.d.ts +1 -1
  39. package/dist/sandboxes/daytona.js +82 -79
  40. package/dist/sandboxes/daytona.js.map +1 -1
  41. package/dist/sandboxes/docker.d.ts +23 -1
  42. package/dist/sandboxes/docker.js +6 -5
  43. package/dist/sandboxes/e2b.d.ts +1 -1
  44. package/dist/sandboxes/e2b.js +4 -4
  45. package/dist/sandboxes/modal.d.ts +1 -1
  46. package/dist/sandboxes/modal.js +1 -1
  47. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  48. package/dist/sandboxes/no-sandbox.js +1 -1
  49. package/dist/sandboxes/podman.d.ts +27 -4
  50. package/dist/sandboxes/podman.js +18 -45
  51. package/dist/sandboxes/podman.js.map +1 -1
  52. package/dist/sandboxes/seatbelt.d.ts +2 -2
  53. package/dist/sandboxes/seatbelt.js +10 -10
  54. package/dist/sandboxes/seatbelt.js.map +1 -1
  55. package/dist/sandboxes/sprites.d.ts +1 -1
  56. package/dist/sandboxes/sprites.js +25 -4
  57. package/dist/sandboxes/sprites.js.map +1 -1
  58. package/dist/sandboxes/vercel.d.ts +10 -1
  59. package/dist/sandboxes/vercel.js +74 -46
  60. package/dist/sandboxes/vercel.js.map +1 -1
  61. package/dist/templates/parallel-planner/main.mts +43 -21
  62. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  63. package/dist/templates/sequential-reviewer/main.mts +1 -1
  64. package/package.json +7 -3
  65. package/dist/chunk-7N7AMUYA.js.map +0 -1
  66. package/dist/chunk-BIF2X6QB.js +0 -94
  67. package/dist/chunk-BIF2X6QB.js.map +0 -1
  68. package/dist/chunk-BVZWLFFT.js.map +0 -1
  69. package/dist/chunk-G2R53CVZ.js.map +0 -1
  70. package/dist/chunk-GCLEXPXG.js.map +0 -1
  71. package/dist/chunk-H2PEFS4W.js.map +0 -1
  72. package/dist/chunk-HSXPRZKG.js.map +0 -1
  73. package/dist/chunk-RDW7FNN6.js.map +0 -1
  74. package/dist/chunk-STB2U7BB.js.map +0 -1
@@ -1,15 +1,16 @@
1
1
  import { createRequire } from 'node:module';
2
+ import { patchGitMountsForWindows, SANDBOX_REPO_DIR, removeMountTempDirs, normalizeMounts, makeSandboxFromHandle } from './chunk-7PHPLDVS.js';
2
3
  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';
4
+ import { FileSystem_exports, WorktreeError, withTimeout, CopyToWorktreeTimeoutError, AgentIdleTimeoutError, AgentError, ContainerStartTimeoutError, SyncInTimeoutError, ExecError, HookTimeoutError, CopyToWorktreeError, SyncError, WorktreeTimeoutError, SyncOutPathError, HostGitError, CommitCollectionTimeoutError, GitSetupTimeoutError, MergeToHostTimeoutError } from './chunk-YDQW5IOY.js';
5
+ import { Effect_exports, Context_exports, Layer_exports, Console_exports, Exit_exports, Option_exports, DateTime_exports, Clock_exports, Predicate_exports, Ref_exports, Schedule_exports, Duration_exports, Deferred_exports, Runtime_exports } from './chunk-JEQ4IVQM.js';
6
+ import { join, dirname, relative, resolve, posix, basename, isAbsolute, sep, normalize, win32, delimiter } from 'path';
6
7
  import * as clack from '@clack/prompts';
7
8
  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
9
  import { randomBytes } from 'crypto';
12
10
  import { execFile, spawn } from 'child_process';
11
+ import { tmpdir, devNull } from 'os';
12
+ import { readFile, lstat, mkdir as mkdir$1, writeFile as writeFile$1, readdir as readdir$1, stat as stat$1, realpath, access as access$1, constants, readlink } from 'fs';
13
+ import { stat, mkdir, mkdtemp, rm, access, readdir, writeFile, readFile as readFile$1 } from 'fs/promises';
13
14
 
14
15
  createRequire(import.meta.url);
15
16
  var severityToClack = {
@@ -219,11 +220,176 @@ var FileDisplay = {
219
220
  var ClackDisplay = {
220
221
  layer: Layer_exports.scoped(Display, makeClackDisplayService)
221
222
  };
223
+
224
+ // src/ErrorHandler.ts
225
+ var formatErrorMessage = (error) => {
226
+ switch (error._tag) {
227
+ case "ExecError": {
228
+ return `Command failed in sandbox (${error.command}): ${error.message}`;
229
+ }
230
+ case "ExecHostError": {
231
+ return `Command failed on host (${error.command}): ${error.message}`;
232
+ }
233
+ case "CopyError": {
234
+ return `File copy failed: ${error.message}`;
235
+ }
236
+ case "DockerError": {
237
+ return `Docker operation failed: ${error.message}. Is Docker running?`;
238
+ }
239
+ case "PodmanError": {
240
+ return `Podman operation failed: ${error.message}. Is Podman running?`;
241
+ }
242
+ case "SyncError": {
243
+ return `Git sync failed: ${error.message}`;
244
+ }
245
+ case "WorktreeError": {
246
+ return `Git worktree operation failed: ${error.message}`;
247
+ }
248
+ case "PromptError": {
249
+ return `Failed to resolve prompt: ${error.message}`;
250
+ }
251
+ case "AgentError": {
252
+ return `Agent invocation failed: ${error.message}`;
253
+ }
254
+ case "ConfigDirError":
255
+ case "InitError":
256
+ case "AgentIdleTimeoutError":
257
+ case "WorktreeTimeoutError":
258
+ case "ContainerStartTimeoutError":
259
+ case "CopyToWorktreeTimeoutError":
260
+ case "CopyToWorktreeError":
261
+ case "SyncInTimeoutError":
262
+ case "HookTimeoutError":
263
+ case "GitSetupTimeoutError":
264
+ case "PromptExpansionTimeoutError":
265
+ case "CommitCollectionTimeoutError":
266
+ case "MergeToHostTimeoutError":
267
+ case "SessionCaptureError":
268
+ case "SyncOutPathError":
269
+ case "CwdError":
270
+ case "ImageNotFoundError": {
271
+ return error.message;
272
+ }
273
+ }
274
+ };
275
+ var showErrorAndExit = (error) => Effect_exports.gen(function* () {
276
+ const d = yield* Display;
277
+ yield* d.status(formatErrorMessage(error), "error");
278
+ return yield* Effect_exports.sync(() => process.exit(1));
279
+ });
280
+ var sandboxErrorTags = {
281
+ ExecError: true,
282
+ ExecHostError: true,
283
+ CopyError: true,
284
+ DockerError: true,
285
+ PodmanError: true,
286
+ SyncError: true,
287
+ SyncOutPathError: true,
288
+ WorktreeError: true,
289
+ PromptError: true,
290
+ AgentError: true,
291
+ ConfigDirError: true,
292
+ InitError: true,
293
+ AgentIdleTimeoutError: true,
294
+ WorktreeTimeoutError: true,
295
+ ContainerStartTimeoutError: true,
296
+ CopyToWorktreeTimeoutError: true,
297
+ CopyToWorktreeError: true,
298
+ SyncInTimeoutError: true,
299
+ HookTimeoutError: true,
300
+ GitSetupTimeoutError: true,
301
+ PromptExpansionTimeoutError: true,
302
+ CommitCollectionTimeoutError: true,
303
+ MergeToHostTimeoutError: true,
304
+ SessionCaptureError: true,
305
+ CwdError: true,
306
+ ImageNotFoundError: true
307
+ };
308
+ var isSandboxError = (error) => Predicate_exports.hasProperty(error, "_tag") && typeof error._tag === "string" && Object.hasOwn(sandboxErrorTags, error._tag);
309
+ var withFriendlyErrors = (effect) => Effect_exports.catchIf(
310
+ effect,
311
+ (error) => isSandboxError(error),
312
+ (error) => showErrorAndExit(error)
313
+ );
314
+
315
+ // src/hostGitEntries.ts
222
316
  var TRUSTED_SCOPES = /* @__PURE__ */ new Set([
223
317
  "system",
224
318
  "global",
225
319
  "command"
226
320
  ]);
321
+ var isTrusted = (entry) => TRUSTED_SCOPES.has(entry.scope);
322
+ var lastTrustedValue = (entries, keys) => {
323
+ const trusted = entries.filter((e) => isTrusted(e) && keys.includes(e.key));
324
+ const last = trusted.at(-1);
325
+ return last === void 0 ? void 0 : last.value ?? "true";
326
+ };
327
+ var keyAndValue = (entry) => {
328
+ const newline = entry.indexOf("\n");
329
+ return newline === -1 ? { key: entry, value: void 0 } : { key: entry.slice(0, newline), value: entry.slice(newline + 1) };
330
+ };
331
+ var parseConfigList = (output) => {
332
+ const fields = output.split("\0");
333
+ const entries = [];
334
+ for (let i = 0; i + 2 < fields.length; i += 3) {
335
+ entries.push({
336
+ scope: fields[i] ?? "",
337
+ origin: fields[i + 1] ?? "",
338
+ ...keyAndValue(fields[i + 2] ?? "")
339
+ });
340
+ }
341
+ return entries;
342
+ };
343
+ var parseFileConfigList = (output, file, scope) => output.split("\0").filter((entry) => entry !== "").map((entry) => {
344
+ const { key, value } = keyAndValue(entry);
345
+ return { scope, origin: `file:${file}`, key, value };
346
+ });
347
+
348
+ // src/hostGitHooks.ts
349
+ var hookKeyParts = (key) => {
350
+ const last = key.lastIndexOf(".");
351
+ return key.startsWith("hook.") && last > "hook.".length ? { name: key.slice("hook.".length, last), variable: key.slice(last + 1) } : void 0;
352
+ };
353
+ var RUNNING_HOOK_VARIABLES = /* @__PURE__ */ new Set([
354
+ "command",
355
+ "event",
356
+ "parallel"
357
+ ]);
358
+ var overridesForHook = (entries, name, repoVariables) => {
359
+ const key = (variable) => `hook.${name}.${variable}`;
360
+ const enabled = lastTrustedValue(entries, [key("enabled")]);
361
+ const command = lastTrustedValue(entries, [key("command")]);
362
+ if (command !== void 0) {
363
+ const events = entries.filter((e) => isTrusted(e) && e.key === key("event")).map((e) => [key("event"), e.value ?? ""]);
364
+ return [
365
+ [key("command"), command],
366
+ // An empty event clears the list; then the user's events, in order.
367
+ [key("event"), ""],
368
+ ...events,
369
+ [key("enabled"), enabled ?? "true"]
370
+ ];
371
+ }
372
+ if ([...repoVariables].some((v) => RUNNING_HOOK_VARIABLES.has(v))) {
373
+ return [[key("enabled"), "false"]];
374
+ }
375
+ return enabled === void 0 ? [] : [[key("enabled"), enabled]];
376
+ };
377
+ var hookOverrides = (entries) => {
378
+ const repoVariables = /* @__PURE__ */ new Map();
379
+ for (const entry of entries) {
380
+ const parts = isTrusted(entry) ? void 0 : hookKeyParts(entry.key);
381
+ if (parts !== void 0) {
382
+ const variables = repoVariables.get(parts.name) ?? /* @__PURE__ */ new Set();
383
+ variables.add(parts.variable);
384
+ repoVariables.set(parts.name, variables);
385
+ }
386
+ }
387
+ return [...repoVariables].flatMap(
388
+ ([name, variables]) => overridesForHook(entries, name, variables)
389
+ );
390
+ };
391
+
392
+ // src/hostGitConfig.ts
227
393
  var PINNED_GROUPS = [
228
394
  [["core.fsmonitor"], "false"],
229
395
  [["core.hookspath"], devNull],
@@ -255,7 +421,6 @@ var NAMED_KEYS = /* @__PURE__ */ new Map([
255
421
  ["remote.uploadpack", "git-upload-pack"],
256
422
  ["remote.receivepack", "git-receive-pack"]
257
423
  ]);
258
- var isTrusted = (entry) => TRUSTED_SCOPES.has(entry.scope);
259
424
  var namedKeyClass = (key) => {
260
425
  const first = key.indexOf(".");
261
426
  const last = key.lastIndexOf(".");
@@ -265,11 +430,6 @@ var namedKeyClass = (key) => {
265
430
  return `${key.slice(0, first)}.${key.slice(last + 1)}`;
266
431
  };
267
432
  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
433
  var pinnedOverrides = (entries) => PINNED_GROUPS.flatMap(([keys, neutral]) => {
274
434
  const value = lastTrustedValue(entries, keys) ?? neutral;
275
435
  return keys.map((key) => [key, value]);
@@ -311,25 +471,9 @@ var credentialOverrides = (entries) => {
311
471
  var hardeningOverrides = (entries) => [
312
472
  ...pinnedOverrides(entries),
313
473
  ...repoSetOverrides(entries),
314
- ...credentialOverrides(entries)
474
+ ...credentialOverrides(entries),
475
+ ...hookOverrides(entries)
315
476
  ];
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
477
  var withConfigOverrides = (env, overrides) => {
334
478
  const existing = Number(env["GIT_CONFIG_COUNT"] ?? "0");
335
479
  const start = Number.isInteger(existing) && existing > 0 ? existing : 0;
@@ -391,8 +535,8 @@ var readLinkedWorktree = (args, dir) => Effect_exports.gen(function* () {
391
535
  });
392
536
  var commonDirOf = (args, repoDir) => Effect_exports.gen(function* () {
393
537
  const dotGit = join(repoDir, ".git");
394
- const stat3 = yield* statOf(args, dotGit);
395
- if (stat3.isDirectory()) {
538
+ const stat5 = yield* statOf(args, dotGit);
539
+ if (stat5.isDirectory()) {
396
540
  return yield* realPath(args, dotGit);
397
541
  }
398
542
  const linked = yield* readLinkedWorktree(args, repoDir);
@@ -401,15 +545,15 @@ var commonDirOf = (args, repoDir) => Effect_exports.gen(function* () {
401
545
  var resolveGitDirPins = (cwd, args) => Effect_exports.gen(function* () {
402
546
  const dotGit = join(cwd, ".git");
403
547
  const managed = isManagedWorktree(cwd);
404
- const stat3 = yield* statOf(args, dotGit).pipe(Effect_exports.option);
405
- if (stat3._tag === "None" || stat3.value.isDirectory()) {
548
+ const stat5 = yield* statOf(args, dotGit).pipe(Effect_exports.option);
549
+ if (stat5._tag === "None" || stat5.value.isDirectory()) {
406
550
  if (managed) {
407
551
  return yield* refusal(args, `${dotGit} is not a worktree's .git file`);
408
552
  }
409
553
  const none = {};
410
554
  return none;
411
555
  }
412
- if (!stat3.value.isFile()) {
556
+ if (!stat5.value.isFile()) {
413
557
  return yield* refusal(args, `${dotGit} is not a regular file`);
414
558
  }
415
559
  const dirs = yield* readLinkedWorktree(args, cwd);
@@ -429,6 +573,54 @@ var resolveGitDirPins = (cwd, args) => Effect_exports.gen(function* () {
429
573
  GIT_WORK_TREE: cwd
430
574
  };
431
575
  });
576
+ var INCLUDED_SCOPE = "included";
577
+ var MAX_INCLUDE_DEPTH = 10;
578
+ var isIncludeKey = (key) => key === "include.path" || key.startsWith("includeif.") && key.endsWith(".path");
579
+ var includeTarget = (entry, cwd, env) => {
580
+ const path = entry.value;
581
+ if (path === void 0 || path === "" || !entry.origin.startsWith("file:")) {
582
+ return void 0;
583
+ }
584
+ const including = resolve(cwd, entry.origin.slice("file:".length));
585
+ if (path.startsWith("~/")) {
586
+ const home = env["HOME"];
587
+ return home === void 0 ? void 0 : join(home, path.slice(2));
588
+ }
589
+ if (path.startsWith("~") || path.startsWith("%(prefix)/")) {
590
+ return void 0;
591
+ }
592
+ return isAbsolute(path) ? path : resolve(dirname(including), path);
593
+ };
594
+ var isRegularFile = (path) => Effect_exports.async((resume) => {
595
+ stat$1(path, (error, stats) => {
596
+ resume(Effect_exports.succeed(error === null && stats?.isFile() === true));
597
+ });
598
+ });
599
+ var repoIncludedEntries = (entries, { cwd, env, listFile }) => Effect_exports.gen(function* () {
600
+ const seen = /* @__PURE__ */ new Set();
601
+ const found = [];
602
+ let pending = entries.filter((e) => !isTrusted(e) && isIncludeKey(e.key));
603
+ for (let depth = 0; depth < MAX_INCLUDE_DEPTH && pending.length > 0; depth++) {
604
+ const next = [];
605
+ for (const include of pending) {
606
+ const file = includeTarget(include, cwd, env);
607
+ if (file !== void 0 && !seen.has(file)) {
608
+ seen.add(file);
609
+ if (yield* isRegularFile(file)) {
610
+ const read = parseFileConfigList(
611
+ yield* listFile(file),
612
+ file,
613
+ INCLUDED_SCOPE
614
+ );
615
+ found.push(...read);
616
+ next.push(...read.filter((e) => isIncludeKey(e.key)));
617
+ }
618
+ }
619
+ }
620
+ pending = next;
621
+ }
622
+ return found;
623
+ });
432
624
  var SAFE_PROTOCOLS = "file:git:http:https:ssh";
433
625
  var pathKey = (env) => Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
434
626
  var attempt = (call) => Effect_exports.async((resume) => {
@@ -481,7 +673,7 @@ var isExecutableFile = (p) => Effect_exports.gen(function* () {
481
673
  return false;
482
674
  }
483
675
  const executable = yield* attempt((done) => {
484
- access(p, constants.X_OK, (error) => {
676
+ access$1(p, constants.X_OK, (error) => {
485
677
  done(error, void 0);
486
678
  });
487
679
  });
@@ -559,12 +751,19 @@ var hostGitOutput = (args, cwd, options) => Effect_exports.gen(function* () {
559
751
  });
560
752
  }
561
753
  const git = found.value;
562
- const listed = yield* spawnGit(["config", "--list", "--show-scope", "-z"], {
563
- git,
754
+ const listConfig = (flags) => spawnGit(["config", ...flags, "--list", "-z"], { git, cwd, env }).pipe(
755
+ Effect_exports.map((o) => o.stdout),
756
+ Effect_exports.orElseSucceed(() => "")
757
+ );
758
+ const listed = parseConfigList(
759
+ yield* listConfig(["--show-scope", "--show-origin"])
760
+ );
761
+ const included = yield* repoIncludedEntries(listed, {
564
762
  cwd,
565
- env
566
- }).pipe(Effect_exports.orElseSucceed(() => ({ stdout: "", stderr: "" })));
567
- const overrides = hardeningOverrides(parseConfigList(listed.stdout));
763
+ env,
764
+ listFile: (file) => listConfig(["--file", file, "--no-includes"])
765
+ });
766
+ const overrides = hardeningOverrides([...listed, ...included]);
568
767
  return yield* spawnGit(args, {
569
768
  git,
570
769
  cwd,
@@ -634,6 +833,17 @@ var listWorktrees = (repoDir) => execGit(["worktree", "list", "--porcelain"], re
634
833
  return entries;
635
834
  })
636
835
  );
836
+ var worktreeTimeout = (repoDir, operation, noun) => new WorktreeTimeoutError({
837
+ message: `Worktree ${noun} timed out after ${WORKTREE_TIMEOUT_MS}ms`,
838
+ timeoutMs: WORKTREE_TIMEOUT_MS,
839
+ path: repoDir,
840
+ operation
841
+ });
842
+ var headSha = (worktreePath) => execGit(["rev-parse", "HEAD"], worktreePath).pipe(
843
+ Effect_exports.map((s) => s.trim()),
844
+ Effect_exports.orElseSucceed(() => "")
845
+ );
846
+ var tryUnlockedGit = (args, worktreePath) => Effect_exports.either(execGit([...NO_CONFIG_LOCK_FLAGS, ...args], worktreePath));
637
847
  var fastForwardFromOrigin = (worktreePath, branch) => Effect_exports.gen(function* () {
638
848
  const headRef = yield* execGit(
639
849
  ["symbolic-ref", "--quiet", "HEAD"],
@@ -648,11 +858,9 @@ var fastForwardFromOrigin = (worktreePath, branch) => Effect_exports.gen(functio
648
858
  );
649
859
  return;
650
860
  }
651
- const fetchResult = yield* Effect_exports.either(
652
- execGit(
653
- [...NO_CONFIG_LOCK_FLAGS, "fetch", "origin", branch],
654
- worktreePath
655
- )
861
+ const fetchResult = yield* tryUnlockedGit(
862
+ ["fetch", "origin", branch],
863
+ worktreePath
656
864
  );
657
865
  if (fetchResult._tag === "Left") {
658
866
  yield* Console_exports.log(
@@ -660,15 +868,10 @@ var fastForwardFromOrigin = (worktreePath, branch) => Effect_exports.gen(functio
660
868
  );
661
869
  return;
662
870
  }
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
- )
871
+ const before = yield* headSha(worktreePath);
872
+ const mergeResult = yield* tryUnlockedGit(
873
+ ["merge", "--ff-only", `origin/${branch}`],
874
+ worktreePath
672
875
  );
673
876
  if (mergeResult._tag === "Left") {
674
877
  yield* Console_exports.log(
@@ -676,102 +879,99 @@ var fastForwardFromOrigin = (worktreePath, branch) => Effect_exports.gen(functio
676
879
  );
677
880
  return;
678
881
  }
679
- const after = yield* execGit(["rev-parse", "HEAD"], worktreePath).pipe(
680
- Effect_exports.map((s) => s.trim()),
681
- Effect_exports.orElseSucceed(() => "")
682
- );
882
+ const after = yield* headSha(worktreePath);
683
883
  yield* Console_exports.log(
684
884
  before && after && before !== after ? `Fast-forwarded worktree at ${worktreePath} (branch '${branch}') to origin/${branch}` : `Reusing existing worktree at ${worktreePath} (branch '${branch}')`
685
885
  );
686
886
  });
887
+ var reuseCollidingWorktree = (collision, branch, worktreesDir) => Effect_exports.gen(function* () {
888
+ if (isManagedWorktreePath(collision.path, worktreesDir)) {
889
+ const dirty = yield* hasUncommittedChanges(collision.path);
890
+ yield* dirty ? Console_exports.warn(
891
+ `Reusing worktree at ${collision.path} (branch '${branch}') \u2014 worktree has uncommitted changes`
892
+ ) : fastForwardFromOrigin(collision.path, branch);
893
+ return { path: normalize(collision.path), branch };
894
+ }
895
+ return yield* new WorktreeError({
896
+ message: `Branch '${branch}' is already checked out in worktree at '${collision.path}'. Sandcastle's branch and merge-to-head strategies run the agent in a git worktree under .sandcastle/worktrees/, and git refuses to check out the same branch in two worktrees at once (HEAD would become ambiguous). Pick a different branch, or switch the main working tree to a different branch before re-running.`
897
+ });
898
+ });
899
+ var addBranchWorktree = (repoDir, worktreePath, target) => execGit(
900
+ [...NO_CONFIG_LOCK_FLAGS, "worktree", "add", worktreePath, target.branch],
901
+ repoDir
902
+ ).pipe(
903
+ Effect_exports.catchAll((e) => {
904
+ if (e.message.includes("invalid reference")) {
905
+ return execGit(
906
+ [
907
+ ...NO_CONFIG_LOCK_FLAGS,
908
+ "worktree",
909
+ "add",
910
+ "-b",
911
+ target.branch,
912
+ worktreePath,
913
+ target.baseBranch ?? "HEAD"
914
+ ],
915
+ repoDir
916
+ );
917
+ }
918
+ return Effect_exports.fail(e);
919
+ })
920
+ );
921
+ var addOrReuseBranchWorktree = (repoDir, worktreePath, target) => Effect_exports.gen(function* () {
922
+ const { branch, worktreesDir } = target;
923
+ const existing = yield* listWorktrees(repoDir);
924
+ const collision = findCollidingWorktree(existing, branch, worktreePath);
925
+ if (collision) {
926
+ return yield* reuseCollidingWorktree(collision, branch, worktreesDir);
927
+ }
928
+ yield* addBranchWorktree(repoDir, worktreePath, target);
929
+ return { path: worktreePath, branch };
930
+ });
931
+ var addTempBranchWorktree = (repoDir, worktreePath, branch) => execGit(
932
+ [
933
+ ...NO_CONFIG_LOCK_FLAGS,
934
+ "worktree",
935
+ "add",
936
+ "-b",
937
+ branch,
938
+ worktreePath,
939
+ "HEAD"
940
+ ],
941
+ repoDir
942
+ ).pipe(
943
+ Effect_exports.catchAll((e) => {
944
+ if (e.message.includes("already checked out") || e.message.includes("already exists")) {
945
+ return Effect_exports.fail(
946
+ new WorktreeError({
947
+ message: `Branch '${branch}' is already checked out in another worktree. Use a different branch name, or wait for the other run to finish.`
948
+ })
949
+ );
950
+ }
951
+ return Effect_exports.fail(e);
952
+ })
953
+ );
687
954
  var create = (repoDir, opts) => Effect_exports.gen(function* () {
688
955
  const fs = yield* FileSystem_exports.FileSystem;
689
956
  const worktreesDir = join(repoDir, ".sandcastle", "worktrees");
690
957
  yield* fs.makeDirectory(worktreesDir, { recursive: true }).pipe(Effect_exports.mapError((e) => new WorktreeError({ message: e.message })));
691
- let branch;
692
- let worktreeName;
693
958
  const explicitBranch = opts?.branch;
694
959
  const hasExplicitBranch = explicitBranch !== void 0 && explicitBranch !== "";
960
+ const branch = hasExplicitBranch ? explicitBranch : opts?.tempBranch ?? generateTempBranchName(opts?.name);
961
+ const worktreePath = join(worktreesDir, branch.replaceAll("/", "-"));
695
962
  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
- );
963
+ return yield* addOrReuseBranchWorktree(repoDir, worktreePath, {
964
+ branch,
965
+ baseBranch: opts?.baseBranch,
966
+ worktreesDir
967
+ });
764
968
  }
969
+ yield* addTempBranchWorktree(repoDir, worktreePath, branch);
765
970
  return { path: worktreePath, branch };
766
971
  }).pipe(
767
972
  withTimeout(
768
973
  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
- })
974
+ () => worktreeTimeout(repoDir, "create", "creation")
775
975
  )
776
976
  );
777
977
  var hasUncommittedChanges = (worktreePath) => execGit(["status", "--porcelain"], worktreePath).pipe(
@@ -814,28 +1014,37 @@ var deleteTempBranchIfUnused = (repoDir, branch) => Effect_exports.gen(function*
814
1014
  yield* execGit(["branch", "-D", branch], repoDir);
815
1015
  return { unmergedCommits: 0 };
816
1016
  });
1017
+ var readEntriesIfPresent = (fs, dir) => fs.readDirectory(dir).pipe(
1018
+ Effect_exports.map((es) => es),
1019
+ Effect_exports.catchSome(
1020
+ (e) => e._tag === "SystemError" && e.reason === "NotFound" ? Option_exports.some(Effect_exports.succeed(null)) : Option_exports.none()
1021
+ ),
1022
+ Effect_exports.mapError((e) => new WorktreeError({ message: e.message }))
1023
+ );
1024
+ var listActiveWorktreePaths = (repoDir) => execGit(["worktree", "list", "--porcelain"], repoDir).pipe(
1025
+ Effect_exports.map(
1026
+ (worktreeList) => new Set(
1027
+ worktreeList.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length).trim())
1028
+ )
1029
+ )
1030
+ );
1031
+ var removeDir = (fs, dir) => fs.remove(dir, { recursive: true, force: true }).pipe(
1032
+ Effect_exports.mapError(
1033
+ (e) => new WorktreeError({
1034
+ message: `Failed to remove ${dir}: ${e.message}`
1035
+ })
1036
+ )
1037
+ );
817
1038
  var pruneStale = (repoDir) => Effect_exports.gen(function* () {
818
1039
  const fs = yield* FileSystem_exports.FileSystem;
819
1040
  yield* execGit(["worktree", "prune"], repoDir);
820
1041
  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
- );
1042
+ const entries = yield* readEntriesIfPresent(fs, worktreesDir);
828
1043
  if (entries === null) {
829
1044
  return;
830
1045
  }
831
1046
  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
- );
1047
+ const activeWorktreePaths = yield* listActiveWorktreePaths(repoDir);
839
1048
  for (const entry of entries) {
840
1049
  const entryPath = join(realWorktreesDir, entry);
841
1050
  const isDir = yield* fs.stat(entryPath).pipe(
@@ -843,90 +1052,80 @@ var pruneStale = (repoDir) => Effect_exports.gen(function* () {
843
1052
  Effect_exports.catchAll(() => Effect_exports.succeed(false))
844
1053
  );
845
1054
  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
- );
1055
+ yield* removeDir(fs, entryPath);
853
1056
  }
854
1057
  }
855
1058
  }).pipe(
856
1059
  withTimeout(
857
1060
  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
- })
1061
+ () => worktreeTimeout(repoDir, "prune", "prune")
864
1062
  )
865
1063
  );
866
1064
  var COPY_TO_WORKTREE_TIMEOUT_MS = 6e4;
867
1065
  var getCopyOnWriteFlags = (platform) => platform === "darwin" ? ["-cR"] : ["-R", "--reflink=auto"];
1066
+ var createDir = (dir, relativePath) => Effect_exports.tryPromise({
1067
+ try: () => mkdir(dir, { recursive: true }),
1068
+ catch: (e) => {
1069
+ const message = e instanceof Error ? e.message : String(e);
1070
+ return new CopyToWorktreeError({
1071
+ message: `Failed to copy ${relativePath} to worktree: ${message}`,
1072
+ path: relativePath,
1073
+ stderr: message,
1074
+ exitCode: null
1075
+ });
1076
+ }
1077
+ });
1078
+ var copyFailed = (relativePath, error, stderr) => new CopyToWorktreeError({
1079
+ message: `Failed to copy ${relativePath} to worktree: ${stderr || error.message}`,
1080
+ path: relativePath,
1081
+ stderr: stderr || error.message,
1082
+ exitCode: typeof error.code === "number" ? error.code : null
1083
+ });
1084
+ var copyPath = (copy) => Effect_exports.async((resume) => {
1085
+ const { cowFlags, cpSrc, dest, relativePath } = copy;
1086
+ let child;
1087
+ let interrupted = false;
1088
+ child = execFile("cp", [...cowFlags, cpSrc, dest], (error) => {
1089
+ if (interrupted) {
1090
+ return;
1091
+ }
1092
+ if (!error) {
1093
+ resume(Effect_exports.void);
1094
+ return;
1095
+ }
1096
+ child = execFile(
1097
+ "cp",
1098
+ ["-R", cpSrc, dest],
1099
+ (fallbackError, _, stderr) => {
1100
+ resume(
1101
+ fallbackError ? Effect_exports.fail(copyFailed(relativePath, fallbackError, stderr)) : Effect_exports.void
1102
+ );
1103
+ }
1104
+ );
1105
+ });
1106
+ return Effect_exports.sync(() => {
1107
+ interrupted = true;
1108
+ child.kill("SIGKILL");
1109
+ });
1110
+ });
868
1111
  var copyToWorktree = (paths, hostRepoDir, worktreePath, timeoutMs) => {
869
1112
  const effectiveTimeout = timeoutMs ?? COPY_TO_WORKTREE_TIMEOUT_MS;
870
1113
  return Effect_exports.gen(function* () {
871
1114
  const cowFlags = getCopyOnWriteFlags(process.platform);
872
1115
  for (const relativePath of paths) {
873
1116
  const src = join(hostRepoDir, relativePath);
874
- if (!existsSync(src)) {
1117
+ const srcStats = yield* Effect_exports.promise(
1118
+ () => stat(src).catch(() => void 0)
1119
+ );
1120
+ if (srcStats === void 0) {
875
1121
  continue;
876
1122
  }
877
1123
  const dest = join(worktreePath, relativePath);
878
- const isDirectory = statSync(src).isDirectory();
1124
+ const isDirectory = srcStats.isDirectory();
879
1125
  const dirToCreate = isDirectory ? dest : dirname(dest);
880
1126
  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
- });
1127
+ yield* createDir(dirToCreate, relativePath);
1128
+ yield* copyPath({ cowFlags, cpSrc, dest, relativePath });
930
1129
  }
931
1130
  }).pipe(
932
1131
  withTimeout(
@@ -1176,102 +1375,8 @@ var runOnSandboxReadyHooks = (hooks) => Effect_exports.gen(function* () {
1176
1375
  (hook) => runHostHook(hook, hooks.hostWorktreePath, hooks.signal)
1177
1376
  )
1178
1377
  ];
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
- }
1378
+ const runAll = all.length > 0 ? Effect_exports.all(all, { concurrency: "unbounded" }) : Effect_exports.void;
1379
+ yield* runAll.pipe(Effect_exports.ensuring(Effect_exports.sync(() => cleanup?.())));
1275
1380
  });
1276
1381
 
1277
1382
  // src/RecoveryMessage.ts
@@ -1648,17 +1753,16 @@ var resolveHostDestination = (realRoot, relPath) => Effect_exports.gen(function*
1648
1753
  });
1649
1754
  var checkStagedFile = (staged, relPath) => lstatOf(staged).pipe(
1650
1755
  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"))
1756
+ (stat5) => Option_exports.isSome(stat5) && stat5.value.isFile() ? Effect_exports.void : Effect_exports.fail(refusal2(relPath, "it is not a regular file"))
1652
1757
  )
1653
1758
  );
1654
1759
  var hostSymlinkAt = (realRoot) => (relPath) => Effect_exports.gen(function* () {
1655
1760
  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();
1761
+ const stat5 = yield* lstatOf(p);
1762
+ return Option_exports.isSome(stat5) && stat5.value.isSymbolicLink() ? yield* readLinkOf(p) : Option_exports.none();
1658
1763
  });
1659
1764
 
1660
- // src/syncOut.ts
1661
- var SYNC_BASE_REF = "refs/sandcastle/sync-base";
1765
+ // src/syncOutExec.ts
1662
1766
  var execHostGit = (args, cwd) => hostGit(args, cwd).pipe(
1663
1767
  Effect_exports.mapError(
1664
1768
  (e) => new SyncError({
@@ -1690,64 +1794,9 @@ var execSandbox = (handle, command, options) => Effect_exports.tryPromise({
1690
1794
  ${e instanceof Error ? e.message : String(e)}`
1691
1795
  })
1692
1796
  });
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
- );
1797
+
1798
+ // src/syncOutInspect.ts
1799
+ var SYNC_BASE_REF = "refs/sandcastle/sync-base";
1751
1800
  var countCommitsToSync = (sandbox, cwd, hostHead) => Effect_exports.gen(function* () {
1752
1801
  const baseResult = yield* sandbox.exec(`git rev-parse --verify --quiet ${SYNC_BASE_REF}`, { cwd }).pipe(
1753
1802
  Effect_exports.catchAll(
@@ -1771,8 +1820,8 @@ var countCommitsToSync = (sandbox, cwd, hostHead) => Effect_exports.gen(function
1771
1820
  if (countResult.exitCode !== 0) {
1772
1821
  return 0;
1773
1822
  }
1774
- const parsed = Number.parseInt(countResult.stdout.trim(), 10);
1775
- return Number.isNaN(parsed) ? 0 : parsed;
1823
+ const parsed = Number(countResult.stdout.trim());
1824
+ return Number.isInteger(parsed) ? parsed : 0;
1776
1825
  });
1777
1826
  var readSyncBase = (handle, hostHead) => execSandbox(handle, `git rev-parse --verify --quiet ${SYNC_BASE_REF}`, {
1778
1827
  cwd: handle.worktreePath
@@ -1811,6 +1860,48 @@ var inspectSandbox = (hostRepoDir, handle) => Effect_exports.gen(function* () {
1811
1860
  untrackedFiles
1812
1861
  };
1813
1862
  });
1863
+ var isEmptyPatch = (patchPath) => Effect_exports.tryPromise({
1864
+ try: async () => {
1865
+ const info = await stat(patchPath);
1866
+ if (info.size === 0) {
1867
+ return true;
1868
+ }
1869
+ const content = await readFile$1(patchPath, "utf8");
1870
+ return !content.includes("diff --git");
1871
+ },
1872
+ catch: (e) => new SyncError({
1873
+ message: `Failed to check patch ${patchPath}: ${e instanceof Error ? e.message : String(e)}`
1874
+ })
1875
+ });
1876
+ var pad2 = (n) => String(n).padStart(2, "0");
1877
+ var createPatchDir = (hostRepoDir) => DateTime_exports.now.pipe(
1878
+ // Local time, as the directory name has always used.
1879
+ Effect_exports.map(
1880
+ (now) => DateTime_exports.toParts(DateTime_exports.setZone(now, DateTime_exports.zoneMakeLocal()))
1881
+ ),
1882
+ Effect_exports.flatMap(
1883
+ (now) => Effect_exports.tryPromise({
1884
+ try: async () => {
1885
+ const base = `${now.year}${pad2(now.month)}${pad2(now.day)}-${pad2(now.hours)}${pad2(now.minutes)}${pad2(now.seconds)}`;
1886
+ const patchesRoot = join(hostRepoDir, ".sandcastle", "patches");
1887
+ await mkdir(patchesRoot, { recursive: true });
1888
+ const taken = new Set(await readdir(patchesRoot));
1889
+ let dirName = base;
1890
+ let counter = 0;
1891
+ while (taken.has(dirName)) {
1892
+ counter++;
1893
+ dirName = `${base}-${counter}`;
1894
+ }
1895
+ const patchDir = join(patchesRoot, dirName);
1896
+ await mkdir(patchDir, { recursive: true });
1897
+ return patchDir;
1898
+ },
1899
+ catch: (e) => new SyncError({
1900
+ message: `Failed to create patch directory: ${e instanceof Error ? e.message : String(e)}`
1901
+ })
1902
+ })
1903
+ )
1904
+ );
1814
1905
  var diffPathOf = (run) => join(run.patchDir, "changes.patch");
1815
1906
  var stagedUntrackedPath = (run, i) => join(run.untrackedDir, ...run.untrackedSegments[i] ?? []);
1816
1907
  var saveCommitPatches = (run) => Effect_exports.gen(function* () {
@@ -1869,13 +1960,48 @@ var saveUntracked = (run) => Effect_exports.gen(function* () {
1869
1960
  });
1870
1961
  }
1871
1962
  });
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
- );
1963
+ var checkUntrackedDestinations = (run) => Effect_exports.all(
1964
+ run.changes.untrackedFiles.map(
1965
+ (relPath, i) => checkStagedFile(stagedUntrackedPath(run, i), relPath).pipe(
1966
+ Effect_exports.andThen(() => resolveHostDestination(run.realRoot, relPath))
1967
+ )
1968
+ )
1969
+ );
1970
+ var saveAndCheck = (run) => Effect_exports.gen(function* () {
1971
+ const { changes } = run;
1972
+ const nonEmptyPatches = changes.hasCommits ? yield* saveCommitPatches(run) : [];
1973
+ if (changes.hasDiff) {
1974
+ yield* saveDiff(run);
1975
+ }
1976
+ if (changes.hasUntracked) {
1977
+ yield* saveUntracked(run);
1978
+ }
1979
+ yield* checkUntrackedDestinations(run);
1980
+ yield* checkPatchFileSymlinks(
1981
+ [...nonEmptyPatches, ...changes.hasDiff ? [diffPathOf(run)] : []],
1982
+ hostSymlinkAt(run.realRoot)
1983
+ );
1984
+ return nonEmptyPatches;
1985
+ });
1986
+
1987
+ // src/syncOut.ts
1988
+ var removePatchDir = (hostRepoDir, patchDir) => Effect_exports.tryPromise({
1989
+ try: async () => {
1990
+ await rm(patchDir, { recursive: true, force: true });
1991
+ const patchesRoot = join(hostRepoDir, ".sandcastle", "patches");
1992
+ try {
1993
+ const remaining = await readdir(patchesRoot);
1994
+ if (remaining.length === 0) {
1995
+ await rm(patchesRoot, {
1996
+ recursive: true,
1997
+ force: true
1998
+ });
1999
+ }
2000
+ } catch {
2001
+ }
2002
+ },
2003
+ catch: () => new SyncError({ message: "Failed to clean up patch directory" })
2004
+ });
1879
2005
  var copyUntrackedToHost = (run, destinations) => Effect_exports.tryPromise({
1880
2006
  try: async () => {
1881
2007
  for (const [i, destPath] of destinations.entries()) {
@@ -1934,22 +2060,6 @@ ${msg}`);
1934
2060
  yield* removePatchDir(run.hostRepoDir, run.patchDir);
1935
2061
  }
1936
2062
  });
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
2063
  var syncOut = (hostRepoDir, handle) => {
1954
2064
  let createdPatchDir;
1955
2065
  return Effect_exports.gen(function* () {
@@ -1984,6 +2094,101 @@ var syncOut = (hostRepoDir, handle) => {
1984
2094
  );
1985
2095
  };
1986
2096
 
2097
+ // src/lifecycleHostGit.ts
2098
+ var readHostCurrentBranch = (options) => options.branch !== void 0 && options.branch !== "" ? Effect_exports.succeed(null) : hostGit(["rev-parse", "--abbrev-ref", "HEAD"], options.hostRepoDir).pipe(
2099
+ Effect_exports.map((stdout) => stdout.trim()),
2100
+ Effect_exports.orDie
2101
+ );
2102
+ var readHostIdentity = (hostRepoDir) => {
2103
+ const readIdentity = (key) => hostGit(["config", key], hostRepoDir).pipe(
2104
+ Effect_exports.map((stdout) => stdout.trim()),
2105
+ Effect_exports.orElseSucceed(() => "")
2106
+ );
2107
+ return Effect_exports.all([readIdentity("user.name"), readIdentity("user.email")], {
2108
+ concurrency: "unbounded"
2109
+ }).pipe(Effect_exports.map(([name, email]) => ({ name, email })));
2110
+ };
2111
+ var collectCommits = (range, hostRepoDir) => hostGit(["rev-list", ...range, "--reverse"], hostRepoDir).pipe(
2112
+ Effect_exports.map((stdout) => {
2113
+ const lines = stdout.trim();
2114
+ return lines === "" ? [] : lines.split("\n").map((sha) => ({ sha }));
2115
+ }),
2116
+ Effect_exports.orElseSucceed(() => [])
2117
+ );
2118
+ var mergeToHost = (sourceBranch, targetBranch, hostRepoDir) => (
2119
+ // `--`: the branch name comes from the sandbox.
2120
+ hostGit(["merge", "--", sourceBranch], hostRepoDir).pipe(
2121
+ Effect_exports.asVoid,
2122
+ Effect_exports.catchAll(
2123
+ (e) => Effect_exports.gen(function* () {
2124
+ const gitOutput = [e.stdout, e.stderr].map((s) => s.trim()).filter((s) => s !== "").join("\n");
2125
+ const mergeStarted = yield* hostGit(
2126
+ ["rev-parse", "-q", "--verify", "MERGE_HEAD"],
2127
+ hostRepoDir
2128
+ ).pipe(
2129
+ Effect_exports.as(true),
2130
+ Effect_exports.orElseSucceed(() => false)
2131
+ );
2132
+ if (mergeStarted) {
2133
+ yield* hostGit(["merge", "--abort"], hostRepoDir).pipe(Effect_exports.ignore);
2134
+ }
2135
+ return yield* new SyncError({
2136
+ message: `Merge of '${sourceBranch}' onto '${targetBranch}' failed${mergeStarted ? " and was aborted" : ""}, so '${targetBranch}' is unchanged.${gitOutput === "" ? " " : `
2137
+ git merge said:
2138
+ ${gitOutput}
2139
+ `}The temporary branch '${sourceBranch}' has been preserved. To retry: git merge ${sourceBranch} (resolve any conflicts and commit), then clean up: git branch -D ${sourceBranch}`
2140
+ });
2141
+ })
2142
+ )
2143
+ )
2144
+ );
2145
+ var collectCommitsLogged = (range, hostRepoDir, timeoutMs) => Effect_exports.gen(function* () {
2146
+ const display = yield* Display;
2147
+ return yield* display.taskLog(
2148
+ "Collecting commits",
2149
+ () => collectCommits([range], hostRepoDir).pipe(
2150
+ withTimeout(
2151
+ timeoutMs,
2152
+ () => new CommitCollectionTimeoutError({
2153
+ message: `Commit collection timed out after ${timeoutMs}ms`,
2154
+ timeoutMs
2155
+ })
2156
+ )
2157
+ )
2158
+ );
2159
+ });
2160
+ var mergeToHostWithTimeout = (merge) => mergeToHost(merge.tempBranch, merge.hostBranch, merge.hostRepoDir).pipe(
2161
+ withTimeout(
2162
+ merge.mergeToHostTimeoutMs,
2163
+ () => new MergeToHostTimeoutError({
2164
+ message: `Merge of '${merge.tempBranch}' to '${merge.hostBranch}' timed out after ${merge.mergeToHostTimeoutMs}ms`,
2165
+ timeoutMs: merge.mergeToHostTimeoutMs,
2166
+ sourceBranch: merge.tempBranch,
2167
+ targetBranch: merge.hostBranch
2168
+ })
2169
+ )
2170
+ );
2171
+ var mergeTempBranch = (merge) => Effect_exports.gen(function* () {
2172
+ const display = yield* Display;
2173
+ if (!merge.keepSourceBranch) {
2174
+ yield* execOk(merge.sandbox, "git checkout --detach", {
2175
+ cwd: merge.sandboxRepoDir
2176
+ });
2177
+ }
2178
+ if (merge.hasNewCommits) {
2179
+ yield* display.taskLog(
2180
+ `Merging to ${merge.hostBranch}`,
2181
+ () => mergeToHostWithTimeout(merge)
2182
+ );
2183
+ }
2184
+ if (!merge.keepSourceBranch) {
2185
+ yield* hostGit(
2186
+ ["branch", "-D", "--", merge.tempBranch],
2187
+ merge.hostRepoDir
2188
+ ).pipe(Effect_exports.ignore);
2189
+ }
2190
+ });
2191
+
1987
2192
  // src/SandboxLifecycle.ts
1988
2193
  var GIT_SETUP_TIMEOUT_MS = 1e4;
1989
2194
  var COMMIT_COLLECTION_TIMEOUT_MS = 3e4;
@@ -2058,7 +2263,7 @@ var mergeBack = (run, branches) => Effect_exports.gen(function* () {
2058
2263
  ["rev-list", `${baseHead}..HEAD`, "--count"],
2059
2264
  run.hostSideWorktreePath
2060
2265
  ).pipe(
2061
- Effect_exports.map((stdout) => Number.parseInt(stdout.trim(), 10) > 0),
2266
+ Effect_exports.map((stdout) => Number(stdout.trim()) > 0),
2062
2267
  Effect_exports.orElseSucceed(() => false)
2063
2268
  );
2064
2269
  yield* mergeTempBranch({
@@ -2203,7 +2408,7 @@ var syncIn = (hostRepoDir, handle) => Effect_exports.gen(function* () {
2203
2408
  branch
2204
2409
  }),
2205
2410
  // Clean up host-side bundle temp dir (runs regardless of success/failure)
2206
- Effect_exports.promise(() => rm$1(bundleDir, { recursive: true, force: true }))
2411
+ Effect_exports.promise(() => rm(bundleDir, { recursive: true, force: true }))
2207
2412
  );
2208
2413
  return { branch };
2209
2414
  });
@@ -2222,7 +2427,6 @@ var createClosingIfAbandoned = (create2, onError) => Effect_exports.suspend(() =
2222
2427
  )
2223
2428
  );
2224
2429
  });
2225
- var GITDIR_LINE2 = /^gitdir: (?<path>.+)$/u;
2226
2430
  var attempt3 = (call) => Effect_exports.async((resume) => {
2227
2431
  call((error, value) => {
2228
2432
  resume(
@@ -2242,15 +2446,54 @@ var statOf2 = (p) => attempt3((done) => {
2242
2446
  var ensureDir = (p) => attempt3((done) => {
2243
2447
  mkdir$1(p, { recursive: true }, done);
2244
2448
  });
2449
+ var listDir = (p) => attempt3((done) => {
2450
+ readdir$1(p, done);
2451
+ });
2452
+ var ensureFile = (p) => attempt3((done) => {
2453
+ writeFile$1(p, "", { flag: "wx" }, (error) => {
2454
+ done(error, void 0);
2455
+ });
2456
+ });
2457
+
2458
+ // src/protectGitMounts.ts
2459
+ var GITDIR_LINE2 = /^gitdir: (?<path>.+)$/u;
2245
2460
  var toMountPath = (p) => process.platform === "win32" ? p.replaceAll("\\", "/") : p;
2246
2461
  var relativeWithin = (child, parent) => {
2247
2462
  const rel = relative(parent, child);
2248
2463
  return rel.startsWith("..") || isAbsolute(rel) ? Option_exports.none() : Option_exports.some(rel);
2249
2464
  };
2465
+ var worktreeConfigIn = (dir) => Effect_exports.gen(function* () {
2466
+ yield* ensureFile(join(dir, "config.worktree"));
2467
+ const real = yield* realPath2(join(dir, "config.worktree"));
2468
+ if (Option_exports.isNone(real)) {
2469
+ return [];
2470
+ }
2471
+ const stat5 = yield* statOf2(real.value);
2472
+ return Option_exports.isSome(stat5) && stat5.value.isFile() ? [real.value] : [];
2473
+ });
2474
+ var adminDirsOf = (commonDir) => Effect_exports.gen(function* () {
2475
+ const worktrees = join(commonDir, "worktrees");
2476
+ const names = yield* listDir(worktrees);
2477
+ const dirs = [];
2478
+ for (const name of Option_exports.getOrElse(names, () => [])) {
2479
+ const stat5 = yield* statOf2(join(worktrees, name));
2480
+ if (Option_exports.isSome(stat5) && stat5.value.isDirectory()) {
2481
+ dirs.push(join(worktrees, name));
2482
+ }
2483
+ }
2484
+ return dirs;
2485
+ });
2250
2486
  var commonDirControlPaths = (commonDir) => Effect_exports.gen(function* () {
2251
2487
  yield* ensureDir(join(commonDir, "hooks"));
2252
2488
  yield* ensureDir(join(commonDir, "info"));
2253
- return ["config", "hooks", "info"].map((name) => join(commonDir, name));
2489
+ const worktreeConfigs = yield* worktreeConfigIn(commonDir);
2490
+ for (const adminDir of yield* adminDirsOf(commonDir)) {
2491
+ worktreeConfigs.push(...yield* worktreeConfigIn(adminDir));
2492
+ }
2493
+ return [
2494
+ ...["config", "hooks", "info"].map((name) => join(commonDir, name)),
2495
+ ...worktreeConfigs
2496
+ ];
2254
2497
  });
2255
2498
  var linkedWorktreeControlPaths = (dir, gitdir) => Effect_exports.gen(function* () {
2256
2499
  const dotGit = yield* realPath2(join(dir, ".git"));
@@ -2274,11 +2517,11 @@ var linkedWorktreeControlPaths = (dir, gitdir) => Effect_exports.gen(function* (
2274
2517
  });
2275
2518
  var controlPathsOf = (dir) => Effect_exports.gen(function* () {
2276
2519
  const dotGit = join(dir, ".git");
2277
- const stat3 = yield* statOf2(dotGit);
2278
- if (Option_exports.isNone(stat3)) {
2520
+ const stat5 = yield* statOf2(dotGit);
2521
+ if (Option_exports.isNone(stat5)) {
2279
2522
  return [];
2280
2523
  }
2281
- if (stat3.value.isDirectory()) {
2524
+ if (stat5.value.isDirectory()) {
2282
2525
  const real = yield* realPath2(dotGit);
2283
2526
  return Option_exports.isSome(real) ? yield* commonDirControlPaths(real.value) : [];
2284
2527
  }
@@ -2391,7 +2634,10 @@ var startBindMountSandbox = (options) => {
2391
2634
  ...options.gitMounts
2392
2635
  ];
2393
2636
  return protectGitControlFiles(
2394
- normalizeMounts(rawMounts, worktreeOrRepoPath, SANDBOX_REPO_DIR),
2637
+ normalizeMounts(rawMounts, {
2638
+ worktreeHostPath: worktreeOrRepoPath,
2639
+ sandboxRepoDir: SANDBOX_REPO_DIR
2640
+ }),
2395
2641
  worktreeOrRepoPath
2396
2642
  ).pipe(
2397
2643
  Effect_exports.flatMap(
@@ -2420,7 +2666,13 @@ var startBindMountSandbox = (options) => {
2420
2666
  var copyPathsIn = (handle, paths, sourceDir) => Effect_exports.gen(function* () {
2421
2667
  for (const relativePath of paths) {
2422
2668
  const hostPath = join(sourceDir, relativePath);
2423
- if (!existsSync(hostPath)) {
2669
+ const exists = yield* Effect_exports.promise(
2670
+ () => access(hostPath).then(
2671
+ () => true,
2672
+ () => false
2673
+ )
2674
+ );
2675
+ if (!exists) {
2424
2676
  continue;
2425
2677
  }
2426
2678
  const sandboxPath = posix.join(handle.worktreePath, relativePath);
@@ -2476,52 +2728,6 @@ var startIsolatedSandbox = (options) => Effect_exports.gen(function* () {
2476
2728
  );
2477
2729
  return toResult(handle);
2478
2730
  });
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
2731
  var SandboxFactory = class extends Context_exports.Tag(
2526
2732
  "@ai-hero/sandcastle/SandboxFactory"
2527
2733
  )() {
@@ -2559,7 +2765,8 @@ Temporary branch '${tempBranch}' kept: it has ${unmergedCommits} commit${s} not
2559
2765
  Effect_exports.asVoid,
2560
2766
  Effect_exports.catchAll(() => Effect_exports.void)
2561
2767
  );
2562
- var cleanupWorktree = (worktreePath, exit, signal, temp) => {
2768
+ var cleanupWorktree = (worktreePath, exit, options) => {
2769
+ const { signal, temp } = options;
2563
2770
  if (!Exit_exports.isSuccess(exit) && signal?.aborted === true) {
2564
2771
  printWorktreePreservedMessage(
2565
2772
  worktreePath,
@@ -2609,8 +2816,8 @@ var attachPreservedPath = (path, e) => {
2609
2816
  };
2610
2817
  var resolveGitMounts = (gitPath) => Effect_exports.gen(function* () {
2611
2818
  const fs = yield* FileSystem_exports.FileSystem;
2612
- const stat3 = yield* fs.stat(gitPath);
2613
- if (stat3.type === "Directory") {
2819
+ const stat5 = yield* fs.stat(gitPath);
2820
+ if (stat5.type === "Directory") {
2614
2821
  return [{ hostPath: gitPath, sandboxPath: gitPath }];
2615
2822
  }
2616
2823
  const content = (yield* fs.readFileString(gitPath)).trim();
@@ -2671,14 +2878,38 @@ var WorktreeDockerSandboxFactory = {
2671
2878
  })
2672
2879
  }))
2673
2880
  );
2881
+ const prepareWorktree = (worktreePath) => (copyPaths && copyPaths.length > 0 ? display.spinner(
2882
+ "Copying to worktree",
2883
+ copyToWorktree(
2884
+ copyPaths,
2885
+ hostRepoDir,
2886
+ worktreePath,
2887
+ timeouts?.copyToWorktreeMs
2888
+ )
2889
+ ) : Effect_exports.void).pipe(
2890
+ Effect_exports.andThen(
2891
+ onWorktreeReady.length > 0 ? runHostHooks(onWorktreeReady, worktreePath, signal) : Effect_exports.void
2892
+ ),
2893
+ Effect_exports.andThen(
2894
+ resolveGitMounts(join(hostRepoDir, ".git")).pipe(
2895
+ Effect_exports.provideService(FileSystem_exports.FileSystem, fileSystem),
2896
+ Effect_exports.mapError(
2897
+ (e) => new WorktreeError({
2898
+ message: `Failed to resolve git mounts: ${String(e)}`
2899
+ })
2900
+ )
2901
+ )
2902
+ ),
2903
+ Effect_exports.flatMap(
2904
+ (gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
2905
+ )
2906
+ );
2674
2907
  const releaseWorktree = (worktreeInfo, exit) => Effect_exports.sync(worktreeInfo.unregisterShutdown).pipe(
2675
2908
  Effect_exports.andThen(
2676
- cleanupWorktree(
2677
- worktreeInfo.path,
2678
- exit,
2909
+ cleanupWorktree(worktreeInfo.path, exit, {
2679
2910
  signal,
2680
- tempBranchOf(worktreeInfo)
2681
- )
2911
+ temp: tempBranchOf(worktreeInfo)
2912
+ })
2682
2913
  )
2683
2914
  );
2684
2915
  return {
@@ -2874,36 +3105,7 @@ var WorktreeDockerSandboxFactory = {
2874
3105
  pruneAndCreate(),
2875
3106
  // Use: copy files, run host hooks, resolve+patch git mounts, then start
2876
3107
  // 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
- ),
3108
+ (worktreeInfo) => prepareWorktree(worktreeInfo.path).pipe(
2907
3109
  Effect_exports.flatMap(
2908
3110
  (gitMounts) => Effect_exports.acquireUseRelease(
2909
3111
  // sandboxProvider is guaranteed bind-mount here
@@ -2954,219 +3156,6 @@ var WorktreeDockerSandboxFactory = {
2954
3156
  )
2955
3157
  };
2956
3158
 
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
3159
+ export { ClackDisplay, Display, FileDisplay, SandboxConfig, SandboxFactory, SilentDisplay, WorktreeDockerSandboxFactory, copyToWorktree, create, deleteTempBranchIfUnused, execOk, formatErrorMessage, generateTempBranchName, getCurrentBranch, hasUncommittedChanges, pruneStale, remove, resolveGitMounts, reuseSandboxFactoryLayer, runHostHooks, startBindMountSandbox, startIsolatedSandbox, startSandbox, syncOut, withFriendlyErrors, withSandboxLifecycle };
3160
+ //# sourceMappingURL=chunk-EM4QNWKF.js.map
3161
+ //# sourceMappingURL=chunk-EM4QNWKF.js.map