glimmervoid 0.49.1-next.545 → 0.49.1-next.546

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 (83) hide show
  1. package/dist/chunks/{main-kngM7nsP.js → main-IZFxqy9o.js} +1595 -1514
  2. package/dist/client/assets/{benchmark-panel-CZoHN_0Z.js → benchmark-panel-Dn4xSZmQ.js} +1 -1
  3. package/dist/client/assets/benchmark-panel-Dn4xSZmQ.js.br +0 -0
  4. package/dist/client/assets/{boards-view-0hW6lkva.js → boards-view-CMjU7fKn.js} +1 -1
  5. package/dist/client/assets/boards-view-CMjU7fKn.js.br +0 -0
  6. package/dist/client/assets/{community-panel-CmSsVWBy.js → community-panel-DAH-96Wg.js} +1 -1
  7. package/dist/client/assets/community-panel-DAH-96Wg.js.br +0 -0
  8. package/dist/client/assets/{dialogs-C1JgVkCl.js → dialogs-DZfxUaBe.js} +1 -1
  9. package/dist/client/assets/dialogs-DZfxUaBe.js.br +0 -0
  10. package/dist/client/assets/{doc-editor-ui-B-8REtdH.js → doc-editor-ui-xuPB90yq.js} +1 -1
  11. package/dist/client/assets/doc-editor-ui-xuPB90yq.js.br +0 -0
  12. package/dist/client/assets/{feature-hint-DBFiLrtM.js → feature-hint-p4tQ8V_-.js} +1 -1
  13. package/dist/client/assets/feature-hint-p4tQ8V_-.js.br +0 -0
  14. package/dist/client/assets/{first-run-checklist-BH9FBVqg.js → first-run-checklist-B75rn_F3.js} +1 -1
  15. package/dist/client/assets/first-run-checklist-B75rn_F3.js.br +0 -0
  16. package/dist/client/assets/{hooks-panel-Xxum_jet.js → hooks-panel-BS1wN-Sf.js} +1 -1
  17. package/dist/client/assets/hooks-panel-BS1wN-Sf.js.br +0 -0
  18. package/dist/client/assets/{index-DI6o7rGH.js → index-CC-YdqKK.js} +5 -5
  19. package/dist/client/assets/index-CC-YdqKK.js.br +0 -0
  20. package/dist/client/assets/{issues-panel-C5xv0p5V.js → issues-panel-ixQZ1Zpt.js} +1 -1
  21. package/dist/client/assets/issues-panel-ixQZ1Zpt.js.br +0 -0
  22. package/dist/client/assets/{my-prs-panel-BBLC7nfh.js → my-prs-panel-DvOp_AXq.js} +1 -1
  23. package/dist/client/assets/my-prs-panel-DvOp_AXq.js.br +0 -0
  24. package/dist/client/assets/{nyan-cat-CiUobSoH.js → nyan-cat-d2bkyBa0.js} +1 -1
  25. package/dist/client/assets/nyan-cat-d2bkyBa0.js.br +0 -0
  26. package/dist/client/assets/{phone-shell-rMLztheW.js → phone-shell-7IqsFC4m.js} +1 -1
  27. package/dist/client/assets/phone-shell-7IqsFC4m.js.br +0 -0
  28. package/dist/client/assets/{plan-face-hbwZGQp-.js → plan-face-CjFhC9F8.js} +1 -1
  29. package/dist/client/assets/plan-face-CjFhC9F8.js.br +0 -0
  30. package/dist/client/assets/{plan-render-lkJvjRvG.js → plan-render-CmIQceyw.js} +1 -1
  31. package/dist/client/assets/plan-render-CmIQceyw.js.br +0 -0
  32. package/dist/client/assets/{pr-queue-columns-ZQyQE-Ro.js → pr-queue-columns-uW00PCIQ.js} +1 -1
  33. package/dist/client/assets/pr-queue-columns-uW00PCIQ.js.br +0 -0
  34. package/dist/client/assets/{radar-panel-D2yAYg1d.js → radar-panel-Bf2Wl5my.js} +1 -1
  35. package/dist/client/assets/radar-panel-Bf2Wl5my.js.br +0 -0
  36. package/dist/client/assets/{repo-roots-adder-Gs-qdNfB.js → repo-roots-adder-B5xxT2eW.js} +1 -1
  37. package/dist/client/assets/repo-roots-adder-B5xxT2eW.js.br +0 -0
  38. package/dist/client/assets/{resume-dialog-BQOjuwEs.js → resume-dialog-vT3Oepe0.js} +1 -1
  39. package/dist/client/assets/resume-dialog-vT3Oepe0.js.br +0 -0
  40. package/dist/client/assets/{review-queue-panel-BEzjHFln.js → review-queue-panel-xNtJAXkn.js} +1 -1
  41. package/dist/client/assets/review-queue-panel-xNtJAXkn.js.br +0 -0
  42. package/dist/client/assets/{settings-panel-DAzl-OG2.js → settings-panel-BB69waxb.js} +2 -2
  43. package/dist/client/assets/settings-panel-BB69waxb.js.br +0 -0
  44. package/dist/client/assets/{shown-face-DDq1psSy.js → shown-face-QZUGY5CO.js} +1 -1
  45. package/dist/client/assets/shown-face-QZUGY5CO.js.br +0 -0
  46. package/dist/client/assets/{team-review-panel-gzDAuuuZ.js → team-review-panel-C5T1nSQD.js} +1 -1
  47. package/dist/client/assets/team-review-panel-C5T1nSQD.js.br +0 -0
  48. package/dist/client/assets/{trace-panel-DwgSp1Ys.js → trace-panel-DsOmB6GD.js} +1 -1
  49. package/dist/client/assets/trace-panel-DsOmB6GD.js.br +0 -0
  50. package/dist/client/assets/{usage-panel-CruNSfkC.js → usage-panel-Dvf3ZxDZ.js} +1 -1
  51. package/dist/client/assets/usage-panel-Dvf3ZxDZ.js.br +0 -0
  52. package/dist/client/assets/{your-day-tip-XR4QFUTf.js → your-day-tip-CUKgr9yT.js} +1 -1
  53. package/dist/client/assets/your-day-tip-CUKgr9yT.js.br +0 -0
  54. package/dist/client/index.html +1 -1
  55. package/dist/client/index.html.br +0 -0
  56. package/dist/server/index.js +1 -1
  57. package/package.json +1 -1
  58. package/dist/client/assets/benchmark-panel-CZoHN_0Z.js.br +0 -0
  59. package/dist/client/assets/boards-view-0hW6lkva.js.br +0 -0
  60. package/dist/client/assets/community-panel-CmSsVWBy.js.br +0 -0
  61. package/dist/client/assets/dialogs-C1JgVkCl.js.br +0 -0
  62. package/dist/client/assets/doc-editor-ui-B-8REtdH.js.br +0 -0
  63. package/dist/client/assets/feature-hint-DBFiLrtM.js.br +0 -0
  64. package/dist/client/assets/first-run-checklist-BH9FBVqg.js.br +0 -0
  65. package/dist/client/assets/hooks-panel-Xxum_jet.js.br +0 -0
  66. package/dist/client/assets/index-DI6o7rGH.js.br +0 -0
  67. package/dist/client/assets/issues-panel-C5xv0p5V.js.br +0 -0
  68. package/dist/client/assets/my-prs-panel-BBLC7nfh.js.br +0 -0
  69. package/dist/client/assets/nyan-cat-CiUobSoH.js.br +0 -0
  70. package/dist/client/assets/phone-shell-rMLztheW.js.br +0 -0
  71. package/dist/client/assets/plan-face-hbwZGQp-.js.br +0 -0
  72. package/dist/client/assets/plan-render-lkJvjRvG.js.br +0 -0
  73. package/dist/client/assets/pr-queue-columns-ZQyQE-Ro.js.br +0 -0
  74. package/dist/client/assets/radar-panel-D2yAYg1d.js.br +0 -0
  75. package/dist/client/assets/repo-roots-adder-Gs-qdNfB.js.br +0 -0
  76. package/dist/client/assets/resume-dialog-BQOjuwEs.js.br +0 -0
  77. package/dist/client/assets/review-queue-panel-BEzjHFln.js.br +0 -0
  78. package/dist/client/assets/settings-panel-DAzl-OG2.js.br +0 -0
  79. package/dist/client/assets/shown-face-DDq1psSy.js.br +0 -0
  80. package/dist/client/assets/team-review-panel-gzDAuuuZ.js.br +0 -0
  81. package/dist/client/assets/trace-panel-DwgSp1Ys.js.br +0 -0
  82. package/dist/client/assets/usage-panel-CruNSfkC.js.br +0 -0
  83. package/dist/client/assets/your-day-tip-XR4QFUTf.js.br +0 -2
@@ -25423,196 +25423,6 @@ function buildHardenedGitInvocation(args, { baseEnv, transportSourceEnv = {}, pl
25423
25423
  };
25424
25424
  }
25425
25425
  //#endregion
25426
- //#region server/core/integration-sync-core.ts
25427
- function decideIntegrationSync({ localSha, remoteSha, ancestry, checkedOut, checkoutTree = "dirty" }) {
25428
- if (!remoteSha) return {
25429
- action: "none",
25430
- outcome: "no-remote"
25431
- };
25432
- if (!localSha) return {
25433
- action: "none",
25434
- outcome: "missing"
25435
- };
25436
- if (localSha === remoteSha) return {
25437
- action: "none",
25438
- outcome: "up-to-date"
25439
- };
25440
- if (ancestry === "ahead") return {
25441
- action: "none",
25442
- outcome: "ahead"
25443
- };
25444
- if (ancestry === "forked") return {
25445
- action: "none",
25446
- outcome: "diverged"
25447
- };
25448
- if (ancestry !== "behind") return {
25449
- action: "none",
25450
- outcome: "update-failed"
25451
- };
25452
- if (!checkedOut) return {
25453
- action: "update",
25454
- outcome: "updated"
25455
- };
25456
- if (checkoutTree === "clean") return {
25457
- action: "update-checkout",
25458
- outcome: "updated"
25459
- };
25460
- if (checkoutTree === "unknown") return {
25461
- action: "none",
25462
- outcome: "update-failed"
25463
- };
25464
- return {
25465
- action: "none",
25466
- outcome: "checked-out"
25467
- };
25468
- }
25469
- function classifyRefusedIntegrationSync({ currentSha, remoteSha, ancestry, checkoutTree }) {
25470
- if (currentSha && currentSha === remoteSha) return { outcome: "up-to-date" };
25471
- if (ancestry === "ahead") return { outcome: "ahead" };
25472
- if (ancestry === "forked") return { outcome: "diverged" };
25473
- if (checkoutTree === "dirty") return { outcome: "checked-out" };
25474
- return { outcome: "update-failed" };
25475
- }
25476
- //#endregion
25477
- //#region server/core/merge-proof-core.ts
25478
- var MERGE_DRIVER_KEY_PATTERN = "^merge\\..+\\.driver$";
25479
- var MERGE_DRIVER_KEY_REGEXP = new RegExp(MERGE_DRIVER_KEY_PATTERN);
25480
- var INJECTED_GIT_CONFIG_ENV_REGEXP = /^GIT_CONFIG(?:_COUNT|_KEY_\d+|_VALUE_\d+|_PARAMETERS)?$/;
25481
- var MERGE_PROBE_CONFIG_ENTRIES = [
25482
- ["merge.default", "text"],
25483
- ["merge.renormalize", "false"],
25484
- ["merge.union.driver", "false"]
25485
- ];
25486
- function neutralGitConfigEnv(inheritedEnv, devNullPath) {
25487
- const childEnv = {};
25488
- for (const [key, value] of Object.entries(inheritedEnv)) {
25489
- if (value === void 0) continue;
25490
- if (INJECTED_GIT_CONFIG_ENV_REGEXP.test(key)) continue;
25491
- childEnv[key] = value;
25492
- }
25493
- childEnv.GIT_CONFIG_GLOBAL = devNullPath;
25494
- childEnv.GIT_CONFIG_SYSTEM = devNullPath;
25495
- childEnv.GIT_CONFIG_NOSYSTEM = "1";
25496
- return childEnv;
25497
- }
25498
- function mergeDriverKeys(configuredKeysOutput) {
25499
- const keys = [];
25500
- for (const line of configuredKeysOutput.split(/\r?\n/)) {
25501
- const key = line.trim();
25502
- if (!MERGE_DRIVER_KEY_REGEXP.test(key)) continue;
25503
- if (keys.includes(key)) continue;
25504
- keys.push(key);
25505
- }
25506
- return keys;
25507
- }
25508
- function safeDirectoryEntries(safeDirectoryOutput) {
25509
- const entries = [];
25510
- for (const line of safeDirectoryOutput.split(/\r?\n/)) {
25511
- const directory = line.trim();
25512
- if (!directory) continue;
25513
- entries.push(["safe.directory", directory]);
25514
- }
25515
- return entries;
25516
- }
25517
- function numberedGitConfigEnv(neutralEnv, overrides) {
25518
- const childEnv = {
25519
- ...neutralEnv,
25520
- GIT_CONFIG_COUNT: String(overrides.length)
25521
- };
25522
- for (const [index, [key, value]] of overrides.entries()) {
25523
- childEnv[`GIT_CONFIG_KEY_${index}`] = key;
25524
- childEnv[`GIT_CONFIG_VALUE_${index}`] = value;
25525
- }
25526
- return childEnv;
25527
- }
25528
- function driverEnumerationEnv({ neutralEnv, safeDirectoryOutput }) {
25529
- return numberedGitConfigEnv(neutralEnv, safeDirectoryEntries(safeDirectoryOutput));
25530
- }
25531
- function mergeProbeEnv({ neutralEnv, safeDirectoryOutput, configuredKeysOutput }) {
25532
- return numberedGitConfigEnv(neutralEnv, [
25533
- ...safeDirectoryEntries(safeDirectoryOutput),
25534
- ...MERGE_PROBE_CONFIG_ENTRIES,
25535
- ...mergeDriverKeys(configuredKeysOutput).map((key) => [key, "false"])
25536
- ]);
25537
- }
25538
- function ancestryFromResult(result) {
25539
- if (!result.ok) return null;
25540
- return result.isAncestor === true;
25541
- }
25542
- function parseTreeOid(out) {
25543
- const firstLine = out.split(/\r?\n/).find((line) => line.trim());
25544
- if (!firstLine) return null;
25545
- const treeOid = firstLine.trim();
25546
- if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(treeOid)) return null;
25547
- return treeOid;
25548
- }
25549
- function buildTipProbe({ isAncestor, integrationTree, mergeTree }) {
25550
- return {
25551
- isAncestor,
25552
- integrationTreeOid: integrationTree.ok ? parseTreeOid(integrationTree.out ?? "") : null,
25553
- mergeTree: {
25554
- outcome: mergeTree.outcome,
25555
- treeOid: mergeTree.outcome === "tree" ? parseTreeOid(mergeTree.out ?? "") : null
25556
- }
25557
- };
25558
- }
25559
- function ancestorProvenProbe() {
25560
- return {
25561
- isAncestor: true,
25562
- integrationTreeOid: null,
25563
- mergeTree: {
25564
- outcome: "failed",
25565
- treeOid: null
25566
- }
25567
- };
25568
- }
25569
- function proveMerged(probe) {
25570
- if (probe.isAncestor === true) return {
25571
- verdict: "merged",
25572
- reason: "ancestor"
25573
- };
25574
- if (probe.isAncestor === null) return {
25575
- verdict: "undecidable",
25576
- reason: "ancestor-probe-failed"
25577
- };
25578
- if (probe.integrationTreeOid === null) return {
25579
- verdict: "undecidable",
25580
- reason: "tree-probe-failed"
25581
- };
25582
- if (probe.mergeTree.outcome === "failed") return {
25583
- verdict: "undecidable",
25584
- reason: "merge-tree-failed"
25585
- };
25586
- if (probe.mergeTree.outcome === "conflicts") return {
25587
- verdict: "not-merged",
25588
- reason: "unmerged-content"
25589
- };
25590
- if (probe.mergeTree.treeOid === null) return {
25591
- verdict: "undecidable",
25592
- reason: "merge-tree-failed"
25593
- };
25594
- if (probe.mergeTree.treeOid === probe.integrationTreeOid) return {
25595
- verdict: "merged",
25596
- reason: "tree-contained"
25597
- };
25598
- return {
25599
- verdict: "not-merged",
25600
- reason: "unmerged-content"
25601
- };
25602
- }
25603
- function proveMergedAcrossTips(probes) {
25604
- let mostCautiousProof = {
25605
- verdict: "not-merged",
25606
- reason: "unmerged-content"
25607
- };
25608
- for (const probe of probes) {
25609
- const proof = proveMerged(probe);
25610
- if (proof.verdict === "merged") return proof;
25611
- if (proof.verdict === "undecidable") mostCautiousProof = proof;
25612
- }
25613
- return mostCautiousProof;
25614
- }
25615
- //#endregion
25616
25426
  //#region server/core/share-list-core.ts
25617
25427
  var WILDCARD_SKIPPED_NAME = /production/i;
25618
25428
  function namesMatchingWildcard(entry, rootEntryNames) {
@@ -25659,51 +25469,14 @@ function listHomeWorktreePathsMissingLock(porcelain, glimmervoidHomes) {
25659
25469
  return entries.slice(1).filter((entry) => !entry.isLocked && isWorktreeHiddenFromGuardedSessions(entry.path, glimmervoidHomes)).map((entry) => entry.path);
25660
25470
  }
25661
25471
  //#endregion
25662
- //#region server/git/git-workspace.ts
25663
- var fsp = fs.promises;
25472
+ //#region server/git/workspace/workspace-context.ts
25473
+ var fsp$3 = fs.promises;
25664
25474
  var MERGE_PROBE_TIMEOUT_MS = 3e4;
25665
25475
  var REMOTE_REF_PREFIX = "refs/remotes/origin/";
25666
25476
  var REMOTE_BRANCH_LISTING_MAX_BUFFER = 67108864;
25667
25477
  var ISOLATED_CHECKOUT_HYDRATE_TIMEOUT_MS = 6e5;
25668
25478
  var ISOLATED_CHECKOUT_REVIEW_REF = "refs/heads/review";
25669
25479
  var ISOLATED_CHECKOUT_BASE_REF = "refs/benchmark/base";
25670
- async function prepareHardenedGitInvocation(args, baseEnv, probe) {
25671
- const invocationOptions = {
25672
- baseEnv,
25673
- transportSourceEnv: process.env,
25674
- platform: process.platform,
25675
- devNullPath: os.devNull
25676
- };
25677
- const enumeration = buildHardenedGitInvocation([...GIT_CONFIG_LISTING_ARGS], invocationOptions);
25678
- const configListing = await probe(enumeration.args, enumeration.env);
25679
- return buildHardenedGitInvocation(args, {
25680
- ...invocationOptions,
25681
- configListing
25682
- });
25683
- }
25684
- async function prepareHardenedGitCommand(args, options) {
25685
- const { indexFile, ...processOptions } = options;
25686
- const invocation = await prepareHardenedGitInvocation(args, options.env ?? process.env, async (probeArgs, probeEnv) => (await execFileAsync("git", probeArgs, {
25687
- ...processOptions,
25688
- env: probeEnv,
25689
- encoding: "utf8"
25690
- })).stdout);
25691
- if (indexFile) invocation.env.GIT_INDEX_FILE = indexFile;
25692
- return invocation;
25693
- }
25694
- async function runHardenedGit(args, options) {
25695
- const { input, indexFile, ...processOptions } = options;
25696
- const invocation = await prepareHardenedGitCommand(args, {
25697
- ...processOptions,
25698
- indexFile
25699
- });
25700
- return execFileAsync("git", invocation.args, {
25701
- ...processOptions,
25702
- input,
25703
- env: invocation.env,
25704
- encoding: "utf8"
25705
- });
25706
- }
25707
25480
  function errorExitCode(error) {
25708
25481
  return error?.code;
25709
25482
  }
@@ -25723,16 +25496,9 @@ function errResult(err) {
25723
25496
  err: wasKilledByTimeout ? `timed out (killed): ${detail}` : detail
25724
25497
  };
25725
25498
  }
25726
- function comparableGlimmervoidHomes(glimmervoidHome) {
25727
- try {
25728
- return [glimmervoidHome, fs.realpathSync(glimmervoidHome)];
25729
- } catch {
25730
- return [glimmervoidHome];
25731
- }
25732
- }
25733
25499
  async function directoryExists$1(candidatePath) {
25734
25500
  try {
25735
- await fsp.access(candidatePath);
25501
+ await fsp$3.access(candidatePath);
25736
25502
  return true;
25737
25503
  } catch {
25738
25504
  return false;
@@ -25790,22 +25556,6 @@ function mainWorktreePath(porcelain) {
25790
25556
  if (!firstEntry) return null;
25791
25557
  return firstEntry.slice(9).trim() || null;
25792
25558
  }
25793
- function sessionWorktreeLocation(projectPath, teamId, worktreeBase) {
25794
- if (worktreeBase) return {
25795
- parent: worktreeBase,
25796
- prefix: `${sanitizeWorktreeName(path.basename(projectPath)) || "repo"}-`
25797
- };
25798
- return {
25799
- parent: os.tmpdir(),
25800
- prefix: `glimmervoid-wt-${sanitizeWorktreeName(teamId)}-`
25801
- };
25802
- }
25803
- async function foreignSessionWorktreeReason(worktreePath, porcelain, location) {
25804
- const mainWorktree = mainWorktreePath(porcelain);
25805
- if (mainWorktree !== null && await comparableDirectoryPath(worktreePath) === await comparableDirectoryPath(mainWorktree)) return `refusing to discard ${worktreePath}: it is the main checkout`;
25806
- if (await comparableDirectoryPath(path.dirname(worktreePath)) === await comparableDirectoryPath(location.parent) && path.basename(worktreePath).startsWith(location.prefix)) return null;
25807
- return `refusing to discard ${worktreePath}: glimmervoid did not create this worktree under ${path.join(location.parent, location.prefix)}*`;
25808
- }
25809
25559
  function findWorktreeForBranch(porcelain, branch) {
25810
25560
  const hit = parseWorktreeBranches(porcelain).find((w) => w.branch === branch);
25811
25561
  return hit ? hit.cwd : null;
@@ -25833,189 +25583,11 @@ var UNPROBED_MARKER = {
25833
25583
  isMarkerRefResolvable: null,
25834
25584
  isMarkerAbsorbedByDefault: null
25835
25585
  };
25836
- function createGitWorkspace(opts = {}) {
25837
- const rawGit = opts.git || (async (args, cwd, extra) => {
25838
- const result = await runGit(args, {
25839
- cwd,
25840
- timeoutMs: extra?.timeout || 2e4,
25841
- trim: false,
25842
- ...extra?.maxBuffer ? { maxBuffer: extra.maxBuffer } : {},
25843
- ...extra?.replaceEnv ? { replaceEnv: extra.replaceEnv } : {},
25844
- ...extra?.env ? { env: extra.env } : {}
25845
- });
25846
- if (!result.ok) throw result.error;
25847
- return result.out;
25848
- });
25849
- const isolationContext = new AsyncLocalStorage();
25850
- const git = async (args, cwd, extra) => {
25851
- const isolation = isolationContext.getStore() ?? opts.isolation;
25852
- if (!(extra?.disableRepoCommands ?? isolation?.disableRepoCommands)) return rawGit(args, cwd, extra);
25853
- const invocation = await prepareHardenedGitInvocation(args, extra?.replaceEnv ?? isolation?.replaceEnv ?? process.env, (probeArgs, probeEnv) => rawGit(probeArgs, cwd, {
25854
- ...extra,
25855
- replaceEnv: probeEnv
25856
- }));
25857
- return rawGit(invocation.args, cwd, {
25858
- ...extra,
25859
- replaceEnv: {
25860
- ...invocation.env,
25861
- ...extra?.env
25862
- }
25863
- });
25864
- };
25865
- const mkdtemp = opts.mkdtemp || ((prefix) => fs.mkdtempSync(prefix));
25866
- const log = opts.log || console;
25867
- const rerereEnabled = opts.rerere !== false;
25868
- const glimmervoidHome = opts.glimmervoidHome ?? glimmervoidHomeDir$1();
25869
- const glimmervoidHomes = comparableGlimmervoidHomes(glimmervoidHome);
25870
- const removalGuard = resolveRemovalGuard(opts.removalGuard, glimmervoidHome);
25871
- const engineQueue = createSerialQueue();
25872
- const isolatedCall = (body, args) => () => isolationContext.run({
25873
- ...opts.isolation,
25874
- ...isolationContext.getStore(),
25875
- ...args
25876
- }, () => body(args));
25877
- const serialized = (body) => (args) => engineQueue.run(isolatedCall(body, args));
25878
- const admitted = (body, refuse) => async (args) => {
25879
- const admission = args.admissionTimeoutMs === void 0 ? {} : { admissionTimeoutMs: args.admissionTimeoutMs };
25880
- try {
25881
- return await engineQueue.run(isolatedCall(body, args), admission);
25882
- } catch (error) {
25883
- if (!isQueueAdmissionTimeout(error)) throw error;
25884
- return refuse(args);
25885
- }
25886
- };
25887
- async function run(args, cwd, extra) {
25888
- try {
25889
- return okResult(await git(args, cwd, extra));
25890
- } catch (err) {
25891
- return errResult(err);
25892
- }
25893
- }
25894
- const runInProject = (projectPath) => (args) => run(args, projectPath);
25895
- async function addWorktreeEntry(runGitInProject, worktreePath, addArgs, ownership) {
25896
- const added = await runGitInProject([
25897
- "worktree",
25898
- "add",
25899
- ...addArgs
25900
- ]);
25901
- if (!added.ok) return added;
25902
- await opts.ownedPaths?.record({
25903
- path: worktreePath,
25904
- kind: "git-worktree",
25905
- ...ownership
25906
- });
25907
- if (!isWorktreeHiddenFromGuardedSessions(worktreePath, glimmervoidHomes)) return added;
25908
- await lockWorktreeEntry(runGitInProject, worktreePath);
25909
- return added;
25910
- }
25911
- async function lockWorktreeEntry(runGitInProject, worktreePath) {
25912
- const locked = await runGitInProject([
25913
- "worktree",
25914
- "lock",
25915
- "--reason",
25916
- GLIMMERVOID_WORKTREE_LOCK_REASON,
25917
- worktreePath
25918
- ]);
25919
- if (!locked.ok) log.warn(`[git-workspace] could not lock ${worktreePath}, so a guarded session's git worktree prune can drop it: ${locked.err}`);
25920
- }
25921
- async function lockReusedHomeWorktrees(runGitInProject, porcelain) {
25922
- for (const unlockedPath of listHomeWorktreePathsMissingLock(porcelain, glimmervoidHomes)) {
25923
- if (!await directoryExists$1(unlockedPath)) continue;
25924
- await lockWorktreeEntry(runGitInProject, unlockedPath);
25925
- }
25926
- }
25927
- async function removeWorktreeEntry(runGitInProject, worktreePath, removeFlags) {
25928
- if (isWorktreeHiddenFromGuardedSessions(worktreePath, glimmervoidHomes)) await runGitInProject([
25929
- "worktree",
25930
- "unlock",
25931
- worktreePath
25932
- ]);
25933
- const removed = await runGitInProject([
25934
- "worktree",
25935
- "remove",
25936
- ...removeFlags,
25937
- worktreePath
25938
- ]);
25939
- await forgetRemovedPath(worktreePath);
25940
- return removed;
25941
- }
25942
- async function forgetRemovedPath(ownedPath) {
25943
- if (await directoryExists$1(ownedPath)) return;
25944
- await opts.ownedPaths?.forget(ownedPath);
25945
- }
25946
- async function admitRemoval(target) {
25947
- const facts = removalOwnershipFacts(target, target.path === null ? null : await opts.ownedPaths?.ownerOf(target.path) ?? null, removalGuard.protectedSessionIds());
25948
- const lastTouchedMs = isRecencyProbeNeeded(facts) ? await probeLastTouchedMs(target) : null;
25949
- const verdict = decideRemovalKeep({
25950
- ...facts,
25951
- lastTouchedMs,
25952
- nowMs: removalGuard.now()
25953
- });
25954
- if (verdict.keep) {
25955
- log.warn(`[removals] kept ${describeRemovalTarget(target)} from a ${target.cause} removal because of ${verdict.reason}`);
25956
- return {
25957
- admitted: false,
25958
- reason: verdict.reason
25959
- };
25960
- }
25961
- const record = buildRemovalRecord(target, facts, verdict.checksPassed, removalGuard.now());
25962
- if (!await appendRemovalRecord(removalGuard.journalPath, record, log)) return {
25963
- admitted: false,
25964
- reason: "removal-record-unwritten"
25965
- };
25966
- return { admitted: true };
25967
- }
25968
- async function probeLastTouchedMs({ projectPath, path: targetPath, branch, tipSha }) {
25969
- const touchedTimesMs = [];
25970
- const targetStat = targetPath === null ? "missing" : await statUnlessMissing(targetPath);
25971
- if (targetStat === null) return null;
25972
- if (targetPath !== null && targetStat !== "missing") {
25973
- touchedTimesMs.push(targetStat.mtimeMs);
25974
- const adminDir = await run(["rev-parse", "--absolute-git-dir"], targetPath);
25975
- const adminStat = adminDir.ok ? await fsp.stat(adminDir.out).catch(() => null) : null;
25976
- if (adminStat === null) return null;
25977
- touchedTimesMs.push(adminStat.mtimeMs);
25978
- }
25979
- const commitRef = tipSha ?? (branch ? `refs/heads/${branch}` : null);
25980
- if (commitRef !== null) {
25981
- const commitTime = await run([
25982
- "log",
25983
- "-1",
25984
- "--format=%ct",
25985
- commitRef
25986
- ], projectPath);
25987
- const commitTimeMs = commitTime.ok ? parseCommitTimeMs(commitTime.out) : null;
25988
- if (commitTimeMs === null) return null;
25989
- touchedTimesMs.push(commitTimeMs);
25990
- }
25991
- if (touchedTimesMs.length === 0) return null;
25992
- return Math.max(...touchedTimesMs);
25993
- }
25994
- async function recordOwnedFolder({ folderPath, owner }) {
25995
- await opts.ownedPaths?.record({
25996
- path: folderPath,
25997
- owner,
25998
- kind: "folder",
25999
- projectPath: null,
26000
- branch: null
26001
- });
26002
- }
26003
- async function pruneWorktreeEntries(runGitInProject) {
26004
- const listed = await runGitInProject([
26005
- "worktree",
26006
- "list",
26007
- "--porcelain"
26008
- ]);
26009
- for (const lockedPath of listed.ok ? listOwnLockedWorktreePaths(listed.out, glimmervoidHomes) : []) {
26010
- if (await directoryExists$1(lockedPath) || !await directoryExists$1(glimmervoidHome)) continue;
26011
- await runGitInProject([
26012
- "worktree",
26013
- "unlock",
26014
- lockedPath
26015
- ]);
26016
- }
26017
- return runGitInProject(["worktree", "prune"]);
26018
- }
25586
+ //#endregion
25587
+ //#region server/git/workspace/origin-ops.ts
25588
+ function createOriginOps(context) {
25589
+ const { git, run, log } = context;
25590
+ const { listWorktreePorcelain } = context.worktrees;
26019
25591
  async function detectDefaultBranch({ projectPath }) {
26020
25592
  const remoteHead = await run([
26021
25593
  "symbolic-ref",
@@ -26215,22 +25787,6 @@ function createGitWorkspace(opts = {}) {
26215
25787
  warning: `Merged into ${branch}, but origin refused the push, so origin/${branch} does not have it yet. Resync the base branch to push it.`
26216
25788
  };
26217
25789
  }
26218
- function joinWarnings(...warnings) {
26219
- const presentWarnings = warnings.filter((warning) => !!warning);
26220
- return presentWarnings.length > 0 ? presentWarnings.join(" ") : null;
26221
- }
26222
- function mergeSyncWarning(baseSync, branch) {
26223
- if (baseSync.fetched === false) return `could not fetch origin/${branch}; merged with local base: ${baseSync.error}`;
26224
- if (baseSync.error) return `could not fast-forward ${branch} from origin/${branch}; merged with local base`;
26225
- return null;
26226
- }
26227
- function includeWarning(mergeResult, warning) {
26228
- if (!warning) return mergeResult;
26229
- return {
26230
- ...mergeResult,
26231
- warning
26232
- };
26233
- }
26234
25790
  async function ensureLocalBranch(projectPath, baseBranch) {
26235
25791
  const seedCandidates = [
26236
25792
  `refs/remotes/origin/${baseBranch}`,
@@ -26258,318 +25814,232 @@ function createGitWorkspace(opts = {}) {
26258
25814
  }
26259
25815
  return null;
26260
25816
  }
26261
- async function createBody({ projectPath, owner, teamId, label, baseBranch = null, configuredIntegrationBranch = null, forkFromHead = false, worktreeBase, shareList }) {
26262
- const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
26263
- if (!inside.ok || inside.out !== "true") return {
26264
- cwd: projectPath,
26265
- isGit: false
26266
- };
26267
- const head = await run(["rev-parse", "HEAD"], projectPath);
26268
- if (!head.ok) return {
26269
- cwd: projectPath,
26270
- isGit: false
26271
- };
26272
- if (rerereEnabled) {
26273
- const configured = await run([
26274
- "config",
26275
- "--get",
26276
- "rerere.enabled"
26277
- ], projectPath);
26278
- if (!configured.ok || configured.out === "") await run([
26279
- "config",
26280
- "rerere.enabled",
26281
- "true"
26282
- ], projectPath);
26283
- }
26284
- const branch = `glimmervoid/${sanitizeWorktreeName(teamId)}/${sanitizeWorktreeName(label)}`;
26285
- await pruneWorktreeEntries(runInProject(projectPath));
26286
- const listed = await run([
26287
- "worktree",
26288
- "list",
26289
- "--porcelain"
26290
- ], projectPath);
26291
- if (listed.ok) {
26292
- const conflictPath = findWorktreeForBranch(listed.out, branch);
26293
- if (conflictPath) return {
26294
- cwd: projectPath,
26295
- isGit: false,
26296
- reason: "branch-in-use",
26297
- conflictPath,
26298
- branch,
26299
- base: (await migrateMarkerBase(projectPath, branch, baseBranch, configuredIntegrationBranch)).base
26300
- };
26301
- }
26302
- let base = (await run([
26303
- "rev-parse",
26304
- "--abbrev-ref",
26305
- "HEAD"
26306
- ], projectPath)).out || "HEAD";
26307
- if (!forkFromHead) base = baseBranch || await detectDefaultBranch({ projectPath });
26308
- if (!base) return {
26309
- cwd: projectPath,
26310
- isGit: false,
26311
- reason: "no-base-branch"
25817
+ async function fetchOriginBody({ projectPath, branch = null, timeoutMs = GIT_FETCH_TIMEOUT_MS }) {
25818
+ const fetchOptions = {
25819
+ timeout: timeoutMs,
25820
+ env: { GIT_TERMINAL_PROMPT: "0" }
26312
25821
  };
26313
- const ref = forkFromHead ? head : await run([
26314
- "rev-parse",
26315
- "--verify",
25822
+ if (branch) return run([
25823
+ "fetch",
26316
25824
  "--quiet",
26317
- `refs/heads/${base}`
26318
- ], projectPath);
26319
- const baseSha = ref.ok ? ref.out : await ensureLocalBranch(projectPath, base);
26320
- if (!baseSha) return {
26321
- cwd: projectPath,
26322
- isGit: false,
26323
- reason: "no-base-branch"
26324
- };
26325
- await deleteStaleSessionBranch(projectPath, branch);
26326
- if (worktreeBase) try {
26327
- fs.mkdirSync(worktreeBase, { recursive: true });
26328
- } catch {}
26329
- const location = sessionWorktreeLocation(projectPath, teamId, worktreeBase);
26330
- const wtDir = mkdtemp(path.join(location.parent, location.prefix));
26331
- const add = await addWorktreeEntry(runInProject(projectPath), wtDir, [
26332
- "-b",
26333
- branch,
26334
- wtDir,
26335
- baseSha
26336
- ], {
26337
- owner,
26338
- projectPath,
26339
- branch
26340
- });
26341
- if (!add.ok) {
26342
- try {
26343
- fs.rmSync(wtDir, {
26344
- recursive: true,
26345
- force: true
26346
- });
26347
- } catch {}
26348
- return {
26349
- cwd: projectPath,
26350
- isGit: false,
26351
- error: add.err
26352
- };
26353
- }
26354
- await run([
26355
- "config",
26356
- markerKey(branch),
26357
- base
26358
- ], projectPath);
26359
- await populateShare({
26360
- projectPath,
26361
- wtDir,
26362
- shareList
26363
- });
26364
- return {
26365
- cwd: wtDir,
26366
- isGit: true,
26367
- branch,
26368
- base,
26369
- baseSha
26370
- };
26371
- }
26372
- async function populateShare({ projectPath, wtDir, shareList, keepTrackableLinks = false }) {
26373
- if (!wtDir) return;
26374
- const expandedShareList = await expandShareListIn(projectPath, shareList);
26375
- const projectRealPath = await fs.promises.realpath(projectPath).catch(() => null);
26376
- if (projectRealPath) removeWorktreeLinks(wtDir, {
26377
- projectRealPath,
26378
- shareList: expandedShareList
26379
- });
26380
- if (!expandedShareList.length) return;
26381
- const ignored = [];
26382
- for (const rel of expandedShareList) if (rel && !String(rel).includes("..") && (await run([
26383
- "check-ignore",
26384
- "-q",
26385
- "--",
26386
- rel
26387
- ], projectPath)).ok) ignored.push(rel);
26388
- if (!ignored.length) return;
26389
- try {
26390
- await populateWorktree(projectPath, wtDir, ignored);
26391
- } catch {}
26392
- if (keepTrackableLinks) return;
26393
- await refuseTrackableLinks(wtDir, ignored);
25825
+ "--prune",
25826
+ "origin",
25827
+ "refs/heads/*:refs/remotes/origin/*"
25828
+ ], projectPath, fetchOptions);
25829
+ return run([
25830
+ "fetch",
25831
+ "--prune",
25832
+ "origin"
25833
+ ], projectPath, fetchOptions);
26394
25834
  }
26395
- async function ensureWorkspaceMemberBody({ projectPath, owner, wtDir, branch, shareList }) {
26396
- if (!wtDir || !branch) return {
26397
- cwd: projectPath,
26398
- isGit: false,
26399
- reason: "missing-workspace-member"
26400
- };
26401
- const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
26402
- if (!inside.ok || inside.out !== "true") return {
26403
- cwd: projectPath,
26404
- isGit: false,
26405
- reason: "not-git"
25835
+ async function seedBranchFromOriginBody({ projectPath, name }) {
25836
+ const branchName = name ?? "";
25837
+ if (!(await run([
25838
+ "check-ref-format",
25839
+ "--branch",
25840
+ branchName
25841
+ ], projectPath)).ok || branchName.startsWith("-")) return {
25842
+ ok: false,
25843
+ out: "",
25844
+ err: `not a branch name: ${branchName}`
26406
25845
  };
26407
- await pruneWorktreeEntries(runInProject(projectPath));
26408
- const listed = await run([
26409
- "worktree",
26410
- "list",
26411
- "--porcelain"
25846
+ const remoteRef = `refs/remotes/origin/${branchName}`;
25847
+ const fetched = await run([
25848
+ "fetch",
25849
+ "--quiet",
25850
+ "origin",
25851
+ `+refs/heads/${branchName}:${remoteRef}`
25852
+ ], projectPath, {
25853
+ timeout: GIT_FETCH_TIMEOUT_MS,
25854
+ env: { GIT_TERMINAL_PROMPT: "0" }
25855
+ });
25856
+ if (!fetched.ok) return fetched;
25857
+ const originTip = await run([
25858
+ "rev-parse",
25859
+ "--verify",
25860
+ "--quiet",
25861
+ remoteRef
26412
25862
  ], projectPath);
26413
- if (!listed.ok) return {
26414
- cwd: projectPath,
26415
- isGit: false,
26416
- error: listed.err
26417
- };
26418
- const conflictPath = findWorktreeForBranch(listed.out, branch);
26419
- if (conflictPath && !isSameDirectoryPath(conflictPath, wtDir)) return {
26420
- cwd: projectPath,
26421
- isGit: false,
26422
- reason: "branch-in-use",
26423
- conflictPath,
26424
- branch
26425
- };
26426
- const base = await detectDefaultBranch({ projectPath });
26427
- if (conflictPath) {
26428
- await populateShare({
26429
- projectPath,
26430
- wtDir,
26431
- shareList
26432
- });
26433
- return {
26434
- cwd: wtDir,
26435
- isGit: true,
26436
- branch,
26437
- base
26438
- };
26439
- }
26440
- if ((await run([
25863
+ if (!originTip.ok) return originTip;
25864
+ const localRef = `refs/heads/${branchName}`;
25865
+ const existing = await run([
26441
25866
  "rev-parse",
26442
25867
  "--verify",
26443
25868
  "--quiet",
26444
- `refs/heads/${branch}`
26445
- ], projectPath)).ok) {
26446
- const attached = await addWorktreeEntry(runInProject(projectPath), wtDir, [wtDir, branch], {
26447
- owner,
26448
- projectPath,
26449
- branch
26450
- });
26451
- if (!attached.ok) return {
26452
- cwd: projectPath,
26453
- isGit: false,
26454
- reason: "worktree-add-failed",
26455
- error: attached.err
26456
- };
26457
- await populateShare({
26458
- projectPath,
26459
- wtDir,
26460
- shareList
26461
- });
26462
- return {
26463
- cwd: wtDir,
26464
- isGit: true,
26465
- branch,
26466
- base
26467
- };
26468
- }
26469
- if (!base) return {
26470
- cwd: projectPath,
26471
- isGit: false,
26472
- reason: "no-base-branch"
26473
- };
26474
- const synced = await syncIntegrationBranchBody({
26475
- projectPath,
26476
- branch: base
26477
- });
26478
- if (synced.outcome === "fetch-failed" || synced.outcome === "update-failed") return {
26479
- cwd: projectPath,
26480
- isGit: false,
26481
- reason: "base-sync-failed",
26482
- error: synced.error
26483
- };
26484
- const baseRef = await run([
25869
+ localRef
25870
+ ], projectPath);
25871
+ if (existing.ok) return fastForwardSeededBranch(projectPath, branchName, existing.out, originTip.out);
25872
+ const created = await run([
25873
+ "branch",
25874
+ "--",
25875
+ branchName,
25876
+ remoteRef
25877
+ ], projectPath);
25878
+ if (!created.ok) return created;
25879
+ return run([
26485
25880
  "rev-parse",
26486
25881
  "--verify",
26487
25882
  "--quiet",
26488
- `refs/heads/${base}`
25883
+ localRef
26489
25884
  ], projectPath);
26490
- const baseSha = baseRef.ok ? baseRef.out : await ensureLocalBranch(projectPath, base);
26491
- if (!baseSha) return {
26492
- cwd: projectPath,
26493
- isGit: false,
26494
- reason: "no-base-branch"
26495
- };
26496
- const added = await addWorktreeEntry(runInProject(projectPath), wtDir, [
26497
- "-b",
26498
- branch,
26499
- wtDir,
26500
- baseSha
26501
- ], {
26502
- owner,
26503
- projectPath,
26504
- branch
26505
- });
26506
- if (!added.ok) return {
26507
- cwd: projectPath,
26508
- isGit: false,
26509
- reason: "worktree-add-failed",
26510
- error: added.err
26511
- };
26512
- await populateShare({
25885
+ }
25886
+ async function fastForwardSeededBranch(projectPath, branchName, localSha, originSha) {
25887
+ if (localSha === originSha) return okResult(localSha);
25888
+ const mismatch = `local branch ${branchName} is at ${localSha} but origin has ${originSha}`;
25889
+ const ancestry = await isAncestor({
26513
25890
  projectPath,
26514
- wtDir,
26515
- shareList
25891
+ ancestorSha: localSha,
25892
+ descendantSha: originSha
26516
25893
  });
26517
- return {
26518
- cwd: wtDir,
26519
- isGit: true,
26520
- branch,
26521
- base,
26522
- baseSha
25894
+ if (!ancestry.ok) return {
25895
+ ok: false,
25896
+ out: "",
25897
+ err: `could not compare ${mismatch}`
26523
25898
  };
26524
- }
26525
- async function refuseTrackableLinks(wtDir, entries) {
26526
- for (const rel of entries) {
26527
- if ((await run([
26528
- "check-ignore",
26529
- "-q",
26530
- "--",
26531
- rel
26532
- ], wtDir)).ok) continue;
26533
- const target = path.join(wtDir, rel);
26534
- const stat = await fsp.lstat(target).catch(() => null);
26535
- if (!stat || !stat.isSymbolicLink()) continue;
26536
- console.warn(`[git-workspace] not sharing ${rel}: git does not ignore it as a link, so a commit in the worktree would carry it (use a slash-free .gitignore entry)`);
26537
- try {
26538
- await fsp.rm(target, { force: true });
26539
- } catch {}
25899
+ if (!ancestry.isAncestor) return {
25900
+ ok: false,
25901
+ out: "",
25902
+ err: `${mismatch}, and the local branch has commits that are not on origin`
25903
+ };
25904
+ const listed = await listWorktreePorcelain(projectPath);
25905
+ if (!listed.ok) return listed;
25906
+ if (parseWorktreeBranches(listed.out).some((entry) => entry.branch === branchName)) return {
25907
+ ok: false,
25908
+ out: "",
25909
+ err: `${mismatch}, and it is checked out in a worktree`
25910
+ };
25911
+ const updated = await run([
25912
+ "update-ref",
25913
+ `refs/heads/${branchName}`,
25914
+ originSha,
25915
+ localSha
25916
+ ], projectPath);
25917
+ if (!updated.ok) return updated;
25918
+ return okResult(originSha);
25919
+ }
25920
+ async function listRemoteBranches({ projectPath, prefixes }) {
25921
+ if (usablePrefixes(prefixes).length === 0) return {
25922
+ ok: true,
25923
+ branches: []
25924
+ };
25925
+ const listed = await run([
25926
+ "for-each-ref",
25927
+ REMOTE_REF_PREFIX,
25928
+ "--format=%(refname) %(objectname) %(committerdate:unix) %(symref)"
25929
+ ], projectPath, { maxBuffer: REMOTE_BRANCH_LISTING_MAX_BUFFER });
25930
+ if (!listed.ok) return listed;
25931
+ const branches = [];
25932
+ for (const line of listed.out.split(/\r?\n/)) {
25933
+ if (!line) continue;
25934
+ const [refName, tipSha, commitTimeSeconds, symbolicTarget] = line.trim().split(/\s+/);
25935
+ if (symbolicTarget) continue;
25936
+ if (!refName.startsWith("refs/remotes/origin/")) continue;
25937
+ const name = refName.slice(REMOTE_REF_PREFIX.length);
25938
+ if (matchedPrefix(name, prefixes) === null) continue;
25939
+ branches.push({
25940
+ name,
25941
+ tipSha,
25942
+ tipCommitTimeMs: Number.parseInt(commitTimeSeconds, 10) * 1e3
25943
+ });
26540
25944
  }
25945
+ return {
25946
+ ok: true,
25947
+ branches
25948
+ };
26541
25949
  }
26542
- async function deleteStaleSessionBranch(projectPath, branch) {
26543
- if (!(await readLocalBranchSha(projectPath, branch)).out) return;
26544
- if (!(await admitRemoval({
26545
- cause: "session-create",
26546
- kind: "local-branch",
26547
- projectPath,
26548
- path: null,
26549
- branch
26550
- })).admitted) return;
26551
- await run([
26552
- "branch",
26553
- "-D",
26554
- branch
25950
+ async function listIntegrationTips({ projectPath, integrationBranch }) {
25951
+ const detectedBranch = integrationBranch || await detectDefaultBranch({ projectPath });
25952
+ const branchNames = [...new Set([
25953
+ detectedBranch,
25954
+ "main",
25955
+ "master"
25956
+ ].filter((name) => Boolean(name)))];
25957
+ const refNames = branchNames.flatMap((branchName) => [`refs/remotes/origin/${branchName}`, `refs/heads/${branchName}`]);
25958
+ const listed = await run([
25959
+ "for-each-ref",
25960
+ ...refNames,
25961
+ "--format=%(refname) %(objectname)"
26555
25962
  ], projectPath);
25963
+ if (!listed.ok) return listed;
25964
+ const shaByRef = /* @__PURE__ */ new Map();
25965
+ for (const line of listed.out.split(/\r?\n/)) {
25966
+ if (!line) continue;
25967
+ const [refName, sha] = line.trim().split(/\s+/);
25968
+ if (refNames.includes(refName)) shaByRef.set(refName, sha);
25969
+ }
25970
+ const integrationTips = [];
25971
+ for (const branch of branchNames) {
25972
+ const sha = shaByRef.get(`refs/remotes/origin/${branch}`) || shaByRef.get(`refs/heads/${branch}`);
25973
+ integrationTips.push({
25974
+ branch,
25975
+ sha: sha || null
25976
+ });
25977
+ }
25978
+ return {
25979
+ ok: true,
25980
+ integrationTips
25981
+ };
26556
25982
  }
26557
- async function tearDownWorktree(projectPath, wt, branch) {
26558
- if (!(await admitRemoval({
26559
- cause: "merge",
26560
- kind: "worktree",
26561
- projectPath,
26562
- path: wt,
26563
- branch: branch ?? null
26564
- })).admitted) return;
26565
- removeWorktreeLinks(wt);
26566
- await removeWorktreeEntry(runInProject(projectPath), wt, ["--force"]);
26567
- await pruneWorktreeEntries(runInProject(projectPath));
26568
- if (branch) await run([
26569
- "branch",
26570
- "-D",
26571
- branch
26572
- ], projectPath);
25983
+ async function isAncestor({ projectPath, ancestorSha, descendantSha }) {
25984
+ try {
25985
+ await git([
25986
+ "merge-base",
25987
+ "--is-ancestor",
25988
+ ancestorSha ?? "",
25989
+ descendantSha ?? ""
25990
+ ], projectPath);
25991
+ return {
25992
+ ok: true,
25993
+ isAncestor: true
25994
+ };
25995
+ } catch (err) {
25996
+ if (errorExitCode(err) === 1) return {
25997
+ ok: true,
25998
+ isAncestor: false
25999
+ };
26000
+ return {
26001
+ ...errResult(err),
26002
+ isAncestor: false
26003
+ };
26004
+ }
26005
+ }
26006
+ return {
26007
+ detectDefaultBranch,
26008
+ migrateMarkerBase,
26009
+ hasOriginRemote,
26010
+ originUrl,
26011
+ synchronizeBaseWithOrigin,
26012
+ pushBaseToOrigin,
26013
+ ensureLocalBranch,
26014
+ fetchOriginBody,
26015
+ seedBranchFromOriginBody,
26016
+ isAncestor,
26017
+ listRemoteBranches,
26018
+ listIntegrationTips
26019
+ };
26020
+ }
26021
+ //#endregion
26022
+ //#region server/git/workspace/rebase-ops.ts
26023
+ var fsp$2 = fs.promises;
26024
+ function createRebaseOps(context, origin) {
26025
+ const { run, runUntrusted, rerereEnabled } = context;
26026
+ const { tearDownWorktree } = context.worktrees;
26027
+ const { synchronizeBaseWithOrigin, pushBaseToOrigin } = origin;
26028
+ function joinWarnings(...warnings) {
26029
+ const presentWarnings = warnings.filter((warning) => !!warning);
26030
+ return presentWarnings.length > 0 ? presentWarnings.join(" ") : null;
26031
+ }
26032
+ function mergeSyncWarning(baseSync, branch) {
26033
+ if (baseSync.fetched === false) return `could not fetch origin/${branch}; merged with local base: ${baseSync.error}`;
26034
+ if (baseSync.error) return `could not fast-forward ${branch} from origin/${branch}; merged with local base`;
26035
+ return null;
26036
+ }
26037
+ function includeWarning(mergeResult, warning) {
26038
+ if (!warning) return mergeResult;
26039
+ return {
26040
+ ...mergeResult,
26041
+ warning
26042
+ };
26573
26043
  }
26574
26044
  async function fastForwardTarget(projectPath, sourceRef, target, targetIsHead) {
26575
26045
  if (!targetIsHead) {
@@ -26827,7 +26297,7 @@ function createGitWorkspace(opts = {}) {
26827
26297
  for (const [index, segment] of pathSegments.entries()) {
26828
26298
  if (!segment || segment === "." || segment === "..") return false;
26829
26299
  checkedPath = path.join(checkedPath, segment);
26830
- const entryStats = await fsp.lstat(checkedPath).catch(() => null);
26300
+ const entryStats = await fsp$2.lstat(checkedPath).catch(() => null);
26831
26301
  if (!entryStats) return false;
26832
26302
  if (index === pathSegments.length - 1) return entryStats.isFile();
26833
26303
  if (!entryStats.isDirectory()) return false;
@@ -27049,26 +26519,19 @@ function createGitWorkspace(opts = {}) {
27049
26519
  rerereReplayed
27050
26520
  };
27051
26521
  }
27052
- async function discardBody({ projectPath, workspace, cause }) {
27053
- if (!workspace || !workspace.isGit) return;
27054
- if (!(await admitRemoval({
27055
- cause,
27056
- kind: "worktree",
27057
- projectPath,
27058
- path: workspace.cwd || null,
27059
- branch: workspace.branch || null
27060
- })).admitted) return;
27061
- if (workspace.cwd) {
27062
- removeWorktreeLinks(workspace.cwd);
27063
- await removeWorktreeEntry(runInProject(projectPath), workspace.cwd, ["--force"]);
27064
- }
27065
- if (workspace.branch) await run([
27066
- "branch",
27067
- "-D",
27068
- workspace.branch
27069
- ], projectPath);
27070
- await pruneWorktreeEntries(runInProject(projectPath));
27071
- }
26522
+ return {
26523
+ fastForwardTarget,
26524
+ mergeBackBody,
26525
+ mergeKeepBody,
26526
+ rebaseOnlyBody
26527
+ };
26528
+ }
26529
+ //#endregion
26530
+ //#region server/git/workspace/probe-ops.ts
26531
+ function createProbeOps(context, origin) {
26532
+ const { run, runInProject } = context;
26533
+ const { listWorktreePorcelain, lockReusedHomeWorktrees } = context.worktrees;
26534
+ const { detectDefaultBranch, migrateMarkerBase } = origin;
27072
26535
  async function probeWorktreeWork({ projectPath, cwd, branch, measuredTip = branch, integrationBranch, configuredIntegrationBranch }) {
27073
26536
  const { base: resolvedIntegrationBranch, measureRef } = await migrateMarkerBase(projectPath, branch, integrationBranch, configuredIntegrationBranch);
27074
26537
  const dirty = await run(WORK_PRESENCE_STATUS_ARGS, cwd);
@@ -27121,11 +26584,7 @@ function createGitWorkspace(opts = {}) {
27121
26584
  const described = [];
27122
26585
  const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
27123
26586
  if (!inside.ok || inside.out !== "true") return described;
27124
- const listed = await run([
27125
- "worktree",
27126
- "list",
27127
- "--porcelain"
27128
- ], projectPath);
26587
+ const listed = await listWorktreePorcelain(projectPath);
27129
26588
  if (!listed.ok) return described;
27130
26589
  if (beforeDescribe) await beforeDescribe(listed.out);
27131
26590
  const mainWorktree = mainWorktreePath(listed.out);
@@ -27221,853 +26680,1448 @@ function createGitWorkspace(opts = {}) {
27221
26680
  headSha: head.out
27222
26681
  };
27223
26682
  }
27224
- function runUntrusted(args, cwd, { disableHooks, disableRepoCommands, replaceEnv }) {
27225
- return run(disableHooks ? [
27226
- "-c",
27227
- `core.hooksPath=${os.devNull}`,
27228
- ...args
27229
- ] : args, cwd, {
27230
- replaceEnv,
27231
- disableRepoCommands
27232
- });
27233
- }
27234
- async function removeWorktreeByPathBody({ projectPath, cwd, branch, cause, disableHooks, replaceEnv }) {
27235
- const admission = await admitRemoval({
27236
- cause,
27237
- kind: cwd ? "worktree" : "local-branch",
27238
- projectPath,
27239
- path: cwd || null,
27240
- branch: branch || null
27241
- });
27242
- if (!admission.admitted) return keptRemovalResult(admission.reason);
27243
- const isolation = {
27244
- disableHooks,
27245
- replaceEnv
27246
- };
27247
- let failure = null;
27248
- if (cwd) {
27249
- removeWorktreeLinks(cwd);
27250
- const removed = await removeWorktreeEntry((args) => runUntrusted(args, projectPath, isolation), cwd, ["--force"]);
27251
- if (!removed.ok) failure = removed;
27252
- }
27253
- if (branch) {
27254
- const deleted = await runUntrusted([
27255
- "branch",
27256
- "-D",
27257
- branch
27258
- ], projectPath, isolation);
27259
- if (!deleted.ok && failure === null) failure = deleted;
27260
- }
27261
- await pruneWorktreeEntries((args) => runUntrusted(args, projectPath, isolation));
27262
- return failure ?? okResult("");
27263
- }
27264
- async function readLocalBranchSha(projectPath, branch) {
27265
- try {
27266
- return okResult(await git([
27267
- "rev-parse",
27268
- "--verify",
27269
- "--quiet",
27270
- `refs/heads/${branch}`
27271
- ], projectPath));
27272
- } catch (err) {
27273
- if (errorExitCode(err) === 1) return okResult("");
27274
- return errResult(err);
27275
- }
27276
- }
27277
- async function discardSessionBranchBody({ projectPath, teamId = "", label = "", worktreeBase, disableHooks, replaceEnv }) {
27278
- const branch = `glimmervoid/${sanitizeWorktreeName(teamId)}/${sanitizeWorktreeName(label)}`;
27279
- const existingBranch = await readLocalBranchSha(projectPath, branch);
27280
- if (!existingBranch.ok) return existingBranch;
27281
- if (existingBranch.out === "") return okResult("");
27282
- const listed = await run([
27283
- "worktree",
27284
- "list",
27285
- "--porcelain"
26683
+ return {
26684
+ describeWorkspaceMemberWorkBody,
26685
+ hasUnmergedWorkBody,
26686
+ listWorktreesBody,
26687
+ listSessionWorktreesBody,
26688
+ probeWorktreeDirtyBody
26689
+ };
26690
+ }
26691
+ //#endregion
26692
+ //#region server/core/integration-sync-core.ts
26693
+ function decideIntegrationSync({ localSha, remoteSha, ancestry, checkedOut, checkoutTree = "dirty" }) {
26694
+ if (!remoteSha) return {
26695
+ action: "none",
26696
+ outcome: "no-remote"
26697
+ };
26698
+ if (!localSha) return {
26699
+ action: "none",
26700
+ outcome: "missing"
26701
+ };
26702
+ if (localSha === remoteSha) return {
26703
+ action: "none",
26704
+ outcome: "up-to-date"
26705
+ };
26706
+ if (ancestry === "ahead") return {
26707
+ action: "none",
26708
+ outcome: "ahead"
26709
+ };
26710
+ if (ancestry === "forked") return {
26711
+ action: "none",
26712
+ outcome: "diverged"
26713
+ };
26714
+ if (ancestry !== "behind") return {
26715
+ action: "none",
26716
+ outcome: "update-failed"
26717
+ };
26718
+ if (!checkedOut) return {
26719
+ action: "update",
26720
+ outcome: "updated"
26721
+ };
26722
+ if (checkoutTree === "clean") return {
26723
+ action: "update-checkout",
26724
+ outcome: "updated"
26725
+ };
26726
+ if (checkoutTree === "unknown") return {
26727
+ action: "none",
26728
+ outcome: "update-failed"
26729
+ };
26730
+ return {
26731
+ action: "none",
26732
+ outcome: "checked-out"
26733
+ };
26734
+ }
26735
+ function classifyRefusedIntegrationSync({ currentSha, remoteSha, ancestry, checkoutTree }) {
26736
+ if (currentSha && currentSha === remoteSha) return { outcome: "up-to-date" };
26737
+ if (ancestry === "ahead") return { outcome: "ahead" };
26738
+ if (ancestry === "forked") return { outcome: "diverged" };
26739
+ if (checkoutTree === "dirty") return { outcome: "checked-out" };
26740
+ return { outcome: "update-failed" };
26741
+ }
26742
+ //#endregion
26743
+ //#region server/core/merge-proof-core.ts
26744
+ var MERGE_DRIVER_KEY_PATTERN = "^merge\\..+\\.driver$";
26745
+ var MERGE_DRIVER_KEY_REGEXP = new RegExp(MERGE_DRIVER_KEY_PATTERN);
26746
+ var INJECTED_GIT_CONFIG_ENV_REGEXP = /^GIT_CONFIG(?:_COUNT|_KEY_\d+|_VALUE_\d+|_PARAMETERS)?$/;
26747
+ var MERGE_PROBE_CONFIG_ENTRIES = [
26748
+ ["merge.default", "text"],
26749
+ ["merge.renormalize", "false"],
26750
+ ["merge.union.driver", "false"]
26751
+ ];
26752
+ function neutralGitConfigEnv(inheritedEnv, devNullPath) {
26753
+ const childEnv = {};
26754
+ for (const [key, value] of Object.entries(inheritedEnv)) {
26755
+ if (value === void 0) continue;
26756
+ if (INJECTED_GIT_CONFIG_ENV_REGEXP.test(key)) continue;
26757
+ childEnv[key] = value;
26758
+ }
26759
+ childEnv.GIT_CONFIG_GLOBAL = devNullPath;
26760
+ childEnv.GIT_CONFIG_SYSTEM = devNullPath;
26761
+ childEnv.GIT_CONFIG_NOSYSTEM = "1";
26762
+ return childEnv;
26763
+ }
26764
+ function mergeDriverKeys(configuredKeysOutput) {
26765
+ const keys = [];
26766
+ for (const line of configuredKeysOutput.split(/\r?\n/)) {
26767
+ const key = line.trim();
26768
+ if (!MERGE_DRIVER_KEY_REGEXP.test(key)) continue;
26769
+ if (keys.includes(key)) continue;
26770
+ keys.push(key);
26771
+ }
26772
+ return keys;
26773
+ }
26774
+ function safeDirectoryEntries(safeDirectoryOutput) {
26775
+ const entries = [];
26776
+ for (const line of safeDirectoryOutput.split(/\r?\n/)) {
26777
+ const directory = line.trim();
26778
+ if (!directory) continue;
26779
+ entries.push(["safe.directory", directory]);
26780
+ }
26781
+ return entries;
26782
+ }
26783
+ function numberedGitConfigEnv(neutralEnv, overrides) {
26784
+ const childEnv = {
26785
+ ...neutralEnv,
26786
+ GIT_CONFIG_COUNT: String(overrides.length)
26787
+ };
26788
+ for (const [index, [key, value]] of overrides.entries()) {
26789
+ childEnv[`GIT_CONFIG_KEY_${index}`] = key;
26790
+ childEnv[`GIT_CONFIG_VALUE_${index}`] = value;
26791
+ }
26792
+ return childEnv;
26793
+ }
26794
+ function driverEnumerationEnv({ neutralEnv, safeDirectoryOutput }) {
26795
+ return numberedGitConfigEnv(neutralEnv, safeDirectoryEntries(safeDirectoryOutput));
26796
+ }
26797
+ function mergeProbeEnv({ neutralEnv, safeDirectoryOutput, configuredKeysOutput }) {
26798
+ return numberedGitConfigEnv(neutralEnv, [
26799
+ ...safeDirectoryEntries(safeDirectoryOutput),
26800
+ ...MERGE_PROBE_CONFIG_ENTRIES,
26801
+ ...mergeDriverKeys(configuredKeysOutput).map((key) => [key, "false"])
26802
+ ]);
26803
+ }
26804
+ function ancestryFromResult(result) {
26805
+ if (!result.ok) return null;
26806
+ return result.isAncestor === true;
26807
+ }
26808
+ function parseTreeOid(out) {
26809
+ const firstLine = out.split(/\r?\n/).find((line) => line.trim());
26810
+ if (!firstLine) return null;
26811
+ const treeOid = firstLine.trim();
26812
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(treeOid)) return null;
26813
+ return treeOid;
26814
+ }
26815
+ function buildTipProbe({ isAncestor, integrationTree, mergeTree }) {
26816
+ return {
26817
+ isAncestor,
26818
+ integrationTreeOid: integrationTree.ok ? parseTreeOid(integrationTree.out ?? "") : null,
26819
+ mergeTree: {
26820
+ outcome: mergeTree.outcome,
26821
+ treeOid: mergeTree.outcome === "tree" ? parseTreeOid(mergeTree.out ?? "") : null
26822
+ }
26823
+ };
26824
+ }
26825
+ function ancestorProvenProbe() {
26826
+ return {
26827
+ isAncestor: true,
26828
+ integrationTreeOid: null,
26829
+ mergeTree: {
26830
+ outcome: "failed",
26831
+ treeOid: null
26832
+ }
26833
+ };
26834
+ }
26835
+ function proveMerged(probe) {
26836
+ if (probe.isAncestor === true) return {
26837
+ verdict: "merged",
26838
+ reason: "ancestor"
26839
+ };
26840
+ if (probe.isAncestor === null) return {
26841
+ verdict: "undecidable",
26842
+ reason: "ancestor-probe-failed"
26843
+ };
26844
+ if (probe.integrationTreeOid === null) return {
26845
+ verdict: "undecidable",
26846
+ reason: "tree-probe-failed"
26847
+ };
26848
+ if (probe.mergeTree.outcome === "failed") return {
26849
+ verdict: "undecidable",
26850
+ reason: "merge-tree-failed"
26851
+ };
26852
+ if (probe.mergeTree.outcome === "conflicts") return {
26853
+ verdict: "not-merged",
26854
+ reason: "unmerged-content"
26855
+ };
26856
+ if (probe.mergeTree.treeOid === null) return {
26857
+ verdict: "undecidable",
26858
+ reason: "merge-tree-failed"
26859
+ };
26860
+ if (probe.mergeTree.treeOid === probe.integrationTreeOid) return {
26861
+ verdict: "merged",
26862
+ reason: "tree-contained"
26863
+ };
26864
+ return {
26865
+ verdict: "not-merged",
26866
+ reason: "unmerged-content"
26867
+ };
26868
+ }
26869
+ function proveMergedAcrossTips(probes) {
26870
+ let mostCautiousProof = {
26871
+ verdict: "not-merged",
26872
+ reason: "unmerged-content"
26873
+ };
26874
+ for (const probe of probes) {
26875
+ const proof = proveMerged(probe);
26876
+ if (proof.verdict === "merged") return proof;
26877
+ if (proof.verdict === "undecidable") mostCautiousProof = proof;
26878
+ }
26879
+ return mostCautiousProof;
26880
+ }
26881
+ //#endregion
26882
+ //#region server/git/workspace/integration-ops.ts
26883
+ var fsp$1 = fs.promises;
26884
+ function createIntegrationOps(context, origin, rebase) {
26885
+ const { git, run, runUntrusted, serialized, admitted } = context;
26886
+ const { listWorktreePorcelain } = context.worktrees;
26887
+ const { hasOriginRemote, isAncestor } = origin;
26888
+ const { fastForwardTarget } = rebase;
26889
+ async function checkoutDetachedBody({ worktreePath, sha, ...isolation }) {
26890
+ if (!worktreePath) return {
26891
+ ok: false,
26892
+ out: "",
26893
+ err: "a detached worktree needs a path"
26894
+ };
26895
+ if (normalizeSha(sha) !== sha) return {
26896
+ ok: false,
26897
+ out: "",
26898
+ err: "a detached worktree sha must be 40 lowercase hexadecimal characters"
26899
+ };
26900
+ return runUntrusted([
26901
+ "checkout",
26902
+ "--quiet",
26903
+ "--detach",
26904
+ sha
26905
+ ], worktreePath, isolation);
26906
+ }
26907
+ function isolatedCheckoutRefusal({ checkoutPath, sha, baseSha }) {
26908
+ if (!checkoutPath) return {
26909
+ ok: false,
26910
+ out: "",
26911
+ err: "an isolated checkout needs a path"
26912
+ };
26913
+ if (normalizeSha(sha) !== sha || normalizeSha(baseSha) !== baseSha) return {
26914
+ ok: false,
26915
+ out: "",
26916
+ err: "an isolated checkout sha and base sha must be 40 lowercase hexadecimal characters"
26917
+ };
26918
+ return null;
26919
+ }
26920
+ async function hydrateCheckoutTree(projectPath, sha) {
26921
+ const emptyTree = await run([
26922
+ "hash-object",
26923
+ "-t",
26924
+ "tree",
26925
+ os.devNull
27286
26926
  ], projectPath);
27287
- if (!listed.ok) return listed;
27288
- const worktreePath = findWorktreeForBranch(listed.out, branch);
27289
- if (worktreePath === null) return removeWorktreeByPathBody({
27290
- projectPath,
27291
- branch,
27292
- cause: "session",
27293
- disableHooks,
27294
- replaceEnv
26927
+ if (!emptyTree.ok) return emptyTree;
26928
+ return run([
26929
+ "diff",
26930
+ "--shortstat",
26931
+ emptyTree.out,
26932
+ sha
26933
+ ], projectPath, {
26934
+ timeout: ISOLATED_CHECKOUT_HYDRATE_TIMEOUT_MS,
26935
+ env: { GIT_TERMINAL_PROMPT: "0" }
27295
26936
  });
27296
- const refusal = await foreignSessionWorktreeReason(worktreePath, listed.out, sessionWorktreeLocation(projectPath, teamId, worktreeBase));
27297
- if (refusal !== null) return {
26937
+ }
26938
+ async function stageIsolatedCheckoutBody({ projectPath, checkoutPath = "", sha = "", baseSha = "" }) {
26939
+ const commonDir = await run(["rev-parse", "--git-common-dir"], projectPath);
26940
+ if (!commonDir.ok || !commonDir.out) return {
27298
26941
  ok: false,
27299
26942
  out: "",
27300
- err: refusal
26943
+ err: commonDir.err || "the source repository has no git dir"
27301
26944
  };
27302
- return removeWorktreeByPathBody({
27303
- projectPath,
27304
- cwd: worktreePath,
27305
- branch,
27306
- cause: "session",
27307
- disableHooks,
27308
- replaceEnv
26945
+ const sourceObjectsDir = path.join(path.resolve(projectPath, commonDir.out), "objects");
26946
+ await fsp$1.mkdir(path.dirname(checkoutPath), { recursive: true });
26947
+ await fsp$1.mkdir(checkoutPath);
26948
+ const initialized = await run([
26949
+ "init",
26950
+ "--quiet",
26951
+ "--template="
26952
+ ], checkoutPath);
26953
+ if (!initialized.ok) return initialized;
26954
+ const alternatesPath = path.join(checkoutPath, ".git", "objects", "info", "alternates");
26955
+ await fsp$1.mkdir(path.dirname(alternatesPath), { recursive: true });
26956
+ await fsp$1.writeFile(alternatesPath, `${sourceObjectsDir}\n`, "utf8");
26957
+ for (const [ref, refSha] of [[ISOLATED_CHECKOUT_REVIEW_REF, sha], [ISOLATED_CHECKOUT_BASE_REF, baseSha]]) {
26958
+ const updated = await run([
26959
+ "update-ref",
26960
+ ref,
26961
+ refSha
26962
+ ], checkoutPath);
26963
+ if (!updated.ok) return updated;
26964
+ }
26965
+ const checkedOut = await run([
26966
+ "checkout",
26967
+ "--quiet",
26968
+ "--detach",
26969
+ ISOLATED_CHECKOUT_REVIEW_REF
26970
+ ], checkoutPath);
26971
+ if (!checkedOut.ok) return checkedOut;
26972
+ const status = await run(WORKTREE_STATUS_ARGS, checkoutPath);
26973
+ if (!status.ok) return status;
26974
+ if (status.out !== "") return {
26975
+ ok: false,
26976
+ out: "",
26977
+ err: "the isolated checkout reports changes right after checkout"
26978
+ };
26979
+ return okResult("");
26980
+ }
26981
+ const stageIsolatedCheckoutQueued = serialized(stageIsolatedCheckoutBody);
26982
+ async function stageIsolatedCheckout(args) {
26983
+ const refusal = isolatedCheckoutRefusal(args);
26984
+ if (refusal) return refusal;
26985
+ const hydrated = await hydrateCheckoutTree(args.projectPath, args.sha ?? "");
26986
+ if (!hydrated.ok) return {
26987
+ ok: false,
26988
+ out: "",
26989
+ err: hydrated.err || "the reviewed tree could not be fetched"
26990
+ };
26991
+ return stageIsolatedCheckoutQueued(args).catch(errResult);
26992
+ }
26993
+ async function mergeFastForwardToBody({ projectPath, expectedHead, sha, timeoutMs }) {
26994
+ if (normalizeSha(sha) !== sha) return {
26995
+ ok: false,
26996
+ out: "",
26997
+ err: "a fast-forward merge needs a 40 lowercase hexadecimal target sha",
26998
+ sampledHead: null,
26999
+ outcome: "invalid-target-sha"
27000
+ };
27001
+ const commandOptions = timeoutMs ? { timeout: timeoutMs } : void 0;
27002
+ const head = await run(["rev-parse", "HEAD"], projectPath, commandOptions);
27003
+ if (!head.ok || !head.out) return {
27004
+ ...head,
27005
+ ok: false,
27006
+ sampledHead: null,
27007
+ outcome: "head-unreadable"
27008
+ };
27009
+ if (head.out !== expectedHead) return {
27010
+ ok: false,
27011
+ out: "",
27012
+ err: `HEAD changed from ${expectedHead ?? "unknown"} to ${head.out}`,
27013
+ sampledHead: head.out,
27014
+ outcome: "head-mismatch"
27015
+ };
27016
+ const merged = await run([
27017
+ "merge",
27018
+ "--ff-only",
27019
+ sha
27020
+ ], projectPath, commandOptions);
27021
+ return {
27022
+ ...merged,
27023
+ sampledHead: head.out,
27024
+ outcome: merged.ok ? "merged" : "merge-failed"
27025
+ };
27026
+ }
27027
+ const mergeFastForwardTo = admitted(mergeFastForwardToBody, (args) => ({
27028
+ ok: false,
27029
+ out: "",
27030
+ err: `the git queue did not admit the merge within ${args.admissionTimeoutMs}ms`,
27031
+ sampledHead: null,
27032
+ outcome: "queue-admission-timed-out"
27033
+ }));
27034
+ async function resetKeepToBody({ projectPath, expectedHead, sha, timeoutMs }) {
27035
+ if (normalizeSha(sha) !== sha) return {
27036
+ ok: false,
27037
+ out: "",
27038
+ err: "a keep reset needs a 40 lowercase hexadecimal target sha"
27039
+ };
27040
+ const commandOptions = timeoutMs ? { timeout: timeoutMs } : void 0;
27041
+ const head = await run(["rev-parse", "HEAD"], projectPath, commandOptions);
27042
+ if (!head.ok || !head.out) return {
27043
+ ...head,
27044
+ ok: false
27045
+ };
27046
+ if (head.out !== expectedHead) return {
27047
+ ok: false,
27048
+ out: "",
27049
+ err: `HEAD changed from ${expectedHead ?? "unknown"} to ${head.out}`
27050
+ };
27051
+ return run([
27052
+ "reset",
27053
+ "--keep",
27054
+ sha
27055
+ ], projectPath, commandOptions);
27056
+ }
27057
+ async function classifyRefusedSync({ projectPath, branch, localRef, localSha, remoteSha, err }) {
27058
+ const current = await run([
27059
+ "rev-parse",
27060
+ "--verify",
27061
+ "--quiet",
27062
+ localRef
27063
+ ], projectPath);
27064
+ const currentSha = current.ok && current.out ? current.out : localSha;
27065
+ let ancestry = null;
27066
+ if (currentSha && remoteSha && currentSha !== remoteSha) ancestry = (await probeBaseAncestry(projectPath, currentSha, remoteSha)).ancestry;
27067
+ const checkout = await readRefusedCheckoutTree(projectPath, branch);
27068
+ const { outcome } = classifyRefusedIntegrationSync({
27069
+ currentSha,
27070
+ remoteSha,
27071
+ ancestry,
27072
+ checkoutTree: checkout.state
27309
27073
  });
27074
+ if (outcome !== "update-failed") return {
27075
+ outcome,
27076
+ from: currentSha,
27077
+ to: remoteSha
27078
+ };
27079
+ return {
27080
+ outcome,
27081
+ from: currentSha,
27082
+ to: remoteSha,
27083
+ error: firstGitErrorLine(err || checkout.error)
27084
+ };
27310
27085
  }
27311
- async function pruneWorktreesBody({ projectPath, disableHooks, replaceEnv }) {
27312
- return pruneWorktreeEntries((args) => runUntrusted(args, projectPath, {
27313
- disableHooks,
27314
- replaceEnv
27315
- }));
27086
+ async function probeBaseAncestry(projectPath, localSha, remoteSha) {
27087
+ const forward = await isAncestor({
27088
+ projectPath,
27089
+ ancestorSha: localSha,
27090
+ descendantSha: remoteSha
27091
+ });
27092
+ if (!forward.ok) return {
27093
+ ancestry: null,
27094
+ error: forward.err ?? ""
27095
+ };
27096
+ if (forward.isAncestor) return {
27097
+ ancestry: "behind",
27098
+ error: ""
27099
+ };
27100
+ const reverse = await isAncestor({
27101
+ projectPath,
27102
+ ancestorSha: remoteSha,
27103
+ descendantSha: localSha
27104
+ });
27105
+ if (reverse.ok && reverse.isAncestor) return {
27106
+ ancestry: "ahead",
27107
+ error: ""
27108
+ };
27109
+ return {
27110
+ ancestry: "forked",
27111
+ error: ""
27112
+ };
27316
27113
  }
27317
- async function removeSharedLinks(wtDir, shareList) {
27318
- for (const rel of await expandShareListIn(wtDir, shareList)) {
27319
- if (!rel || String(rel).includes("..")) continue;
27320
- const linkPath = path.join(wtDir, rel);
27321
- const stat = await fsp.lstat(linkPath).catch(() => null);
27322
- if (!stat || !stat.isSymbolicLink()) continue;
27323
- if (!(await run([
27324
- "check-ignore",
27325
- "-q",
27326
- "--",
27327
- rel
27328
- ], wtDir)).ok) continue;
27329
- await fsp.rm(linkPath, {
27330
- recursive: false,
27331
- force: true
27332
- }).catch(() => fsp.rmdir(linkPath)).catch(() => {});
27333
- }
27114
+ async function readRefusedCheckoutTree(projectPath, branch) {
27115
+ const listed = await listWorktreePorcelain(projectPath);
27116
+ if (!listed.ok) return {
27117
+ state: "unknown",
27118
+ error: listed.err ?? ""
27119
+ };
27120
+ const checkoutPath = findWorktreeForBranch(listed.out, branch);
27121
+ if (!checkoutPath) return {
27122
+ state: null,
27123
+ error: ""
27124
+ };
27125
+ return readCheckoutTree(checkoutPath);
27334
27126
  }
27335
- async function removeWorkspaceMemberBody({ projectPath, cwd, branch, shareList, cause, discardWork = false }) {
27336
- if (!cwd) return {
27127
+ async function readCheckoutTree(worktreePath) {
27128
+ const status = await run([
27129
+ "--no-optional-locks",
27130
+ "status",
27131
+ "--porcelain",
27132
+ "--untracked-files=no"
27133
+ ], worktreePath);
27134
+ if (!status.ok) return {
27135
+ state: "unknown",
27136
+ error: status.err ?? ""
27137
+ };
27138
+ return {
27139
+ state: status.out === "" ? "clean" : "dirty",
27140
+ error: ""
27141
+ };
27142
+ }
27143
+ async function findLocalFilesAddedUpstream({ checkoutPath, localSha, remoteSha }) {
27144
+ const added = await run([
27145
+ "diff",
27146
+ "--name-only",
27147
+ "--no-renames",
27148
+ "--diff-filter=A",
27149
+ "-z",
27150
+ localSha,
27151
+ remoteSha
27152
+ ], checkoutPath);
27153
+ if (!added.ok) return {
27337
27154
  ok: false,
27338
- out: "",
27339
- err: "a workspace member removal needs a path"
27155
+ err: added.err ?? ""
27340
27156
  };
27341
- const admission = await admitRemoval({
27342
- cause,
27343
- kind: "worktree",
27344
- projectPath,
27345
- path: cwd,
27346
- branch: branch || null
27347
- });
27348
- if (!admission.admitted) return keptRemovalResult(admission.reason);
27349
- await removeSharedLinks(cwd, shareList);
27350
- const removed = await removeWorktreeEntry(runInProject(projectPath), cwd, discardWork ? ["--force", "--force"] : []);
27351
- if (discardWork && await directoryExists$1(cwd)) await fsp.rm(cwd, {
27352
- recursive: true,
27353
- force: true
27354
- });
27355
- await pruneWorktreeEntries(runInProject(projectPath));
27356
- await forgetRemovedPath(cwd);
27357
- if (discardWork && !await directoryExists$1(cwd)) return {
27157
+ const addedPaths = added.out.split("\0").filter(Boolean);
27158
+ const collidingPaths = [];
27159
+ for (const addedPath of addedPaths) if (await fsp$1.lstat(path.join(checkoutPath, addedPath)).then(() => true, (error) => !isMissingFileError(error, { includeNotDir: false }))) collidingPaths.push(addedPath);
27160
+ return {
27358
27161
  ok: true,
27359
- out: removed.out
27162
+ collidingPaths
27360
27163
  };
27361
- return removed;
27362
- }
27363
- async function listWorktreeBranches({ projectPath }) {
27364
- const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
27365
- if (!inside.ok || inside.out !== "true") return [];
27366
- const listed = await run([
27367
- "worktree",
27368
- "list",
27369
- "--porcelain"
27370
- ], projectPath);
27371
- if (!listed.ok) return [];
27372
- return parseWorktreeBranches(listed.out);
27373
27164
  }
27374
- async function fetchOriginBody({ projectPath, branch = null, timeoutMs = GIT_FETCH_TIMEOUT_MS }) {
27375
- const fetchOptions = {
27376
- timeout: timeoutMs,
27377
- env: { GIT_TERMINAL_PROMPT: "0" }
27378
- };
27379
- if (branch) return run([
27380
- "fetch",
27165
+ async function fastForwardCheckout({ checkoutPath, branch, localSha, remoteSha }) {
27166
+ const refused = (error) => ({
27167
+ outcome: "update-failed",
27168
+ from: localSha,
27169
+ to: remoteSha,
27170
+ error
27171
+ });
27172
+ const headBranch = await run([
27173
+ "symbolic-ref",
27381
27174
  "--quiet",
27382
- "--prune",
27383
- "origin",
27384
- "refs/heads/*:refs/remotes/origin/*"
27385
- ], projectPath, fetchOptions);
27386
- return run([
27387
- "fetch",
27388
- "--prune",
27389
- "origin"
27390
- ], projectPath, fetchOptions);
27175
+ "--short",
27176
+ "HEAD"
27177
+ ], checkoutPath);
27178
+ if (!headBranch.ok || headBranch.out !== branch) return refused(`${checkoutPath} no longer has ${branch} checked out`);
27179
+ const collisions = await findLocalFilesAddedUpstream({
27180
+ checkoutPath,
27181
+ localSha,
27182
+ remoteSha
27183
+ });
27184
+ if (!collisions.ok) return refused(firstGitErrorLine(collisions.err));
27185
+ if (collisions.collidingPaths.length > 0) return refused(`fast-forward would overwrite local file ${collisions.collidingPaths.join(", ")}`);
27186
+ const merged = await run([
27187
+ "merge",
27188
+ "--ff-only",
27189
+ remoteSha
27190
+ ], checkoutPath);
27191
+ if (merged.ok) return {
27192
+ outcome: "updated",
27193
+ from: localSha,
27194
+ to: remoteSha
27195
+ };
27196
+ return refused(firstGitErrorLine(merged.err ?? ""));
27391
27197
  }
27392
- async function seedBranchFromOriginBody({ projectPath, name }) {
27393
- const branchName = name ?? "";
27394
- if (!(await run([
27395
- "check-ref-format",
27396
- "--branch",
27397
- branchName
27398
- ], projectPath)).ok || branchName.startsWith("-")) return {
27399
- ok: false,
27400
- out: "",
27401
- err: `not a branch name: ${branchName}`
27198
+ async function syncIntegrationBranchBody({ projectPath, branch }) {
27199
+ if (!await hasOriginRemote(projectPath)) return {
27200
+ outcome: "no-remote",
27201
+ from: null,
27202
+ to: null
27402
27203
  };
27403
- const remoteRef = `refs/remotes/origin/${branchName}`;
27404
- const fetched = await run([
27204
+ const localRef = `refs/heads/${branch}`;
27205
+ const remoteRef = `refs/remotes/origin/${branch}`;
27206
+ if (!(await run([
27405
27207
  "fetch",
27406
- "--quiet",
27208
+ "--prune",
27407
27209
  "origin",
27408
- `+refs/heads/${branchName}:${remoteRef}`
27210
+ "+refs/heads/*:refs/remotes/origin/*"
27409
27211
  ], projectPath, {
27410
- timeout: GIT_FETCH_TIMEOUT_MS,
27212
+ timeout: 8e3,
27411
27213
  env: { GIT_TERMINAL_PROMPT: "0" }
27412
- });
27413
- if (!fetched.ok) return fetched;
27414
- const originTip = await run([
27415
- "rev-parse",
27416
- "--verify",
27417
- "--quiet",
27418
- remoteRef
27419
- ], projectPath);
27420
- if (!originTip.ok) return originTip;
27421
- const localRef = `refs/heads/${branchName}`;
27422
- const existing = await run([
27214
+ })).ok) return {
27215
+ outcome: "fetch-failed",
27216
+ from: null,
27217
+ to: null
27218
+ };
27219
+ const local = await run([
27423
27220
  "rev-parse",
27424
27221
  "--verify",
27425
27222
  "--quiet",
27426
27223
  localRef
27427
27224
  ], projectPath);
27428
- if (existing.ok) return fastForwardSeededBranch(projectPath, branchName, existing.out, originTip.out);
27429
- const created = await run([
27430
- "branch",
27431
- "--",
27432
- branchName,
27433
- remoteRef
27434
- ], projectPath);
27435
- if (!created.ok) return created;
27436
- return run([
27225
+ const remote = await run([
27437
27226
  "rev-parse",
27438
27227
  "--verify",
27439
27228
  "--quiet",
27440
- localRef
27229
+ remoteRef
27441
27230
  ], projectPath);
27442
- }
27443
- async function fastForwardSeededBranch(projectPath, branchName, localSha, originSha) {
27444
- if (localSha === originSha) return okResult(localSha);
27445
- const mismatch = `local branch ${branchName} is at ${localSha} but origin has ${originSha}`;
27446
- const ancestry = await isAncestor({
27447
- projectPath,
27448
- ancestorSha: localSha,
27449
- descendantSha: originSha
27231
+ const localSha = local.ok ? local.out : null;
27232
+ const remoteSha = remote.ok ? remote.out : null;
27233
+ let ancestry = null;
27234
+ let syncError = "";
27235
+ let checkedOut = false;
27236
+ let checkoutPath = null;
27237
+ let checkoutTree = "unknown";
27238
+ if (localSha && remoteSha && localSha !== remoteSha) {
27239
+ const probe = await probeBaseAncestry(projectPath, localSha, remoteSha);
27240
+ ancestry = probe.ancestry;
27241
+ syncError = probe.error;
27242
+ if (ancestry === "behind") {
27243
+ const listed = await listWorktreePorcelain(projectPath);
27244
+ if (!listed.ok) syncError = listed.err ?? "";
27245
+ checkoutPath = listed.ok ? findWorktreeForBranch(listed.out, branch ?? "") : null;
27246
+ checkedOut = !listed.ok || Boolean(checkoutPath);
27247
+ if (checkoutPath) {
27248
+ const tree = await readCheckoutTree(checkoutPath);
27249
+ checkoutTree = tree.state;
27250
+ syncError = tree.error;
27251
+ }
27252
+ }
27253
+ }
27254
+ const decision = decideIntegrationSync({
27255
+ localSha,
27256
+ remoteSha,
27257
+ ancestry,
27258
+ checkedOut,
27259
+ checkoutTree
27450
27260
  });
27451
- if (!ancestry.ok) return {
27452
- ok: false,
27453
- out: "",
27454
- err: `could not compare ${mismatch}`
27455
- };
27456
- if (!ancestry.isAncestor) return {
27457
- ok: false,
27458
- out: "",
27459
- err: `${mismatch}, and the local branch has commits that are not on origin`
27460
- };
27461
- const listed = await run([
27462
- "worktree",
27463
- "list",
27464
- "--porcelain"
27465
- ], projectPath);
27466
- if (!listed.ok) return listed;
27467
- if (parseWorktreeBranches(listed.out).some((entry) => entry.branch === branchName)) return {
27468
- ok: false,
27469
- out: "",
27470
- err: `${mismatch}, and it is checked out in a worktree`
27261
+ if (decision.outcome === "update-failed") return {
27262
+ outcome: decision.outcome,
27263
+ from: localSha,
27264
+ to: remoteSha,
27265
+ error: firstGitErrorLine(syncError)
27471
27266
  };
27472
- const updated = await run([
27473
- "update-ref",
27474
- `refs/heads/${branchName}`,
27475
- originSha,
27476
- localSha
27477
- ], projectPath);
27478
- if (!updated.ok) return updated;
27479
- return okResult(originSha);
27480
- }
27481
- async function stageDetachedWorktreeBody({ projectPath, worktreePath, sha, owner, disableHooks, replaceEnv }) {
27482
- if (!worktreePath) return {
27483
- ok: false,
27484
- out: "",
27485
- err: "a detached worktree needs a path"
27267
+ if (decision.action === "update-checkout" && checkoutPath && localSha && remoteSha) return fastForwardCheckout({
27268
+ checkoutPath,
27269
+ branch: branch ?? "",
27270
+ localSha,
27271
+ remoteSha
27272
+ });
27273
+ if (decision.action !== "update") return {
27274
+ outcome: decision.outcome,
27275
+ from: localSha,
27276
+ to: remoteSha
27486
27277
  };
27487
- if (normalizeSha(sha) !== sha) return {
27488
- ok: false,
27489
- out: "",
27490
- err: "a detached worktree sha must be 40 lowercase hexadecimal characters"
27278
+ const updated = await fastForwardTarget(projectPath, remoteRef, branch ?? "", false);
27279
+ if (updated.ok) return {
27280
+ outcome: "updated",
27281
+ from: localSha,
27282
+ to: remoteSha
27491
27283
  };
27492
- return addWorktreeEntry((args) => runUntrusted(args, projectPath, {
27493
- disableHooks,
27494
- replaceEnv
27495
- }), worktreePath, [
27496
- "--detach",
27497
- worktreePath,
27498
- sha
27499
- ], {
27500
- owner,
27284
+ return classifyRefusedSync({
27501
27285
  projectPath,
27502
- branch: null
27286
+ branch: branch ?? "",
27287
+ localRef,
27288
+ localSha,
27289
+ remoteSha,
27290
+ err: updated.err
27503
27291
  });
27504
27292
  }
27505
- async function checkoutDetachedBody({ worktreePath, sha, ...isolation }) {
27506
- if (!worktreePath) return {
27293
+ async function readGitConfigValues(args, projectPath, timeoutMs, replaceEnv) {
27294
+ try {
27295
+ return okResult(await git(["config", ...args], projectPath, {
27296
+ timeout: timeoutMs,
27297
+ ...replaceEnv ? { replaceEnv } : {}
27298
+ }));
27299
+ } catch (err) {
27300
+ if (errorExitCode(err) === 1) return okResult("");
27301
+ return errResult(err);
27302
+ }
27303
+ }
27304
+ async function resolveMergeProbeEnv({ projectPath, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
27305
+ const safeDirectories = await readGitConfigValues(["--get-all", "safe.directory"], projectPath, timeoutMs);
27306
+ if (!safeDirectories.ok) return {
27507
27307
  ok: false,
27508
- out: "",
27509
- err: "a detached worktree needs a path"
27308
+ err: safeDirectories.err || "reading safe.directory failed"
27510
27309
  };
27511
- if (normalizeSha(sha) !== sha) return {
27310
+ const neutralEnv = neutralGitConfigEnv(process.env, os.devNull);
27311
+ const safeDirectoryOutput = safeDirectories.out;
27312
+ const configuredKeys = await readGitConfigValues([
27313
+ "--name-only",
27314
+ "--get-regexp",
27315
+ MERGE_DRIVER_KEY_PATTERN
27316
+ ], projectPath, timeoutMs, driverEnumerationEnv({
27317
+ neutralEnv,
27318
+ safeDirectoryOutput
27319
+ }));
27320
+ if (!configuredKeys.ok) return {
27512
27321
  ok: false,
27513
- out: "",
27514
- err: "a detached worktree sha must be 40 lowercase hexadecimal characters"
27322
+ err: configuredKeys.err || "enumerating merge drivers failed"
27515
27323
  };
27516
- return runUntrusted([
27517
- "checkout",
27518
- "--quiet",
27519
- "--detach",
27520
- sha
27521
- ], worktreePath, isolation);
27324
+ return {
27325
+ ok: true,
27326
+ probeEnv: mergeProbeEnv({
27327
+ neutralEnv,
27328
+ safeDirectoryOutput,
27329
+ configuredKeysOutput: configuredKeys.out
27330
+ })
27331
+ };
27332
+ }
27333
+ async function writeMergedTree({ projectPath, integrationSha, branchSha, probeEnv, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
27334
+ try {
27335
+ return {
27336
+ ...okResult(await git([
27337
+ "merge-tree",
27338
+ "--write-tree",
27339
+ "--allow-unrelated-histories",
27340
+ integrationSha,
27341
+ branchSha
27342
+ ], projectPath, {
27343
+ timeout: timeoutMs,
27344
+ replaceEnv: probeEnv
27345
+ })),
27346
+ outcome: "tree"
27347
+ };
27348
+ } catch (err) {
27349
+ if (errorExitCode(err) === 1) return {
27350
+ ...errResult(err),
27351
+ outcome: "conflicts"
27352
+ };
27353
+ return {
27354
+ ...errResult(err),
27355
+ outcome: "failed"
27356
+ };
27357
+ }
27358
+ }
27359
+ async function treeOid({ projectPath, sha, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
27360
+ return run(["rev-parse", `${sha ?? ""}^{tree}`], projectPath, { timeout: timeoutMs });
27361
+ }
27362
+ return {
27363
+ checkoutDetachedBody,
27364
+ stageIsolatedCheckout,
27365
+ mergeFastForwardTo,
27366
+ resetKeepToBody,
27367
+ syncIntegrationBranchBody,
27368
+ resolveMergeProbeEnv,
27369
+ writeMergedTree,
27370
+ treeOid
27371
+ };
27372
+ }
27373
+ //#endregion
27374
+ //#region server/git/git-workspace.ts
27375
+ var fsp = fs.promises;
27376
+ async function prepareHardenedGitInvocation(args, baseEnv, probe) {
27377
+ const invocationOptions = {
27378
+ baseEnv,
27379
+ transportSourceEnv: process.env,
27380
+ platform: process.platform,
27381
+ devNullPath: os.devNull
27382
+ };
27383
+ const enumeration = buildHardenedGitInvocation([...GIT_CONFIG_LISTING_ARGS], invocationOptions);
27384
+ const configListing = await probe(enumeration.args, enumeration.env);
27385
+ return buildHardenedGitInvocation(args, {
27386
+ ...invocationOptions,
27387
+ configListing
27388
+ });
27389
+ }
27390
+ async function prepareHardenedGitCommand(args, options) {
27391
+ const { indexFile, ...processOptions } = options;
27392
+ const invocation = await prepareHardenedGitInvocation(args, options.env ?? process.env, async (probeArgs, probeEnv) => (await execFileAsync("git", probeArgs, {
27393
+ ...processOptions,
27394
+ env: probeEnv,
27395
+ encoding: "utf8"
27396
+ })).stdout);
27397
+ if (indexFile) invocation.env.GIT_INDEX_FILE = indexFile;
27398
+ return invocation;
27399
+ }
27400
+ async function runHardenedGit(args, options) {
27401
+ const { input, indexFile, ...processOptions } = options;
27402
+ const invocation = await prepareHardenedGitCommand(args, {
27403
+ ...processOptions,
27404
+ indexFile
27405
+ });
27406
+ return execFileAsync("git", invocation.args, {
27407
+ ...processOptions,
27408
+ input,
27409
+ env: invocation.env,
27410
+ encoding: "utf8"
27411
+ });
27412
+ }
27413
+ function comparableGlimmervoidHomes(glimmervoidHome) {
27414
+ try {
27415
+ return [glimmervoidHome, fs.realpathSync(glimmervoidHome)];
27416
+ } catch {
27417
+ return [glimmervoidHome];
27418
+ }
27419
+ }
27420
+ function sessionWorktreeLocation(projectPath, teamId, worktreeBase) {
27421
+ if (worktreeBase) return {
27422
+ parent: worktreeBase,
27423
+ prefix: `${sanitizeWorktreeName(path.basename(projectPath)) || "repo"}-`
27424
+ };
27425
+ return {
27426
+ parent: os.tmpdir(),
27427
+ prefix: `glimmervoid-wt-${sanitizeWorktreeName(teamId)}-`
27428
+ };
27429
+ }
27430
+ async function foreignSessionWorktreeReason(worktreePath, porcelain, location) {
27431
+ const mainWorktree = mainWorktreePath(porcelain);
27432
+ if (mainWorktree !== null && await comparableDirectoryPath(worktreePath) === await comparableDirectoryPath(mainWorktree)) return `refusing to discard ${worktreePath}: it is the main checkout`;
27433
+ if (await comparableDirectoryPath(path.dirname(worktreePath)) === await comparableDirectoryPath(location.parent) && path.basename(worktreePath).startsWith(location.prefix)) return null;
27434
+ return `refusing to discard ${worktreePath}: glimmervoid did not create this worktree under ${path.join(location.parent, location.prefix)}*`;
27435
+ }
27436
+ function createGitWorkspace(opts = {}) {
27437
+ const rawGit = opts.git || (async (args, cwd, extra) => {
27438
+ const result = await runGit(args, {
27439
+ cwd,
27440
+ timeoutMs: extra?.timeout || 2e4,
27441
+ trim: false,
27442
+ ...extra?.maxBuffer ? { maxBuffer: extra.maxBuffer } : {},
27443
+ ...extra?.replaceEnv ? { replaceEnv: extra.replaceEnv } : {},
27444
+ ...extra?.env ? { env: extra.env } : {}
27445
+ });
27446
+ if (!result.ok) throw result.error;
27447
+ return result.out;
27448
+ });
27449
+ const isolationContext = new AsyncLocalStorage();
27450
+ const git = async (args, cwd, extra) => {
27451
+ const isolation = isolationContext.getStore() ?? opts.isolation;
27452
+ if (!(extra?.disableRepoCommands ?? isolation?.disableRepoCommands)) return rawGit(args, cwd, extra);
27453
+ const invocation = await prepareHardenedGitInvocation(args, extra?.replaceEnv ?? isolation?.replaceEnv ?? process.env, (probeArgs, probeEnv) => rawGit(probeArgs, cwd, {
27454
+ ...extra,
27455
+ replaceEnv: probeEnv
27456
+ }));
27457
+ return rawGit(invocation.args, cwd, {
27458
+ ...extra,
27459
+ replaceEnv: {
27460
+ ...invocation.env,
27461
+ ...extra?.env
27462
+ }
27463
+ });
27464
+ };
27465
+ const mkdtemp = opts.mkdtemp || ((prefix) => fs.mkdtempSync(prefix));
27466
+ const log = opts.log || console;
27467
+ const rerereEnabled = opts.rerere !== false;
27468
+ const glimmervoidHome = opts.glimmervoidHome ?? glimmervoidHomeDir$1();
27469
+ const glimmervoidHomes = comparableGlimmervoidHomes(glimmervoidHome);
27470
+ const removalGuard = resolveRemovalGuard(opts.removalGuard, glimmervoidHome);
27471
+ const engineQueue = createSerialQueue();
27472
+ const isolatedCall = (body, args) => () => isolationContext.run({
27473
+ ...opts.isolation,
27474
+ ...isolationContext.getStore(),
27475
+ ...args
27476
+ }, () => body(args));
27477
+ const serialized = (body) => (args) => engineQueue.run(isolatedCall(body, args));
27478
+ const admitted = (body, refuse) => async (args) => {
27479
+ const admission = args.admissionTimeoutMs === void 0 ? {} : { admissionTimeoutMs: args.admissionTimeoutMs };
27480
+ try {
27481
+ return await engineQueue.run(isolatedCall(body, args), admission);
27482
+ } catch (error) {
27483
+ if (!isQueueAdmissionTimeout(error)) throw error;
27484
+ return refuse(args);
27485
+ }
27486
+ };
27487
+ async function run(args, cwd, extra) {
27488
+ try {
27489
+ return okResult(await git(args, cwd, extra));
27490
+ } catch (err) {
27491
+ return errResult(err);
27492
+ }
27493
+ }
27494
+ const runInProject = (projectPath) => (args) => run(args, projectPath);
27495
+ async function addWorktreeEntry(runGitInProject, worktreePath, addArgs, ownership) {
27496
+ const added = await runGitInProject([
27497
+ "worktree",
27498
+ "add",
27499
+ ...addArgs
27500
+ ]);
27501
+ if (!added.ok) return added;
27502
+ await opts.ownedPaths?.record({
27503
+ path: worktreePath,
27504
+ kind: "git-worktree",
27505
+ ...ownership
27506
+ });
27507
+ if (!isWorktreeHiddenFromGuardedSessions(worktreePath, glimmervoidHomes)) return added;
27508
+ await lockWorktreeEntry(runGitInProject, worktreePath);
27509
+ return added;
27510
+ }
27511
+ async function lockWorktreeEntry(runGitInProject, worktreePath) {
27512
+ const locked = await runGitInProject([
27513
+ "worktree",
27514
+ "lock",
27515
+ "--reason",
27516
+ GLIMMERVOID_WORKTREE_LOCK_REASON,
27517
+ worktreePath
27518
+ ]);
27519
+ if (!locked.ok) log.warn(`[git-workspace] could not lock ${worktreePath}, so a guarded session's git worktree prune can drop it: ${locked.err}`);
27522
27520
  }
27523
- function isolatedCheckoutRefusal({ checkoutPath, sha, baseSha }) {
27524
- if (!checkoutPath) return {
27525
- ok: false,
27526
- out: "",
27527
- err: "an isolated checkout needs a path"
27528
- };
27529
- if (normalizeSha(sha) !== sha || normalizeSha(baseSha) !== baseSha) return {
27530
- ok: false,
27531
- out: "",
27532
- err: "an isolated checkout sha and base sha must be 40 lowercase hexadecimal characters"
27533
- };
27534
- return null;
27521
+ async function lockReusedHomeWorktrees(runGitInProject, porcelain) {
27522
+ for (const unlockedPath of listHomeWorktreePathsMissingLock(porcelain, glimmervoidHomes)) {
27523
+ if (!await directoryExists$1(unlockedPath)) continue;
27524
+ await lockWorktreeEntry(runGitInProject, unlockedPath);
27525
+ }
27535
27526
  }
27536
- async function hydrateCheckoutTree(projectPath, sha) {
27537
- const emptyTree = await run([
27538
- "hash-object",
27539
- "-t",
27540
- "tree",
27541
- os.devNull
27542
- ], projectPath);
27543
- if (!emptyTree.ok) return emptyTree;
27544
- return run([
27545
- "diff",
27546
- "--shortstat",
27547
- emptyTree.out,
27548
- sha
27549
- ], projectPath, {
27550
- timeout: ISOLATED_CHECKOUT_HYDRATE_TIMEOUT_MS,
27551
- env: { GIT_TERMINAL_PROMPT: "0" }
27552
- });
27527
+ async function removeWorktreeEntry(runGitInProject, worktreePath, removeFlags) {
27528
+ if (isWorktreeHiddenFromGuardedSessions(worktreePath, glimmervoidHomes)) await runGitInProject([
27529
+ "worktree",
27530
+ "unlock",
27531
+ worktreePath
27532
+ ]);
27533
+ const removed = await runGitInProject([
27534
+ "worktree",
27535
+ "remove",
27536
+ ...removeFlags,
27537
+ worktreePath
27538
+ ]);
27539
+ await forgetRemovedPath(worktreePath);
27540
+ return removed;
27553
27541
  }
27554
- async function stageIsolatedCheckoutBody({ projectPath, checkoutPath = "", sha = "", baseSha = "" }) {
27555
- const commonDir = await run(["rev-parse", "--git-common-dir"], projectPath);
27556
- if (!commonDir.ok || !commonDir.out) return {
27557
- ok: false,
27558
- out: "",
27559
- err: commonDir.err || "the source repository has no git dir"
27560
- };
27561
- const sourceObjectsDir = path.join(path.resolve(projectPath, commonDir.out), "objects");
27562
- await fsp.mkdir(path.dirname(checkoutPath), { recursive: true });
27563
- await fsp.mkdir(checkoutPath);
27564
- const initialized = await run([
27565
- "init",
27566
- "--quiet",
27567
- "--template="
27568
- ], checkoutPath);
27569
- if (!initialized.ok) return initialized;
27570
- const alternatesPath = path.join(checkoutPath, ".git", "objects", "info", "alternates");
27571
- await fsp.mkdir(path.dirname(alternatesPath), { recursive: true });
27572
- await fsp.writeFile(alternatesPath, `${sourceObjectsDir}\n`, "utf8");
27573
- for (const [ref, refSha] of [[ISOLATED_CHECKOUT_REVIEW_REF, sha], [ISOLATED_CHECKOUT_BASE_REF, baseSha]]) {
27574
- const updated = await run([
27575
- "update-ref",
27576
- ref,
27577
- refSha
27578
- ], checkoutPath);
27579
- if (!updated.ok) return updated;
27542
+ async function forgetRemovedPath(ownedPath) {
27543
+ if (await directoryExists$1(ownedPath)) return;
27544
+ await opts.ownedPaths?.forget(ownedPath);
27545
+ }
27546
+ async function admitRemoval(target) {
27547
+ const facts = removalOwnershipFacts(target, target.path === null ? null : await opts.ownedPaths?.ownerOf(target.path) ?? null, removalGuard.protectedSessionIds());
27548
+ const lastTouchedMs = isRecencyProbeNeeded(facts) ? await probeLastTouchedMs(target) : null;
27549
+ const verdict = decideRemovalKeep({
27550
+ ...facts,
27551
+ lastTouchedMs,
27552
+ nowMs: removalGuard.now()
27553
+ });
27554
+ if (verdict.keep) {
27555
+ log.warn(`[removals] kept ${describeRemovalTarget(target)} from a ${target.cause} removal because of ${verdict.reason}`);
27556
+ return {
27557
+ admitted: false,
27558
+ reason: verdict.reason
27559
+ };
27580
27560
  }
27581
- const checkedOut = await run([
27582
- "checkout",
27583
- "--quiet",
27584
- "--detach",
27585
- ISOLATED_CHECKOUT_REVIEW_REF
27586
- ], checkoutPath);
27587
- if (!checkedOut.ok) return checkedOut;
27588
- const status = await run(WORKTREE_STATUS_ARGS, checkoutPath);
27589
- if (!status.ok) return status;
27590
- if (status.out !== "") return {
27591
- ok: false,
27592
- out: "",
27593
- err: "the isolated checkout reports changes right after checkout"
27561
+ const record = buildRemovalRecord(target, facts, verdict.checksPassed, removalGuard.now());
27562
+ if (!await appendRemovalRecord(removalGuard.journalPath, record, log)) return {
27563
+ admitted: false,
27564
+ reason: "removal-record-unwritten"
27594
27565
  };
27595
- return okResult("");
27566
+ return { admitted: true };
27596
27567
  }
27597
- const stageIsolatedCheckoutQueued = serialized(stageIsolatedCheckoutBody);
27598
- async function stageIsolatedCheckout(args) {
27599
- const refusal = isolatedCheckoutRefusal(args);
27600
- if (refusal) return refusal;
27601
- const hydrated = await hydrateCheckoutTree(args.projectPath, args.sha ?? "");
27602
- if (!hydrated.ok) return {
27603
- ok: false,
27604
- out: "",
27605
- err: hydrated.err || "the reviewed tree could not be fetched"
27606
- };
27607
- return stageIsolatedCheckoutQueued(args).catch(errResult);
27568
+ async function probeLastTouchedMs({ projectPath, path: targetPath, branch, tipSha }) {
27569
+ const touchedTimesMs = [];
27570
+ const targetStat = targetPath === null ? "missing" : await statUnlessMissing(targetPath);
27571
+ if (targetStat === null) return null;
27572
+ if (targetPath !== null && targetStat !== "missing") {
27573
+ touchedTimesMs.push(targetStat.mtimeMs);
27574
+ const adminDir = await run(["rev-parse", "--absolute-git-dir"], targetPath);
27575
+ const adminStat = adminDir.ok ? await fsp.stat(adminDir.out).catch(() => null) : null;
27576
+ if (adminStat === null) return null;
27577
+ touchedTimesMs.push(adminStat.mtimeMs);
27578
+ }
27579
+ const commitRef = tipSha ?? (branch ? `refs/heads/${branch}` : null);
27580
+ if (commitRef !== null) {
27581
+ const commitTime = await run([
27582
+ "log",
27583
+ "-1",
27584
+ "--format=%ct",
27585
+ commitRef
27586
+ ], projectPath);
27587
+ const commitTimeMs = commitTime.ok ? parseCommitTimeMs(commitTime.out) : null;
27588
+ if (commitTimeMs === null) return null;
27589
+ touchedTimesMs.push(commitTimeMs);
27590
+ }
27591
+ if (touchedTimesMs.length === 0) return null;
27592
+ return Math.max(...touchedTimesMs);
27608
27593
  }
27609
- async function mergeFastForwardToBody({ projectPath, expectedHead, sha, timeoutMs }) {
27610
- if (normalizeSha(sha) !== sha) return {
27611
- ok: false,
27612
- out: "",
27613
- err: "a fast-forward merge needs a 40 lowercase hexadecimal target sha",
27614
- sampledHead: null,
27615
- outcome: "invalid-target-sha"
27616
- };
27617
- const commandOptions = timeoutMs ? { timeout: timeoutMs } : void 0;
27618
- const head = await run(["rev-parse", "HEAD"], projectPath, commandOptions);
27619
- if (!head.ok || !head.out) return {
27620
- ...head,
27621
- ok: false,
27622
- sampledHead: null,
27623
- outcome: "head-unreadable"
27624
- };
27625
- if (head.out !== expectedHead) return {
27626
- ok: false,
27627
- out: "",
27628
- err: `HEAD changed from ${expectedHead ?? "unknown"} to ${head.out}`,
27629
- sampledHead: head.out,
27630
- outcome: "head-mismatch"
27631
- };
27632
- const merged = await run([
27633
- "merge",
27634
- "--ff-only",
27635
- sha
27636
- ], projectPath, commandOptions);
27637
- return {
27638
- ...merged,
27639
- sampledHead: head.out,
27640
- outcome: merged.ok ? "merged" : "merge-failed"
27641
- };
27594
+ async function recordOwnedFolder({ folderPath, owner }) {
27595
+ await opts.ownedPaths?.record({
27596
+ path: folderPath,
27597
+ owner,
27598
+ kind: "folder",
27599
+ projectPath: null,
27600
+ branch: null
27601
+ });
27642
27602
  }
27643
- const mergeFastForwardTo = admitted(mergeFastForwardToBody, (args) => ({
27644
- ok: false,
27645
- out: "",
27646
- err: `the git queue did not admit the merge within ${args.admissionTimeoutMs}ms`,
27647
- sampledHead: null,
27648
- outcome: "queue-admission-timed-out"
27649
- }));
27650
- async function resetKeepToBody({ projectPath, expectedHead, sha, timeoutMs }) {
27651
- if (normalizeSha(sha) !== sha) return {
27652
- ok: false,
27653
- out: "",
27654
- err: "a keep reset needs a 40 lowercase hexadecimal target sha"
27603
+ async function pruneWorktreeEntries(runGitInProject) {
27604
+ const listed = await runGitInProject([
27605
+ "worktree",
27606
+ "list",
27607
+ "--porcelain"
27608
+ ]);
27609
+ for (const lockedPath of listed.ok ? listOwnLockedWorktreePaths(listed.out, glimmervoidHomes) : []) {
27610
+ if (await directoryExists$1(lockedPath) || !await directoryExists$1(glimmervoidHome)) continue;
27611
+ await runGitInProject([
27612
+ "worktree",
27613
+ "unlock",
27614
+ lockedPath
27615
+ ]);
27616
+ }
27617
+ return runGitInProject(["worktree", "prune"]);
27618
+ }
27619
+ async function createBody({ projectPath, owner, teamId, label, baseBranch = null, configuredIntegrationBranch = null, forkFromHead = false, worktreeBase, shareList }) {
27620
+ const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
27621
+ if (!inside.ok || inside.out !== "true") return {
27622
+ cwd: projectPath,
27623
+ isGit: false
27655
27624
  };
27656
- const commandOptions = timeoutMs ? { timeout: timeoutMs } : void 0;
27657
- const head = await run(["rev-parse", "HEAD"], projectPath, commandOptions);
27658
- if (!head.ok || !head.out) return {
27659
- ...head,
27660
- ok: false
27625
+ const head = await run(["rev-parse", "HEAD"], projectPath);
27626
+ if (!head.ok) return {
27627
+ cwd: projectPath,
27628
+ isGit: false
27661
27629
  };
27662
- if (head.out !== expectedHead) return {
27663
- ok: false,
27664
- out: "",
27665
- err: `HEAD changed from ${expectedHead ?? "unknown"} to ${head.out}`
27630
+ if (rerereEnabled) {
27631
+ const configured = await run([
27632
+ "config",
27633
+ "--get",
27634
+ "rerere.enabled"
27635
+ ], projectPath);
27636
+ if (!configured.ok || configured.out === "") await run([
27637
+ "config",
27638
+ "rerere.enabled",
27639
+ "true"
27640
+ ], projectPath);
27641
+ }
27642
+ const branch = `glimmervoid/${sanitizeWorktreeName(teamId)}/${sanitizeWorktreeName(label)}`;
27643
+ await pruneWorktreeEntries(runInProject(projectPath));
27644
+ const listed = await run([
27645
+ "worktree",
27646
+ "list",
27647
+ "--porcelain"
27648
+ ], projectPath);
27649
+ if (listed.ok) {
27650
+ const conflictPath = findWorktreeForBranch(listed.out, branch);
27651
+ if (conflictPath) return {
27652
+ cwd: projectPath,
27653
+ isGit: false,
27654
+ reason: "branch-in-use",
27655
+ conflictPath,
27656
+ branch,
27657
+ base: (await migrateMarkerBase(projectPath, branch, baseBranch, configuredIntegrationBranch)).base
27658
+ };
27659
+ }
27660
+ let base = (await run([
27661
+ "rev-parse",
27662
+ "--abbrev-ref",
27663
+ "HEAD"
27664
+ ], projectPath)).out || "HEAD";
27665
+ if (!forkFromHead) base = baseBranch || await detectDefaultBranch({ projectPath });
27666
+ if (!base) return {
27667
+ cwd: projectPath,
27668
+ isGit: false,
27669
+ reason: "no-base-branch"
27666
27670
  };
27667
- return run([
27668
- "reset",
27669
- "--keep",
27670
- sha
27671
- ], projectPath, commandOptions);
27672
- }
27673
- async function classifyRefusedSync({ projectPath, branch, localRef, localSha, remoteSha, err }) {
27674
- const current = await run([
27671
+ const ref = forkFromHead ? head : await run([
27675
27672
  "rev-parse",
27676
27673
  "--verify",
27677
27674
  "--quiet",
27678
- localRef
27675
+ `refs/heads/${base}`
27679
27676
  ], projectPath);
27680
- const currentSha = current.ok && current.out ? current.out : localSha;
27681
- let ancestry = null;
27682
- if (currentSha && remoteSha && currentSha !== remoteSha) ancestry = (await probeBaseAncestry(projectPath, currentSha, remoteSha)).ancestry;
27683
- const checkout = await readRefusedCheckoutTree(projectPath, branch);
27684
- const { outcome } = classifyRefusedIntegrationSync({
27685
- currentSha,
27686
- remoteSha,
27687
- ancestry,
27688
- checkoutTree: checkout.state
27689
- });
27690
- if (outcome !== "update-failed") return {
27691
- outcome,
27692
- from: currentSha,
27693
- to: remoteSha
27694
- };
27695
- return {
27696
- outcome,
27697
- from: currentSha,
27698
- to: remoteSha,
27699
- error: firstGitErrorLine(err || checkout.error)
27677
+ const baseSha = ref.ok ? ref.out : await ensureLocalBranch(projectPath, base);
27678
+ if (!baseSha) return {
27679
+ cwd: projectPath,
27680
+ isGit: false,
27681
+ reason: "no-base-branch"
27700
27682
  };
27701
- }
27702
- async function probeBaseAncestry(projectPath, localSha, remoteSha) {
27703
- const forward = await isAncestor({
27683
+ await deleteStaleSessionBranch(projectPath, branch);
27684
+ if (worktreeBase) try {
27685
+ fs.mkdirSync(worktreeBase, { recursive: true });
27686
+ } catch {}
27687
+ const location = sessionWorktreeLocation(projectPath, teamId, worktreeBase);
27688
+ const wtDir = mkdtemp(path.join(location.parent, location.prefix));
27689
+ const add = await addWorktreeEntry(runInProject(projectPath), wtDir, [
27690
+ "-b",
27691
+ branch,
27692
+ wtDir,
27693
+ baseSha
27694
+ ], {
27695
+ owner,
27704
27696
  projectPath,
27705
- ancestorSha: localSha,
27706
- descendantSha: remoteSha
27697
+ branch
27707
27698
  });
27708
- if (!forward.ok) return {
27709
- ancestry: null,
27710
- error: forward.err ?? ""
27711
- };
27712
- if (forward.isAncestor) return {
27713
- ancestry: "behind",
27714
- error: ""
27715
- };
27716
- const reverse = await isAncestor({
27699
+ if (!add.ok) {
27700
+ try {
27701
+ fs.rmSync(wtDir, {
27702
+ recursive: true,
27703
+ force: true
27704
+ });
27705
+ } catch {}
27706
+ return {
27707
+ cwd: projectPath,
27708
+ isGit: false,
27709
+ error: add.err
27710
+ };
27711
+ }
27712
+ await run([
27713
+ "config",
27714
+ markerKey(branch),
27715
+ base
27716
+ ], projectPath);
27717
+ await populateShare({
27717
27718
  projectPath,
27718
- ancestorSha: remoteSha,
27719
- descendantSha: localSha
27719
+ wtDir,
27720
+ shareList
27720
27721
  });
27721
- if (reverse.ok && reverse.isAncestor) return {
27722
- ancestry: "ahead",
27723
- error: ""
27724
- };
27725
27722
  return {
27726
- ancestry: "forked",
27727
- error: ""
27723
+ cwd: wtDir,
27724
+ isGit: true,
27725
+ branch,
27726
+ base,
27727
+ baseSha
27728
27728
  };
27729
27729
  }
27730
- async function readRefusedCheckoutTree(projectPath, branch) {
27730
+ async function populateShare({ projectPath, wtDir, shareList, keepTrackableLinks = false }) {
27731
+ if (!wtDir) return;
27732
+ const expandedShareList = await expandShareListIn(projectPath, shareList);
27733
+ const projectRealPath = await fs.promises.realpath(projectPath).catch(() => null);
27734
+ if (projectRealPath) removeWorktreeLinks(wtDir, {
27735
+ projectRealPath,
27736
+ shareList: expandedShareList
27737
+ });
27738
+ if (!expandedShareList.length) return;
27739
+ const ignored = [];
27740
+ for (const rel of expandedShareList) if (rel && !String(rel).includes("..") && (await run([
27741
+ "check-ignore",
27742
+ "-q",
27743
+ "--",
27744
+ rel
27745
+ ], projectPath)).ok) ignored.push(rel);
27746
+ if (!ignored.length) return;
27747
+ try {
27748
+ await populateWorktree(projectPath, wtDir, ignored);
27749
+ } catch {}
27750
+ if (keepTrackableLinks) return;
27751
+ await refuseTrackableLinks(wtDir, ignored);
27752
+ }
27753
+ async function ensureWorkspaceMemberBody({ projectPath, owner, wtDir, branch, shareList }) {
27754
+ if (!wtDir || !branch) return {
27755
+ cwd: projectPath,
27756
+ isGit: false,
27757
+ reason: "missing-workspace-member"
27758
+ };
27759
+ const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
27760
+ if (!inside.ok || inside.out !== "true") return {
27761
+ cwd: projectPath,
27762
+ isGit: false,
27763
+ reason: "not-git"
27764
+ };
27765
+ await pruneWorktreeEntries(runInProject(projectPath));
27731
27766
  const listed = await run([
27732
27767
  "worktree",
27733
27768
  "list",
27734
27769
  "--porcelain"
27735
- ], projectPath);
27736
- if (!listed.ok) return {
27737
- state: "unknown",
27738
- error: listed.err ?? ""
27739
- };
27740
- const checkoutPath = findWorktreeForBranch(listed.out, branch);
27741
- if (!checkoutPath) return {
27742
- state: null,
27743
- error: ""
27744
- };
27745
- return readCheckoutTree(checkoutPath);
27746
- }
27747
- async function readCheckoutTree(worktreePath) {
27748
- const status = await run([
27749
- "--no-optional-locks",
27750
- "status",
27751
- "--porcelain",
27752
- "--untracked-files=no"
27753
- ], worktreePath);
27754
- if (!status.ok) return {
27755
- state: "unknown",
27756
- error: status.err ?? ""
27757
- };
27758
- return {
27759
- state: status.out === "" ? "clean" : "dirty",
27760
- error: ""
27761
- };
27762
- }
27763
- async function findLocalFilesAddedUpstream({ checkoutPath, localSha, remoteSha }) {
27764
- const added = await run([
27765
- "diff",
27766
- "--name-only",
27767
- "--no-renames",
27768
- "--diff-filter=A",
27769
- "-z",
27770
- localSha,
27771
- remoteSha
27772
- ], checkoutPath);
27773
- if (!added.ok) return {
27774
- ok: false,
27775
- err: added.err ?? ""
27776
- };
27777
- const addedPaths = added.out.split("\0").filter(Boolean);
27778
- const collidingPaths = [];
27779
- for (const addedPath of addedPaths) if (await fsp.lstat(path.join(checkoutPath, addedPath)).then(() => true, (error) => !isMissingFileError(error, { includeNotDir: false }))) collidingPaths.push(addedPath);
27780
- return {
27781
- ok: true,
27782
- collidingPaths
27783
- };
27784
- }
27785
- async function fastForwardCheckout({ checkoutPath, branch, localSha, remoteSha }) {
27786
- const refused = (error) => ({
27787
- outcome: "update-failed",
27788
- from: localSha,
27789
- to: remoteSha,
27790
- error
27791
- });
27792
- const headBranch = await run([
27793
- "symbolic-ref",
27794
- "--quiet",
27795
- "--short",
27796
- "HEAD"
27797
- ], checkoutPath);
27798
- if (!headBranch.ok || headBranch.out !== branch) return refused(`${checkoutPath} no longer has ${branch} checked out`);
27799
- const collisions = await findLocalFilesAddedUpstream({
27800
- checkoutPath,
27801
- localSha,
27802
- remoteSha
27803
- });
27804
- if (!collisions.ok) return refused(firstGitErrorLine(collisions.err));
27805
- if (collisions.collidingPaths.length > 0) return refused(`fast-forward would overwrite local file ${collisions.collidingPaths.join(", ")}`);
27806
- const merged = await run([
27807
- "merge",
27808
- "--ff-only",
27809
- remoteSha
27810
- ], checkoutPath);
27811
- if (merged.ok) return {
27812
- outcome: "updated",
27813
- from: localSha,
27814
- to: remoteSha
27815
- };
27816
- return refused(firstGitErrorLine(merged.err ?? ""));
27817
- }
27818
- async function syncIntegrationBranchBody({ projectPath, branch }) {
27819
- if (!await hasOriginRemote(projectPath)) return {
27820
- outcome: "no-remote",
27821
- from: null,
27822
- to: null
27823
- };
27824
- const localRef = `refs/heads/${branch}`;
27825
- const remoteRef = `refs/remotes/origin/${branch}`;
27826
- if (!(await run([
27827
- "fetch",
27828
- "--prune",
27829
- "origin",
27830
- "+refs/heads/*:refs/remotes/origin/*"
27831
- ], projectPath, {
27832
- timeout: 8e3,
27833
- env: { GIT_TERMINAL_PROMPT: "0" }
27834
- })).ok) return {
27835
- outcome: "fetch-failed",
27836
- from: null,
27837
- to: null
27770
+ ], projectPath);
27771
+ if (!listed.ok) return {
27772
+ cwd: projectPath,
27773
+ isGit: false,
27774
+ error: listed.err
27838
27775
  };
27839
- const local = await run([
27776
+ const conflictPath = findWorktreeForBranch(listed.out, branch);
27777
+ if (conflictPath && !isSameDirectoryPath(conflictPath, wtDir)) return {
27778
+ cwd: projectPath,
27779
+ isGit: false,
27780
+ reason: "branch-in-use",
27781
+ conflictPath,
27782
+ branch
27783
+ };
27784
+ const base = await detectDefaultBranch({ projectPath });
27785
+ if (conflictPath) {
27786
+ await populateShare({
27787
+ projectPath,
27788
+ wtDir,
27789
+ shareList
27790
+ });
27791
+ return {
27792
+ cwd: wtDir,
27793
+ isGit: true,
27794
+ branch,
27795
+ base
27796
+ };
27797
+ }
27798
+ if ((await run([
27840
27799
  "rev-parse",
27841
27800
  "--verify",
27842
27801
  "--quiet",
27843
- localRef
27844
- ], projectPath);
27845
- const remote = await run([
27802
+ `refs/heads/${branch}`
27803
+ ], projectPath)).ok) {
27804
+ const attached = await addWorktreeEntry(runInProject(projectPath), wtDir, [wtDir, branch], {
27805
+ owner,
27806
+ projectPath,
27807
+ branch
27808
+ });
27809
+ if (!attached.ok) return {
27810
+ cwd: projectPath,
27811
+ isGit: false,
27812
+ reason: "worktree-add-failed",
27813
+ error: attached.err
27814
+ };
27815
+ await populateShare({
27816
+ projectPath,
27817
+ wtDir,
27818
+ shareList
27819
+ });
27820
+ return {
27821
+ cwd: wtDir,
27822
+ isGit: true,
27823
+ branch,
27824
+ base
27825
+ };
27826
+ }
27827
+ if (!base) return {
27828
+ cwd: projectPath,
27829
+ isGit: false,
27830
+ reason: "no-base-branch"
27831
+ };
27832
+ const synced = await syncIntegrationBranchBody({
27833
+ projectPath,
27834
+ branch: base
27835
+ });
27836
+ if (synced.outcome === "fetch-failed" || synced.outcome === "update-failed") return {
27837
+ cwd: projectPath,
27838
+ isGit: false,
27839
+ reason: "base-sync-failed",
27840
+ error: synced.error
27841
+ };
27842
+ const baseRef = await run([
27846
27843
  "rev-parse",
27847
27844
  "--verify",
27848
27845
  "--quiet",
27849
- remoteRef
27846
+ `refs/heads/${base}`
27850
27847
  ], projectPath);
27851
- const localSha = local.ok ? local.out : null;
27852
- const remoteSha = remote.ok ? remote.out : null;
27853
- let ancestry = null;
27854
- let syncError = "";
27855
- let checkedOut = false;
27856
- let checkoutPath = null;
27857
- let checkoutTree = "unknown";
27858
- if (localSha && remoteSha && localSha !== remoteSha) {
27859
- const probe = await probeBaseAncestry(projectPath, localSha, remoteSha);
27860
- ancestry = probe.ancestry;
27861
- syncError = probe.error;
27862
- if (ancestry === "behind") {
27863
- const listed = await run([
27864
- "worktree",
27865
- "list",
27866
- "--porcelain"
27867
- ], projectPath);
27868
- if (!listed.ok) syncError = listed.err ?? "";
27869
- checkoutPath = listed.ok ? findWorktreeForBranch(listed.out, branch ?? "") : null;
27870
- checkedOut = !listed.ok || Boolean(checkoutPath);
27871
- if (checkoutPath) {
27872
- const tree = await readCheckoutTree(checkoutPath);
27873
- checkoutTree = tree.state;
27874
- syncError = tree.error;
27875
- }
27876
- }
27877
- }
27878
- const decision = decideIntegrationSync({
27879
- localSha,
27880
- remoteSha,
27881
- ancestry,
27882
- checkedOut,
27883
- checkoutTree
27884
- });
27885
- if (decision.outcome === "update-failed") return {
27886
- outcome: decision.outcome,
27887
- from: localSha,
27888
- to: remoteSha,
27889
- error: firstGitErrorLine(syncError)
27848
+ const baseSha = baseRef.ok ? baseRef.out : await ensureLocalBranch(projectPath, base);
27849
+ if (!baseSha) return {
27850
+ cwd: projectPath,
27851
+ isGit: false,
27852
+ reason: "no-base-branch"
27890
27853
  };
27891
- if (decision.action === "update-checkout" && checkoutPath && localSha && remoteSha) return fastForwardCheckout({
27892
- checkoutPath,
27893
- branch: branch ?? "",
27894
- localSha,
27895
- remoteSha
27854
+ const added = await addWorktreeEntry(runInProject(projectPath), wtDir, [
27855
+ "-b",
27856
+ branch,
27857
+ wtDir,
27858
+ baseSha
27859
+ ], {
27860
+ owner,
27861
+ projectPath,
27862
+ branch
27896
27863
  });
27897
- if (decision.action !== "update") return {
27898
- outcome: decision.outcome,
27899
- from: localSha,
27900
- to: remoteSha
27901
- };
27902
- const updated = await fastForwardTarget(projectPath, remoteRef, branch ?? "", false);
27903
- if (updated.ok) return {
27904
- outcome: "updated",
27905
- from: localSha,
27906
- to: remoteSha
27864
+ if (!added.ok) return {
27865
+ cwd: projectPath,
27866
+ isGit: false,
27867
+ reason: "worktree-add-failed",
27868
+ error: added.err
27907
27869
  };
27908
- return classifyRefusedSync({
27870
+ await populateShare({
27909
27871
  projectPath,
27910
- branch: branch ?? "",
27911
- localRef,
27912
- localSha,
27913
- remoteSha,
27914
- err: updated.err
27872
+ wtDir,
27873
+ shareList
27915
27874
  });
27916
- }
27917
- async function listRemoteBranches({ projectPath, prefixes }) {
27918
- if (usablePrefixes(prefixes).length === 0) return {
27919
- ok: true,
27920
- branches: []
27921
- };
27922
- const listed = await run([
27923
- "for-each-ref",
27924
- REMOTE_REF_PREFIX,
27925
- "--format=%(refname) %(objectname) %(committerdate:unix) %(symref)"
27926
- ], projectPath, { maxBuffer: REMOTE_BRANCH_LISTING_MAX_BUFFER });
27927
- if (!listed.ok) return listed;
27928
- const branches = [];
27929
- for (const line of listed.out.split(/\r?\n/)) {
27930
- if (!line) continue;
27931
- const [refName, tipSha, commitTimeSeconds, symbolicTarget] = line.trim().split(/\s+/);
27932
- if (symbolicTarget) continue;
27933
- if (!refName.startsWith(REMOTE_REF_PREFIX)) continue;
27934
- const name = refName.slice(20);
27935
- if (matchedPrefix(name, prefixes) === null) continue;
27936
- branches.push({
27937
- name,
27938
- tipSha,
27939
- tipCommitTimeMs: Number.parseInt(commitTimeSeconds, 10) * 1e3
27940
- });
27941
- }
27942
27875
  return {
27943
- ok: true,
27944
- branches
27876
+ cwd: wtDir,
27877
+ isGit: true,
27878
+ branch,
27879
+ base,
27880
+ baseSha
27945
27881
  };
27946
27882
  }
27947
- async function listIntegrationTips({ projectPath, integrationBranch }) {
27948
- const detectedBranch = integrationBranch || await detectDefaultBranch({ projectPath });
27949
- const branchNames = [...new Set([
27950
- detectedBranch,
27951
- "main",
27952
- "master"
27953
- ].filter((name) => Boolean(name)))];
27954
- const refNames = branchNames.flatMap((branchName) => [`refs/remotes/origin/${branchName}`, `refs/heads/${branchName}`]);
27955
- const listed = await run([
27956
- "for-each-ref",
27957
- ...refNames,
27958
- "--format=%(refname) %(objectname)"
27959
- ], projectPath);
27960
- if (!listed.ok) return listed;
27961
- const shaByRef = /* @__PURE__ */ new Map();
27962
- for (const line of listed.out.split(/\r?\n/)) {
27963
- if (!line) continue;
27964
- const [refName, sha] = line.trim().split(/\s+/);
27965
- if (refNames.includes(refName)) shaByRef.set(refName, sha);
27883
+ async function refuseTrackableLinks(wtDir, entries) {
27884
+ for (const rel of entries) {
27885
+ if ((await run([
27886
+ "check-ignore",
27887
+ "-q",
27888
+ "--",
27889
+ rel
27890
+ ], wtDir)).ok) continue;
27891
+ const target = path.join(wtDir, rel);
27892
+ const stat = await fsp.lstat(target).catch(() => null);
27893
+ if (!stat || !stat.isSymbolicLink()) continue;
27894
+ console.warn(`[git-workspace] not sharing ${rel}: git does not ignore it as a link, so a commit in the worktree would carry it (use a slash-free .gitignore entry)`);
27895
+ try {
27896
+ await fsp.rm(target, { force: true });
27897
+ } catch {}
27966
27898
  }
27967
- const integrationTips = [];
27968
- for (const branch of branchNames) {
27969
- const sha = shaByRef.get(`refs/remotes/origin/${branch}`) || shaByRef.get(`refs/heads/${branch}`);
27970
- integrationTips.push({
27971
- branch,
27972
- sha: sha || null
27973
- });
27899
+ }
27900
+ async function deleteStaleSessionBranch(projectPath, branch) {
27901
+ if (!(await readLocalBranchSha(projectPath, branch)).out) return;
27902
+ if (!(await admitRemoval({
27903
+ cause: "session-create",
27904
+ kind: "local-branch",
27905
+ projectPath,
27906
+ path: null,
27907
+ branch
27908
+ })).admitted) return;
27909
+ await run([
27910
+ "branch",
27911
+ "-D",
27912
+ branch
27913
+ ], projectPath);
27914
+ }
27915
+ async function tearDownWorktree(projectPath, wt, branch) {
27916
+ if (!(await admitRemoval({
27917
+ cause: "merge",
27918
+ kind: "worktree",
27919
+ projectPath,
27920
+ path: wt,
27921
+ branch: branch ?? null
27922
+ })).admitted) return;
27923
+ removeWorktreeLinks(wt);
27924
+ await removeWorktreeEntry(runInProject(projectPath), wt, ["--force"]);
27925
+ await pruneWorktreeEntries(runInProject(projectPath));
27926
+ if (branch) await run([
27927
+ "branch",
27928
+ "-D",
27929
+ branch
27930
+ ], projectPath);
27931
+ }
27932
+ async function discardBody({ projectPath, workspace, cause }) {
27933
+ if (!workspace || !workspace.isGit) return;
27934
+ if (!(await admitRemoval({
27935
+ cause,
27936
+ kind: "worktree",
27937
+ projectPath,
27938
+ path: workspace.cwd || null,
27939
+ branch: workspace.branch || null
27940
+ })).admitted) return;
27941
+ if (workspace.cwd) {
27942
+ removeWorktreeLinks(workspace.cwd);
27943
+ await removeWorktreeEntry(runInProject(projectPath), workspace.cwd, ["--force"]);
27974
27944
  }
27975
- return {
27976
- ok: true,
27977
- integrationTips
27978
- };
27945
+ if (workspace.branch) await run([
27946
+ "branch",
27947
+ "-D",
27948
+ workspace.branch
27949
+ ], projectPath);
27950
+ await pruneWorktreeEntries(runInProject(projectPath));
27979
27951
  }
27980
- async function isAncestor({ projectPath, ancestorSha, descendantSha }) {
27981
- try {
27982
- await git([
27983
- "merge-base",
27984
- "--is-ancestor",
27985
- ancestorSha ?? "",
27986
- descendantSha ?? ""
27987
- ], projectPath);
27988
- return {
27989
- ok: true,
27990
- isAncestor: true
27991
- };
27992
- } catch (err) {
27993
- if (errorExitCode(err) === 1) return {
27994
- ok: true,
27995
- isAncestor: false
27996
- };
27997
- return {
27998
- ...errResult(err),
27999
- isAncestor: false
28000
- };
27952
+ function runUntrusted(args, cwd, { disableHooks, disableRepoCommands, replaceEnv }) {
27953
+ return run(disableHooks ? [
27954
+ "-c",
27955
+ `core.hooksPath=${os.devNull}`,
27956
+ ...args
27957
+ ] : args, cwd, {
27958
+ replaceEnv,
27959
+ disableRepoCommands
27960
+ });
27961
+ }
27962
+ async function removeWorktreeByPathBody({ projectPath, cwd, branch, cause, disableHooks, replaceEnv }) {
27963
+ const admission = await admitRemoval({
27964
+ cause,
27965
+ kind: cwd ? "worktree" : "local-branch",
27966
+ projectPath,
27967
+ path: cwd || null,
27968
+ branch: branch || null
27969
+ });
27970
+ if (!admission.admitted) return keptRemovalResult(admission.reason);
27971
+ const isolation = {
27972
+ disableHooks,
27973
+ replaceEnv
27974
+ };
27975
+ let failure = null;
27976
+ if (cwd) {
27977
+ removeWorktreeLinks(cwd);
27978
+ const removed = await removeWorktreeEntry((args) => runUntrusted(args, projectPath, isolation), cwd, ["--force"]);
27979
+ if (!removed.ok) failure = removed;
27980
+ }
27981
+ if (branch) {
27982
+ const deleted = await runUntrusted([
27983
+ "branch",
27984
+ "-D",
27985
+ branch
27986
+ ], projectPath, isolation);
27987
+ if (!deleted.ok && failure === null) failure = deleted;
28001
27988
  }
27989
+ await pruneWorktreeEntries((args) => runUntrusted(args, projectPath, isolation));
27990
+ return failure ?? okResult("");
28002
27991
  }
28003
- async function readGitConfigValues(args, projectPath, timeoutMs, replaceEnv) {
27992
+ async function readLocalBranchSha(projectPath, branch) {
28004
27993
  try {
28005
- return okResult(await git(["config", ...args], projectPath, {
28006
- timeout: timeoutMs,
28007
- ...replaceEnv ? { replaceEnv } : {}
28008
- }));
27994
+ return okResult(await git([
27995
+ "rev-parse",
27996
+ "--verify",
27997
+ "--quiet",
27998
+ `refs/heads/${branch}`
27999
+ ], projectPath));
28009
28000
  } catch (err) {
28010
28001
  if (errorExitCode(err) === 1) return okResult("");
28011
28002
  return errResult(err);
28012
28003
  }
28013
28004
  }
28014
- async function resolveMergeProbeEnv({ projectPath, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
28015
- const safeDirectories = await readGitConfigValues(["--get-all", "safe.directory"], projectPath, timeoutMs);
28016
- if (!safeDirectories.ok) return {
28005
+ async function discardSessionBranchBody({ projectPath, teamId = "", label = "", worktreeBase, disableHooks, replaceEnv }) {
28006
+ const branch = `glimmervoid/${sanitizeWorktreeName(teamId)}/${sanitizeWorktreeName(label)}`;
28007
+ const existingBranch = await readLocalBranchSha(projectPath, branch);
28008
+ if (!existingBranch.ok) return existingBranch;
28009
+ if (existingBranch.out === "") return okResult("");
28010
+ const listed = await run([
28011
+ "worktree",
28012
+ "list",
28013
+ "--porcelain"
28014
+ ], projectPath);
28015
+ if (!listed.ok) return listed;
28016
+ const worktreePath = findWorktreeForBranch(listed.out, branch);
28017
+ if (worktreePath === null) return removeWorktreeByPathBody({
28018
+ projectPath,
28019
+ branch,
28020
+ cause: "session",
28021
+ disableHooks,
28022
+ replaceEnv
28023
+ });
28024
+ const refusal = await foreignSessionWorktreeReason(worktreePath, listed.out, sessionWorktreeLocation(projectPath, teamId, worktreeBase));
28025
+ if (refusal !== null) return {
28017
28026
  ok: false,
28018
- err: safeDirectories.err || "reading safe.directory failed"
28027
+ out: "",
28028
+ err: refusal
28019
28029
  };
28020
- const neutralEnv = neutralGitConfigEnv(process.env, os.devNull);
28021
- const safeDirectoryOutput = safeDirectories.out;
28022
- const configuredKeys = await readGitConfigValues([
28023
- "--name-only",
28024
- "--get-regexp",
28025
- MERGE_DRIVER_KEY_PATTERN
28026
- ], projectPath, timeoutMs, driverEnumerationEnv({
28027
- neutralEnv,
28028
- safeDirectoryOutput
28030
+ return removeWorktreeByPathBody({
28031
+ projectPath,
28032
+ cwd: worktreePath,
28033
+ branch,
28034
+ cause: "session",
28035
+ disableHooks,
28036
+ replaceEnv
28037
+ });
28038
+ }
28039
+ async function pruneWorktreesBody({ projectPath, disableHooks, replaceEnv }) {
28040
+ return pruneWorktreeEntries((args) => runUntrusted(args, projectPath, {
28041
+ disableHooks,
28042
+ replaceEnv
28029
28043
  }));
28030
- if (!configuredKeys.ok) return {
28044
+ }
28045
+ async function removeSharedLinks(wtDir, shareList) {
28046
+ for (const rel of await expandShareListIn(wtDir, shareList)) {
28047
+ if (!rel || String(rel).includes("..")) continue;
28048
+ const linkPath = path.join(wtDir, rel);
28049
+ const stat = await fsp.lstat(linkPath).catch(() => null);
28050
+ if (!stat || !stat.isSymbolicLink()) continue;
28051
+ if (!(await run([
28052
+ "check-ignore",
28053
+ "-q",
28054
+ "--",
28055
+ rel
28056
+ ], wtDir)).ok) continue;
28057
+ await fsp.rm(linkPath, {
28058
+ recursive: false,
28059
+ force: true
28060
+ }).catch(() => fsp.rmdir(linkPath)).catch(() => {});
28061
+ }
28062
+ }
28063
+ async function removeWorkspaceMemberBody({ projectPath, cwd, branch, shareList, cause, discardWork = false }) {
28064
+ if (!cwd) return {
28031
28065
  ok: false,
28032
- err: configuredKeys.err || "enumerating merge drivers failed"
28066
+ out: "",
28067
+ err: "a workspace member removal needs a path"
28033
28068
  };
28034
- return {
28069
+ const admission = await admitRemoval({
28070
+ cause,
28071
+ kind: "worktree",
28072
+ projectPath,
28073
+ path: cwd,
28074
+ branch: branch || null
28075
+ });
28076
+ if (!admission.admitted) return keptRemovalResult(admission.reason);
28077
+ await removeSharedLinks(cwd, shareList);
28078
+ const removed = await removeWorktreeEntry(runInProject(projectPath), cwd, discardWork ? ["--force", "--force"] : []);
28079
+ if (discardWork && await directoryExists$1(cwd)) await fsp.rm(cwd, {
28080
+ recursive: true,
28081
+ force: true
28082
+ });
28083
+ await pruneWorktreeEntries(runInProject(projectPath));
28084
+ await forgetRemovedPath(cwd);
28085
+ if (discardWork && !await directoryExists$1(cwd)) return {
28035
28086
  ok: true,
28036
- probeEnv: mergeProbeEnv({
28037
- neutralEnv,
28038
- safeDirectoryOutput,
28039
- configuredKeysOutput: configuredKeys.out
28040
- })
28087
+ out: removed.out
28041
28088
  };
28089
+ return removed;
28042
28090
  }
28043
- async function writeMergedTree({ projectPath, integrationSha, branchSha, probeEnv, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
28044
- try {
28045
- return {
28046
- ...okResult(await git([
28047
- "merge-tree",
28048
- "--write-tree",
28049
- "--allow-unrelated-histories",
28050
- integrationSha,
28051
- branchSha
28052
- ], projectPath, {
28053
- timeout: timeoutMs,
28054
- replaceEnv: probeEnv
28055
- })),
28056
- outcome: "tree"
28057
- };
28058
- } catch (err) {
28059
- if (errorExitCode(err) === 1) return {
28060
- ...errResult(err),
28061
- outcome: "conflicts"
28062
- };
28063
- return {
28064
- ...errResult(err),
28065
- outcome: "failed"
28066
- };
28067
- }
28091
+ async function listWorktreeBranches({ projectPath }) {
28092
+ const inside = await run(["rev-parse", "--is-inside-work-tree"], projectPath);
28093
+ if (!inside.ok || inside.out !== "true") return [];
28094
+ const listed = await run([
28095
+ "worktree",
28096
+ "list",
28097
+ "--porcelain"
28098
+ ], projectPath);
28099
+ if (!listed.ok) return [];
28100
+ return parseWorktreeBranches(listed.out);
28068
28101
  }
28069
- async function treeOid({ projectPath, sha, timeoutMs = MERGE_PROBE_TIMEOUT_MS }) {
28070
- return run(["rev-parse", `${sha ?? ""}^{tree}`], projectPath, { timeout: timeoutMs });
28102
+ async function stageDetachedWorktreeBody({ projectPath, worktreePath, sha, owner, disableHooks, replaceEnv }) {
28103
+ if (!worktreePath) return {
28104
+ ok: false,
28105
+ out: "",
28106
+ err: "a detached worktree needs a path"
28107
+ };
28108
+ if (normalizeSha(sha) !== sha) return {
28109
+ ok: false,
28110
+ out: "",
28111
+ err: "a detached worktree sha must be 40 lowercase hexadecimal characters"
28112
+ };
28113
+ return addWorktreeEntry((args) => runUntrusted(args, projectPath, {
28114
+ disableHooks,
28115
+ replaceEnv
28116
+ }), worktreePath, [
28117
+ "--detach",
28118
+ worktreePath,
28119
+ sha
28120
+ ], {
28121
+ owner,
28122
+ projectPath,
28123
+ branch: null
28124
+ });
28071
28125
  }
28072
28126
  async function deleteRemoteBranchBody({ projectPath, name, tipSha, cause }) {
28073
28127
  const admission = await admitRemoval({
@@ -28088,6 +28142,33 @@ function createGitWorkspace(opts = {}) {
28088
28142
  `:${branchRef}`
28089
28143
  ], projectPath);
28090
28144
  }
28145
+ const context = {
28146
+ git,
28147
+ run,
28148
+ runInProject,
28149
+ runUntrusted,
28150
+ log,
28151
+ rerereEnabled,
28152
+ serialized,
28153
+ admitted,
28154
+ worktrees: {
28155
+ listWorktreePorcelain: (projectPath) => run([
28156
+ "worktree",
28157
+ "list",
28158
+ "--porcelain"
28159
+ ], projectPath),
28160
+ lockReusedHomeWorktrees,
28161
+ tearDownWorktree
28162
+ }
28163
+ };
28164
+ const origin = createOriginOps(context);
28165
+ const rebase = createRebaseOps(context, origin);
28166
+ const probe = createProbeOps(context, origin);
28167
+ const integration = createIntegrationOps(context, origin, rebase);
28168
+ const { detectDefaultBranch, migrateMarkerBase, originUrl, ensureLocalBranch, fetchOriginBody, seedBranchFromOriginBody, isAncestor, listRemoteBranches, listIntegrationTips } = origin;
28169
+ const { mergeBackBody, mergeKeepBody, rebaseOnlyBody } = rebase;
28170
+ const { describeWorkspaceMemberWorkBody, hasUnmergedWorkBody, listWorktreesBody, listSessionWorktreesBody, probeWorktreeDirtyBody } = probe;
28171
+ const { checkoutDetachedBody, stageIsolatedCheckout, mergeFastForwardTo, resetKeepToBody, syncIntegrationBranchBody, resolveMergeProbeEnv, writeMergedTree, treeOid } = integration;
28091
28172
  return {
28092
28173
  withGitIsolation: (isolation, operation) => isolationContext.run(isolation, operation),
28093
28174
  create: serialized(createBody),