glimmervoid 0.49.1-next.548 → 0.49.1-next.550

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 (87) hide show
  1. package/dist/chunks/{main-CidjjEBE.js → main-CMqiFrzy.js} +980 -923
  2. package/dist/client/assets/{benchmark-panel-D1xz_zud.js → benchmark-panel-CQ8mizq9.js} +1 -1
  3. package/dist/client/assets/benchmark-panel-CQ8mizq9.js.br +0 -0
  4. package/dist/client/assets/{boards-view-BJBub2Mv.js → boards-view-BbHv8uCT.js} +1 -1
  5. package/dist/client/assets/boards-view-BbHv8uCT.js.br +0 -0
  6. package/dist/client/assets/{community-panel-Q-unmDyL.js → community-panel-nCWdpHWp.js} +1 -1
  7. package/dist/client/assets/community-panel-nCWdpHWp.js.br +0 -0
  8. package/dist/client/assets/{dialogs-Cv_m5bzB.js → dialogs-DIOZ1Msf.js} +1 -1
  9. package/dist/client/assets/dialogs-DIOZ1Msf.js.br +0 -0
  10. package/dist/client/assets/doc-editor-ui-BUrRarmV.js +3 -0
  11. package/dist/client/assets/doc-editor-ui-BUrRarmV.js.br +0 -0
  12. package/dist/client/assets/{feature-hint-C42vDs5u.js → feature-hint-DS7G9xuv.js} +1 -1
  13. package/dist/client/assets/feature-hint-DS7G9xuv.js.br +0 -0
  14. package/dist/client/assets/{first-run-checklist-BO3Ur5ib.js → first-run-checklist-JzACzDD3.js} +1 -1
  15. package/dist/client/assets/first-run-checklist-JzACzDD3.js.br +0 -0
  16. package/dist/client/assets/{hooks-panel-CFJ_yKWj.js → hooks-panel-COiU9Vpa.js} +1 -1
  17. package/dist/client/assets/hooks-panel-COiU9Vpa.js.br +0 -0
  18. package/dist/client/assets/{index-DI2HkotS.css → index-BbVqGI9t.css} +1 -1
  19. package/dist/client/assets/index-BbVqGI9t.css.br +0 -0
  20. package/dist/client/assets/{index-BcXKUQ3i.js → index-DBngrjdD.js} +5 -5
  21. package/dist/client/assets/index-DBngrjdD.js.br +0 -0
  22. package/dist/client/assets/{issues-panel-CGnvuz3w.js → issues-panel-BMmZXv_R.js} +1 -1
  23. package/dist/client/assets/issues-panel-BMmZXv_R.js.br +0 -0
  24. package/dist/client/assets/{my-prs-panel-DVUvhdzr.js → my-prs-panel-DnjeNgSv.js} +1 -1
  25. package/dist/client/assets/my-prs-panel-DnjeNgSv.js.br +0 -0
  26. package/dist/client/assets/{nyan-cat-DeJlbM8V.js → nyan-cat-DXQF0mmg.js} +1 -1
  27. package/dist/client/assets/nyan-cat-DXQF0mmg.js.br +0 -0
  28. package/dist/client/assets/{phone-shell-DUGU-N_h.js → phone-shell-C1qjtmQI.js} +1 -1
  29. package/dist/client/assets/phone-shell-C1qjtmQI.js.br +0 -0
  30. package/dist/client/assets/{plan-face-BpLQ2IaE.js → plan-face-JniGXGjY.js} +1 -1
  31. package/dist/client/assets/plan-face-JniGXGjY.js.br +0 -0
  32. package/dist/client/assets/{plan-render-Caxt86nk.js → plan-render-B2YJ0ogb.js} +1 -1
  33. package/dist/client/assets/plan-render-B2YJ0ogb.js.br +0 -0
  34. package/dist/client/assets/{pr-queue-columns-fHCLY70x.js → pr-queue-columns-BApLH666.js} +1 -1
  35. package/dist/client/assets/pr-queue-columns-BApLH666.js.br +0 -0
  36. package/dist/client/assets/{radar-panel-Dqya-DmP.js → radar-panel-CQKiNmZs.js} +1 -1
  37. package/dist/client/assets/radar-panel-CQKiNmZs.js.br +0 -0
  38. package/dist/client/assets/{repo-roots-adder-DPYm5tbp.js → repo-roots-adder-Cn7bwH1g.js} +1 -1
  39. package/dist/client/assets/repo-roots-adder-Cn7bwH1g.js.br +0 -0
  40. package/dist/client/assets/{resume-dialog-Bujh131P.js → resume-dialog-erybBzkR.js} +1 -1
  41. package/dist/client/assets/resume-dialog-erybBzkR.js.br +0 -0
  42. package/dist/client/assets/{review-queue-panel-DvkFtACZ.js → review-queue-panel-Dqin2TUT.js} +1 -1
  43. package/dist/client/assets/review-queue-panel-Dqin2TUT.js.br +0 -0
  44. package/dist/client/assets/{settings-panel-HiJJCQLf.js → settings-panel-CMaX-olp.js} +2 -2
  45. package/dist/client/assets/settings-panel-CMaX-olp.js.br +0 -0
  46. package/dist/client/assets/{shown-face-CZZUBagh.js → shown-face-D4-VVHlN.js} +1 -1
  47. package/dist/client/assets/shown-face-D4-VVHlN.js.br +0 -0
  48. package/dist/client/assets/{team-review-panel-CpJCPT_Z.js → team-review-panel-ByY30SkE.js} +1 -1
  49. package/dist/client/assets/team-review-panel-ByY30SkE.js.br +0 -0
  50. package/dist/client/assets/{trace-panel-BcS_W6wN.js → trace-panel-CevbgI9I.js} +1 -1
  51. package/dist/client/assets/trace-panel-CevbgI9I.js.br +0 -0
  52. package/dist/client/assets/{usage-panel-BwoyCJnQ.js → usage-panel-sWKyaZpv.js} +1 -1
  53. package/dist/client/assets/usage-panel-sWKyaZpv.js.br +0 -0
  54. package/dist/client/assets/{your-day-tip-CwrVPoee.js → your-day-tip-lEQzdGa4.js} +1 -1
  55. package/dist/client/assets/your-day-tip-lEQzdGa4.js.br +0 -0
  56. package/dist/client/index.html +2 -2
  57. package/dist/client/index.html.br +0 -0
  58. package/dist/server/index.js +1 -1
  59. package/package.json +1 -1
  60. package/dist/client/assets/benchmark-panel-D1xz_zud.js.br +0 -0
  61. package/dist/client/assets/boards-view-BJBub2Mv.js.br +0 -0
  62. package/dist/client/assets/community-panel-Q-unmDyL.js.br +0 -0
  63. package/dist/client/assets/dialogs-Cv_m5bzB.js.br +0 -0
  64. package/dist/client/assets/doc-editor-ui-K7KUggug.js +0 -2
  65. package/dist/client/assets/doc-editor-ui-K7KUggug.js.br +0 -0
  66. package/dist/client/assets/feature-hint-C42vDs5u.js.br +0 -0
  67. package/dist/client/assets/first-run-checklist-BO3Ur5ib.js.br +0 -0
  68. package/dist/client/assets/hooks-panel-CFJ_yKWj.js.br +0 -0
  69. package/dist/client/assets/index-BcXKUQ3i.js.br +0 -0
  70. package/dist/client/assets/index-DI2HkotS.css.br +0 -0
  71. package/dist/client/assets/issues-panel-CGnvuz3w.js.br +0 -0
  72. package/dist/client/assets/my-prs-panel-DVUvhdzr.js.br +0 -0
  73. package/dist/client/assets/nyan-cat-DeJlbM8V.js.br +0 -0
  74. package/dist/client/assets/phone-shell-DUGU-N_h.js.br +0 -0
  75. package/dist/client/assets/plan-face-BpLQ2IaE.js.br +0 -0
  76. package/dist/client/assets/plan-render-Caxt86nk.js.br +0 -0
  77. package/dist/client/assets/pr-queue-columns-fHCLY70x.js.br +0 -0
  78. package/dist/client/assets/radar-panel-Dqya-DmP.js.br +0 -0
  79. package/dist/client/assets/repo-roots-adder-DPYm5tbp.js.br +0 -0
  80. package/dist/client/assets/resume-dialog-Bujh131P.js.br +0 -0
  81. package/dist/client/assets/review-queue-panel-DvkFtACZ.js.br +0 -0
  82. package/dist/client/assets/settings-panel-HiJJCQLf.js.br +0 -0
  83. package/dist/client/assets/shown-face-CZZUBagh.js.br +0 -0
  84. package/dist/client/assets/team-review-panel-CpJCPT_Z.js.br +0 -0
  85. package/dist/client/assets/trace-panel-BcS_W6wN.js.br +0 -0
  86. package/dist/client/assets/usage-panel-BwoyCJnQ.js.br +0 -0
  87. package/dist/client/assets/your-day-tip-CwrVPoee.js.br +0 -0
@@ -17892,42 +17892,226 @@ var SKIP_DESCRIPTIONS = {
17892
17892
  failed: "cloning node_modules from the main checkout failed; install dependencies in the worktree"
17893
17893
  };
17894
17894
  //#endregion
17895
- //#region session/session-worktree-lifecycle.ts
17896
- var WORKTREE_CHECK_DEBOUNCE_MS = 400;
17897
- var GIT_NOT_FOUND_EXIT_CODE = 1;
17898
- function workspaceMemberGit(gitWorkspace) {
17899
- if (!gitWorkspace) return null;
17900
- const { ensureWorkspaceMember, removeWorkspaceMember, describeWorkspaceMemberWork, recordOwnedFolder, forgetRemovedPath } = gitWorkspace;
17901
- if (!ensureWorkspaceMember || !removeWorkspaceMember || !describeWorkspaceMemberWork || !recordOwnedFolder || !forgetRemovedPath) return null;
17902
- return {
17903
- ensureWorkspaceMember,
17904
- removeWorkspaceMember,
17905
- describeWorkspaceMemberWork,
17906
- recordOwnedFolder,
17907
- forgetRemovedPath
17908
- };
17909
- }
17910
- async function readGitStrict(args, options) {
17911
- const command = await runGit(args, {
17912
- ...options,
17913
- trim: false
17914
- });
17915
- if (!command.ok) throw gitCommandFailure(args, command, options.timeoutMs);
17916
- return command.out;
17895
+ //#region session/worktree/worktree-provisioning.ts
17896
+ function createWorktreeProvisioning(context, deps) {
17897
+ const { id, integrationBranch, gitWorkspace, syncOnStart, worktreeRoot, worktreeShare, seedDependencies, port, workspaceMembers, lifecycleState, currentProjectPath, effectiveIntegrationBranch, setMergeStatus } = context;
17898
+ const { adoptWorktree, resolveCommonGitDir, runAutoRebase, api } = deps;
17899
+ function syncableGitWorkspace() {
17900
+ if (syncOnStart === false) return null;
17901
+ if (!gitWorkspace || typeof gitWorkspace.syncIntegrationBranch !== "function") return null;
17902
+ return gitWorkspace;
17903
+ }
17904
+ async function resolveBaseForStart() {
17905
+ const resolvedBase = effectiveIntegrationBranch();
17906
+ if (resolvedBase) return resolvedBase;
17907
+ if (!gitWorkspace || typeof gitWorkspace.detectDefaultBranch !== "function") return null;
17908
+ const detectedBase = await gitWorkspace.detectDefaultBranch({ projectPath: currentProjectPath() });
17909
+ lifecycleState.effectiveBase = detectedBase;
17910
+ return detectedBase;
17911
+ }
17912
+ async function syncIntegrationBranchForStart(trigger, branch) {
17913
+ const syncGitWorkspace = syncableGitWorkspace();
17914
+ if (!syncGitWorkspace || !branch) return null;
17915
+ try {
17916
+ const sync = await syncGitWorkspace.syncIntegrationBranch({
17917
+ projectPath: currentProjectPath(),
17918
+ branch
17919
+ });
17920
+ port.recordDecision({
17921
+ kind: "integration-sync",
17922
+ ts: Date.now(),
17923
+ decision: trigger,
17924
+ outcome: sync.outcome,
17925
+ from: sync.from,
17926
+ to: sync.to
17927
+ });
17928
+ if (sync.outcome === "fetch-failed" || sync.outcome === "update-failed") {
17929
+ const detail = sync.error ? `${sync.outcome}: ${sync.error}` : sync.outcome;
17930
+ console.warn(`[session ${id}] integration sync failed during ${trigger}: ${detail}`);
17931
+ }
17932
+ return sync;
17933
+ } catch (error) {
17934
+ console.warn(`[session ${id}] integration sync failed during ${trigger}: ${errorMessage(error)}`);
17935
+ return null;
17936
+ }
17937
+ }
17938
+ function forkSyncWarning(sync, branch) {
17939
+ if (!sync || !branch) return null;
17940
+ if (sync.outcome === "ahead") return `base ${branch} is ahead of origin/${branch} (unpushed commits); forked from local`;
17941
+ if (sync.outcome === "diverged") return `base ${branch} has diverged from origin/${branch}; forked from local`;
17942
+ if (sync.outcome === "fetch-failed") return `could not fetch origin/${branch}; forked from local`;
17943
+ if (sync.outcome === "checked-out") return `${branch} is checked out with local changes and behind origin/${branch}; forked from local`;
17944
+ if (sync.outcome === "update-failed") return `could not fast-forward ${branch} from origin/${branch}; forked from local`;
17945
+ return null;
17946
+ }
17947
+ async function syncFreshWorktree() {
17948
+ if (!syncableGitWorkspace()) return;
17949
+ await syncIntegrationBranchForStart(SPAWN_GAP_TRIGGER, await resolveBaseForStart());
17950
+ if (port.state().isDestroyed) return;
17951
+ if (!lifecycleState.workspace) return;
17952
+ const signature = await api.computeWorktreeSignature();
17953
+ if (!signature) return;
17954
+ await runAutoRebase(SPAWN_GAP_TRIGGER, signature);
17955
+ }
17956
+ async function provisionWorkspaceMembers(setup) {
17957
+ if (!setup.ok) {
17958
+ port.emit("worktree-blocked", {
17959
+ id,
17960
+ branch: null,
17961
+ notice: setup.error
17962
+ });
17963
+ return false;
17964
+ }
17965
+ const provisioned = await setup.members.provision();
17966
+ if (provisioned.ok) {
17967
+ lifecycleState.provisionedMembers = provisioned.members;
17968
+ for (const member of provisioned.members) await seedWorktreeDependencies(member.repoPath, member.dir, member.base ?? null);
17969
+ return true;
17970
+ }
17971
+ port.emit("worktree-blocked", {
17972
+ id,
17973
+ branch: setup.members.branch,
17974
+ notice: provisioned.error
17975
+ });
17976
+ return false;
17977
+ }
17978
+ async function provision({ fresh = false } = {}) {
17979
+ if (workspaceMembers) return provisionWorkspaceMembers(workspaceMembers);
17980
+ if (!gitWorkspace) return true;
17981
+ if (lifecycleState.worktreeDir && fs.existsSync(lifecycleState.worktreeDir)) {
17982
+ await Promise.resolve(gitWorkspace.populate({
17983
+ projectPath: currentProjectPath(),
17984
+ wtDir: lifecycleState.worktreeDir,
17985
+ shareList: worktreeShare
17986
+ })).catch(() => {});
17987
+ if (fresh) await syncFreshWorktree();
17988
+ await seedWorktreeDependencies(currentProjectPath(), lifecycleState.worktreeDir, effectiveIntegrationBranch());
17989
+ return true;
17990
+ }
17991
+ const baseBranch = await resolveBaseForStart();
17992
+ const initialSync = await syncIntegrationBranchForStart("initial-create", baseBranch);
17993
+ if (port.state().isDestroyed) return false;
17994
+ let workspace;
17995
+ try {
17996
+ workspace = await gitWorkspace.create({
17997
+ projectPath: currentProjectPath(),
17998
+ owner: `session:${id}`,
17999
+ teamId: "session",
18000
+ label: id,
18001
+ baseBranch,
18002
+ configuredIntegrationBranch: integrationBranch,
18003
+ worktreeBase: worktreeRoot,
18004
+ shareList: worktreeShare
18005
+ });
18006
+ } catch (error) {
18007
+ console.warn(`[session ${id}] worktree create failed: ${errorMessage(error)} - running in place`);
18008
+ return true;
18009
+ }
18010
+ if (workspace?.reason === "no-base-branch") {
18011
+ lifecycleState.worktreeNotice = integrationBranch ? `Integration branch "${integrationBranch}" not found. Create it, then start this session.` : "No default branch found. Configure integrationBranch or create main or master, then start this session.";
18012
+ port.emit("worktree-blocked", {
18013
+ id,
18014
+ branch: integrationBranch,
18015
+ notice: lifecycleState.worktreeNotice
18016
+ });
18017
+ return false;
18018
+ }
18019
+ if (workspace?.reason === "branch-in-use") {
18020
+ let adopted = false;
18021
+ if (workspace.branch && workspace.conflictPath && fs.existsSync(workspace.conflictPath) && !isSameDirectoryPath(workspace.conflictPath, currentProjectPath())) try {
18022
+ adoptWorktree({
18023
+ worktreeDir: workspace.conflictPath,
18024
+ branch: workspace.branch,
18025
+ base: workspace.base || integrationBranch
18026
+ });
18027
+ adopted = true;
18028
+ } catch (error) {
18029
+ console.warn(`[session ${id}] survivor adopt failed: ${errorMessage(error)} - running in place`);
18030
+ }
18031
+ if (adopted && lifecycleState.worktreeDir) {
18032
+ lifecycleState.worktreeNotice = null;
18033
+ await Promise.resolve(gitWorkspace.populate({
18034
+ projectPath: currentProjectPath(),
18035
+ wtDir: lifecycleState.worktreeDir,
18036
+ shareList: worktreeShare
18037
+ })).catch(() => {});
18038
+ port.emit("worktree-ready", {
18039
+ id,
18040
+ worktreeDir: lifecycleState.worktreeDir,
18041
+ branch: workspace.branch,
18042
+ base: effectiveIntegrationBranch()
18043
+ });
18044
+ await seedWorktreeDependencies(currentProjectPath(), lifecycleState.worktreeDir, effectiveIntegrationBranch());
18045
+ return true;
18046
+ }
18047
+ lifecycleState.worktreeNotice = `session branch already checked out at ${workspace.conflictPath}; running in place`;
18048
+ port.emit("worktree-blocked", {
18049
+ id,
18050
+ branch: effectiveIntegrationBranch(),
18051
+ notice: lifecycleState.worktreeNotice
18052
+ });
18053
+ }
18054
+ if (!workspace || !workspace.isGit) {
18055
+ lifecycleState.worktreeDir = null;
18056
+ lifecycleState.isWorktree = false;
18057
+ return true;
18058
+ }
18059
+ lifecycleState.workspace = workspace;
18060
+ lifecycleState.effectiveBase = workspace.base || null;
18061
+ lifecycleState.worktreeDir = workspace.cwd;
18062
+ lifecycleState.commonGitDir = resolveCommonGitDir();
18063
+ lifecycleState.baseSha = workspace.baseSha || null;
18064
+ lifecycleState.worktreeNotice = null;
18065
+ setMergeStatus("none", {}, { emit: false });
18066
+ lifecycleState.isWorktree = true;
18067
+ const syncWarning = forkSyncWarning(initialSync, workspace.base || baseBranch);
18068
+ if (syncWarning) port.emit("worktree-warning", {
18069
+ id,
18070
+ branch: workspace.base || null,
18071
+ notice: syncWarning
18072
+ });
18073
+ port.emit("worktree-ready", {
18074
+ id,
18075
+ worktreeDir: workspace.cwd,
18076
+ branch: workspace.branch,
18077
+ base: workspace.base || null
18078
+ });
18079
+ await seedWorktreeDependencies(currentProjectPath(), workspace.cwd, workspace.base || null);
18080
+ return true;
18081
+ }
18082
+ async function seedWorktreeDependencies(mainCheckout, worktreeDir, branch) {
18083
+ if (!seedDependencies) return;
18084
+ const outcome = await seedDependencies({
18085
+ mainCheckout,
18086
+ worktreeDir
18087
+ });
18088
+ if (outcome.action === "cloned") {
18089
+ console.log(`[session ${id}] cloned node_modules into ${worktreeDir} (${outcome.dirs.join(", ")}) in ${outcome.elapsedMs}ms`);
18090
+ if (!outcome.staleDirs.length) return;
18091
+ const staleNotice = describeStaleDirs(outcome.staleDirs);
18092
+ console.log(`[session ${id}] ${staleNotice}`);
18093
+ port.emit("worktree-warning", {
18094
+ id,
18095
+ branch,
18096
+ notice: staleNotice
18097
+ });
18098
+ return;
18099
+ }
18100
+ const reason = describeDependencyCloneSkip(outcome.reason);
18101
+ console.log(`[session ${id}] did not clone node_modules into ${worktreeDir}: ${reason}`);
18102
+ if (outcome.notify) port.emit("worktree-warning", {
18103
+ id,
18104
+ branch,
18105
+ notice: reason
18106
+ });
18107
+ }
18108
+ return { provision };
17917
18109
  }
18110
+ //#endregion
18111
+ //#region session/worktree/worktree-lifecycle-context.ts
17918
18112
  function branchFromHeadRef(headRef) {
17919
18113
  return headRef.startsWith("refs/heads/") ? headRef.slice(11) : "";
17920
18114
  }
17921
- function stopWatcher(watcher) {
17922
- if (!watcher) return null;
17923
- try {
17924
- watcher.stop();
17925
- } catch {}
17926
- return null;
17927
- }
17928
- function detectLinkedWorktree(directory) {
17929
- return readWorktreeGitdirPointer(directory) !== null;
17930
- }
17931
18115
  function branchFromRemoteRef(upstream) {
17932
18116
  const separatorIndex = upstream.indexOf("/");
17933
18117
  if (separatorIndex === -1) return upstream;
@@ -17939,976 +18123,849 @@ function isOwnRemoteCopy(upstream, branch) {
17939
18123
  function prefixRenameAndCopyHeaders(diffText, memberName) {
17940
18124
  return diffText.replace(/^((?:rename|copy) (?:from|to) )("?)/gm, (_match, keyword, openingQuote) => `${keyword}${openingQuote}${memberName}/`);
17941
18125
  }
17942
- function setUpWorkspaceMembers({ folder, sessionId, sessionName, repoPaths, shareList, gitWorkspace }) {
17943
- const planned = planWorkspaceMembers({
17944
- folder,
17945
- sessionId,
17946
- repoPaths
17947
- });
17948
- if (!planned.ok) return planned;
17949
- const memberGit = workspaceMemberGit(gitWorkspace);
17950
- if (!memberGit) return {
17951
- ok: false,
17952
- error: "Git workspace is unavailable"
17953
- };
17954
- return {
17955
- ok: true,
17956
- members: createSessionWorkspaceMembers({
17957
- plan: planned.plan,
17958
- owner: `session:${sessionId}`,
17959
- sessionName,
17960
- shareList,
17961
- gitWorkspace: memberGit
17962
- })
17963
- };
17964
- }
17965
- function createSessionWorktreeLifecycle({ id, projectPath, integrationBranch = null, gitWorkspace = null, autoRebase = true, syncOnStart = true, liveWorktreeReview = true, worktreeRoot = null, worktreeShare = null, workspaceRepos = null, seedDependencies = null, sessionName = id, port }) {
17966
- const currentProjectPath = () => port.projectPath ? port.projectPath() : projectPath;
17967
- function gitOut(args, options) {
17968
- return readGitStrict(args, options);
18126
+ //#endregion
18127
+ //#region session/worktree/worktree-diff-scopes.ts
18128
+ function createWorktreeDiffScopes(context) {
18129
+ const { id, lifecycleState, currentProjectPath, gitOut, gitLookup, readUpstreamOf, effectiveIntegrationBranch, setMergeStatus } = context;
18130
+ async function resolveEffectiveBase(opts) {
18131
+ if (lifecycleState.workspace?.base) {
18132
+ lifecycleState.effectiveBase = lifecycleState.workspace.base;
18133
+ return lifecycleState.effectiveBase;
18134
+ }
18135
+ const branch = branchFromHeadRef((await gitLookup([
18136
+ "symbolic-ref",
18137
+ "--quiet",
18138
+ "HEAD"
18139
+ ], opts))?.trim() ?? "");
18140
+ const upstream = branch ? await readUpstreamOf(branch, opts) : null;
18141
+ if (upstream && !isOwnRemoteCopy(upstream, branch)) {
18142
+ lifecycleState.effectiveBase = branchFromRemoteRef(upstream);
18143
+ return upstream;
18144
+ }
18145
+ lifecycleState.effectiveBase = effectiveIntegrationBranch();
18146
+ return lifecycleState.effectiveBase;
17969
18147
  }
17970
- function gitLookup(args, options) {
17971
- return gitOut(args, options).catch((error) => {
17972
- if (error?.code === GIT_NOT_FOUND_EXIT_CODE) return null;
17973
- throw error;
17974
- });
18148
+ async function resolveVerifiedBaseRef(opts) {
18149
+ const candidate = await resolveEffectiveBase(opts);
18150
+ if (candidate && await gitLookup([
18151
+ "rev-parse",
18152
+ "--verify",
18153
+ "--quiet",
18154
+ candidate
18155
+ ], opts) !== null) return {
18156
+ ref: await freshestBaseRef(candidate, opts),
18157
+ verified: true
18158
+ };
18159
+ return {
18160
+ ref: lifecycleState.baseSha || null,
18161
+ verified: false
18162
+ };
17975
18163
  }
17976
- async function readUpstreamOf(branch, options) {
17977
- return parseBranchUpstream(await gitOut([
18164
+ async function freshestBaseRef(baseBranch, opts) {
18165
+ const localRef = `refs/heads/${baseBranch}`;
18166
+ const originRef = `refs/remotes/origin/${baseBranch}`;
18167
+ const existingRefs = (await gitOut([
17978
18168
  "for-each-ref",
17979
- `--format=${BRANCH_UPSTREAM_FORMAT}`,
17980
- `refs/heads/${branch}`
17981
- ], options), branch);
17982
- }
17983
- const workspaceMembers = workspaceRepos ? setUpWorkspaceMembers({
17984
- folder: currentProjectPath(),
17985
- sessionId: id,
17986
- sessionName,
17987
- repoPaths: workspaceRepos,
17988
- shareList: worktreeShare,
17989
- gitWorkspace
17990
- }) : null;
17991
- const lifecycleState = {
17992
- worktreeDir: null,
17993
- commonGitDir: null,
17994
- baseSha: null,
17995
- workspace: null,
17996
- mergeStatus: "none",
17997
- mergeReason: null,
17998
- mergeConflicts: [],
17999
- worktreeNotice: null,
18000
- effectiveBase: null,
18001
- isWorktree: detectLinkedWorktree(currentProjectPath()),
18002
- autoRebasing: false,
18003
- rebaseConflictKey: null,
18004
- resyncPromise: null,
18005
- worktreeWatcher: null,
18006
- integrationWatcher: null,
18007
- rerereWatcher: null,
18008
- checkTimer: createCoalescedTimer({
18009
- mode: "leading",
18010
- delayMs: WORKTREE_CHECK_DEBOUNCE_MS,
18011
- run: () => {
18012
- api.checkWorktreeChange().catch(recordWorktreeCheckFailure);
18013
- }
18014
- }),
18015
- lastSignature: null,
18016
- lastLoggedCheckFailure: null,
18017
- provisionedMembers: null
18018
- };
18019
- function effectiveIntegrationBranch() {
18020
- return lifecycleState.workspace?.base || lifecycleState.effectiveBase || integrationBranch || null;
18169
+ "--format=%(refname)",
18170
+ localRef,
18171
+ originRef
18172
+ ], opts)).split("\n");
18173
+ if (!existingRefs.includes(localRef) || !existingRefs.includes(originRef)) return baseBranch;
18174
+ return await gitLookup([
18175
+ "merge-base",
18176
+ "--is-ancestor",
18177
+ localRef,
18178
+ originRef
18179
+ ], opts) !== null ? `origin/${baseBranch}` : baseBranch;
18021
18180
  }
18022
- function snapshot() {
18181
+ function diffGitOptions(cwd) {
18023
18182
  return {
18024
- worktreeDir: lifecycleState.worktreeDir,
18025
- commonGitDir: lifecycleState.commonGitDir,
18026
- baseSha: lifecycleState.baseSha,
18027
- mergeStatus: lifecycleState.mergeStatus,
18028
- mergeReason: lifecycleState.mergeReason,
18029
- mergeConflicts: [...lifecycleState.mergeConflicts],
18030
- worktreeNotice: lifecycleState.worktreeNotice,
18031
- effectiveBase: effectiveIntegrationBranch(),
18032
- isWorktree: lifecycleState.isWorktree,
18033
- isWorkspace: workspaceMembers !== null,
18034
- isAutoRebasing: lifecycleState.autoRebasing,
18035
- hasConflictCooldown: Boolean(lifecycleState.rebaseConflictKey),
18036
- hasPendingCheck: lifecycleState.checkTimer.isArmed
18183
+ cwd,
18184
+ timeoutMs: 15e3,
18185
+ maxBuffer: 67108864
18037
18186
  };
18038
18187
  }
18039
- function getCarry() {
18040
- if (!lifecycleState.worktreeDir || !lifecycleState.workspace) return null;
18188
+ async function resolveDiffBase(opts) {
18189
+ const { ref: baseRef, verified } = await resolveVerifiedBaseRef(opts);
18190
+ if (verified) return {
18191
+ base: (await gitLookup([
18192
+ "merge-base",
18193
+ baseRef,
18194
+ "HEAD"
18195
+ ], opts))?.trim() ?? "",
18196
+ aheadCount: (await gitOut([
18197
+ "rev-list",
18198
+ "--count",
18199
+ `${baseRef}..HEAD`
18200
+ ], opts)).trim(),
18201
+ ref: baseRef,
18202
+ verified
18203
+ };
18204
+ if (!baseRef) return {
18205
+ base: "",
18206
+ aheadCount: "0",
18207
+ ref: null,
18208
+ verified
18209
+ };
18041
18210
  return {
18042
- worktreeDir: lifecycleState.worktreeDir,
18043
- branch: lifecycleState.workspace.branch || null,
18044
- base: lifecycleState.workspace.base || null
18211
+ base: baseRef,
18212
+ aheadCount: (await gitOut([
18213
+ "rev-list",
18214
+ "--count",
18215
+ `${baseRef}..HEAD`
18216
+ ], opts)).trim(),
18217
+ ref: null,
18218
+ verified
18045
18219
  };
18046
18220
  }
18047
- function hasOwnWorktree() {
18048
- return Boolean(gitWorkspace && lifecycleState.workspace);
18049
- }
18050
- function setMergeStatus(status, detail = {}, { emit = true } = {}) {
18051
- Object.assign(lifecycleState, projectMergeState(status, detail));
18052
- if (!emit) return;
18053
- port.emit("merge-status", {
18054
- id,
18055
- mergeStatus: status,
18056
- ...detail
18057
- });
18058
- }
18059
- const isMerging = () => lifecycleState.mergeStatus === "merging";
18060
- function effectiveCwd() {
18061
- return lifecycleState.worktreeDir || currentProjectPath();
18062
- }
18063
- function refreshGitContext() {
18064
- const next = detectLinkedWorktree(effectiveCwd());
18065
- if (next === lifecycleState.isWorktree) return false;
18066
- lifecycleState.isWorktree = next;
18067
- return true;
18221
+ async function readChangeScope(name, root, base, sessionPathPrefix) {
18222
+ const run = (args) => gitOut(args, diffGitOptions(root));
18223
+ const nul = String.fromCharCode(0);
18224
+ const trackedNameStatus = await run([
18225
+ "diff",
18226
+ "-z",
18227
+ "--name-status",
18228
+ "-M",
18229
+ "HEAD"
18230
+ ]);
18231
+ const untrackedPaths = (await run([
18232
+ "ls-files",
18233
+ "-z",
18234
+ "--others",
18235
+ "--exclude-standard"
18236
+ ])).split(nul).filter(Boolean);
18237
+ return {
18238
+ name,
18239
+ root,
18240
+ sessionPathPrefix,
18241
+ base: base || null,
18242
+ committedNameStatus: base ? await run([
18243
+ "diff",
18244
+ "-z",
18245
+ "--name-status",
18246
+ "-M",
18247
+ `${base}..HEAD`
18248
+ ]) : "",
18249
+ uncommittedNameStatus: trackedNameStatus + untrackedPaths.map((untrackedPath) => `?${nul}${untrackedPath}${nul}`).join("")
18250
+ };
18068
18251
  }
18069
- function resolveCommonGitDir() {
18070
- if (!lifecycleState.worktreeDir) return null;
18071
- try {
18072
- const invocation = {
18073
- args: ["rev-parse", "--git-common-dir"],
18074
- env: process.env
18252
+ async function memberMergeBase(member) {
18253
+ const opts = diffGitOptions(member.dir);
18254
+ const candidates = member.base ? [
18255
+ await freshestBaseRef(member.base, opts),
18256
+ `origin/${member.base}`,
18257
+ "origin/HEAD"
18258
+ ] : ["origin/HEAD"];
18259
+ for (const candidate of candidates) {
18260
+ if (await gitLookup([
18261
+ "rev-parse",
18262
+ "--verify",
18263
+ "--quiet",
18264
+ candidate
18265
+ ], opts) === null) continue;
18266
+ return {
18267
+ ref: candidate,
18268
+ sha: (await gitLookup([
18269
+ "merge-base",
18270
+ candidate,
18271
+ "HEAD"
18272
+ ], opts))?.trim() ?? ""
18075
18273
  };
18076
- const commonDir = execFileSync("git", invocation.args, {
18077
- env: invocation.env,
18078
- cwd: lifecycleState.worktreeDir,
18079
- encoding: "utf8",
18080
- stdio: [
18081
- "ignore",
18082
- "pipe",
18083
- "pipe"
18084
- ],
18085
- timeout: 1e4
18086
- });
18087
- return path.resolve(lifecycleState.worktreeDir, commonDir.trim());
18088
- } catch {
18089
- return null;
18090
18274
  }
18275
+ return {
18276
+ ref: null,
18277
+ sha: ""
18278
+ };
18091
18279
  }
18092
- function clearCheckTimer() {
18093
- lifecycleState.checkTimer.cancel();
18094
- }
18095
- function scheduleCheck() {
18096
- if (port.state().isDestroyed) return;
18097
- if (!lifecycleState.worktreeDir && !lifecycleState.provisionedMembers) return;
18098
- lifecycleState.checkTimer.schedule();
18280
+ async function getChangeScopes() {
18281
+ const members = lifecycleState.provisionedMembers;
18282
+ if (members) {
18283
+ const scopes = [];
18284
+ for (const member of members) {
18285
+ if (!(await fs.promises.stat(member.dir).catch(() => null))?.isDirectory()) continue;
18286
+ scopes.push(await readChangeScope(member.name, member.dir, (await memberMergeBase(member)).sha, `${member.name}/`));
18287
+ }
18288
+ return scopes;
18289
+ }
18290
+ const worktreeDir = lifecycleState.worktreeDir;
18291
+ if (!worktreeDir) return [];
18292
+ const { base } = await resolveDiffBase(diffGitOptions(worktreeDir));
18293
+ return [await readChangeScope(path.basename(currentProjectPath()), worktreeDir, base, "")];
18099
18294
  }
18100
- function stopWatching() {
18101
- lifecycleState.worktreeWatcher = stopWatcher(lifecycleState.worktreeWatcher);
18102
- lifecycleState.integrationWatcher = stopWatcher(lifecycleState.integrationWatcher);
18103
- lifecycleState.rerereWatcher = stopWatcher(lifecycleState.rerereWatcher);
18104
- clearCheckTimer();
18105
- lifecycleState.lastSignature = null;
18295
+ async function readMemberDiff(member) {
18296
+ const run = (args) => gitOut(args, diffGitOptions(member.dir));
18297
+ const prefixArgs = [`--src-prefix=a/${member.name}/`, `--dst-prefix=b/${member.name}/`];
18298
+ await markUntrackedIntentToAdd(member.dir);
18299
+ const { ref: baseRef, sha: base } = await memberMergeBase(member);
18300
+ const aheadCount = base ? (await run([
18301
+ "rev-list",
18302
+ "--count",
18303
+ `${base}..HEAD`
18304
+ ])).trim() : "0";
18305
+ const readPrefixedDiff = async (range) => prefixRenameAndCopyHeaders(await run([
18306
+ "diff",
18307
+ ...prefixArgs,
18308
+ range
18309
+ ]), member.name);
18310
+ return {
18311
+ name: member.name,
18312
+ committed: base ? {
18313
+ stat: (await run([
18314
+ "diff",
18315
+ "--stat",
18316
+ `${base}..HEAD`
18317
+ ])).trim(),
18318
+ diff: await readPrefixedDiff(`${base}..HEAD`)
18319
+ } : {
18320
+ stat: "",
18321
+ diff: ""
18322
+ },
18323
+ uncommitted: {
18324
+ stat: (await run([
18325
+ "diff",
18326
+ "--stat",
18327
+ "HEAD"
18328
+ ])).trim(),
18329
+ diff: await readPrefixedDiff("HEAD")
18330
+ },
18331
+ hasCommits: aheadCount !== "" && aheadCount !== "0",
18332
+ baseRef,
18333
+ baseSha: base
18334
+ };
18106
18335
  }
18107
- function onRerereRecorded() {
18108
- const session = port.state();
18109
- const verdict = decideRerereCooldownClear({
18110
- enabled: autoRebase !== false && Boolean(gitWorkspace && lifecycleState.workspace),
18111
- hasCooldown: Boolean(lifecycleState.rebaseConflictKey),
18112
- teardownPending: session.isTeardownPending
18113
- });
18114
- if (!verdict.clear) return;
18115
- port.recordDecision({
18116
- kind: "rebase",
18117
- ts: Date.now(),
18118
- decision: "cooldown-cleared",
18119
- reason: verdict.reason
18336
+ async function getWorkspaceDiff(members) {
18337
+ const memberDiffs = [];
18338
+ for (const member of members) {
18339
+ if (!(await fs.promises.stat(member.dir).catch(() => null))?.isDirectory()) continue;
18340
+ memberDiffs.push(await readMemberDiff(member));
18341
+ }
18342
+ const joinSection = (section) => ({
18343
+ stat: memberDiffs.filter((memberDiff) => memberDiff[section].stat).map((memberDiff) => `${memberDiff.name}/\n${memberDiff[section].stat}`).join("\n"),
18344
+ diff: memberDiffs.map((memberDiff) => memberDiff[section].diff).join("")
18120
18345
  });
18121
- lifecycleState.rebaseConflictKey = null;
18122
- scheduleCheck();
18346
+ return {
18347
+ committed: joinSection("committed"),
18348
+ uncommitted: joinSection("uncommitted"),
18349
+ hasCommits: memberDiffs.some((memberDiff) => memberDiff.hasCommits),
18350
+ bases: memberDiffs.filter((memberDiff) => memberDiff.baseSha).map((memberDiff) => ({
18351
+ member: memberDiff.name,
18352
+ ref: memberDiff.baseRef,
18353
+ sha: memberDiff.baseSha,
18354
+ verified: true
18355
+ }))
18356
+ };
18123
18357
  }
18124
- function startWatching() {
18125
- stopWatching();
18126
- if (port.state().isDestroyed || !lifecycleState.worktreeDir) return;
18127
- const onChange = () => scheduleCheck();
18128
- lifecycleState.worktreeWatcher = createWorktreeWatcher({
18129
- worktreeDir: lifecycleState.worktreeDir,
18130
- onChange
18131
- });
18132
- lifecycleState.worktreeWatcher.start();
18133
- const watchedBranch = effectiveIntegrationBranch();
18134
- if (liveWorktreeReview === false || !lifecycleState.commonGitDir || !watchedBranch) return;
18135
- lifecycleState.integrationWatcher = createIntegrationRefWatcher({
18136
- commonGitDir: lifecycleState.commonGitDir,
18137
- branch: watchedBranch,
18138
- onChange
18139
- });
18140
- lifecycleState.integrationWatcher.start();
18141
- lifecycleState.rerereWatcher = createRerereWatcher({
18142
- commonGitDir: lifecycleState.commonGitDir,
18143
- onChange: onRerereRecorded
18144
- });
18145
- lifecycleState.rerereWatcher.start();
18358
+ async function markUntrackedIntentToAdd(dir) {
18359
+ try {
18360
+ await gitOut([
18361
+ "add",
18362
+ "-N",
18363
+ "--",
18364
+ "."
18365
+ ], diffGitOptions(dir));
18366
+ } catch (error) {
18367
+ console.warn(`[session ${id}] intent-to-add in ${dir} failed: ${errorMessage(error)}`);
18368
+ }
18146
18369
  }
18147
- function adoptWorktree({ worktreeDir, branch, base, baseSha = null, hasUnmergedWork: hasUnmerged = true, watch = true, emit = true }) {
18148
- if (!worktreeDir) return;
18149
- const resolvedBase = base || integrationBranch || null;
18150
- lifecycleState.workspace = {
18151
- cwd: worktreeDir,
18152
- isGit: true,
18153
- branch,
18154
- base: resolvedBase,
18155
- baseSha
18370
+ async function getDiff() {
18371
+ const empty = {
18372
+ stat: "",
18373
+ diff: ""
18374
+ };
18375
+ if (lifecycleState.provisionedMembers) return getWorkspaceDiff(lifecycleState.provisionedMembers);
18376
+ if (!lifecycleState.worktreeDir) return {
18377
+ committed: empty,
18378
+ uncommitted: empty,
18379
+ hasCommits: false,
18380
+ bases: []
18381
+ };
18382
+ const opts = diffGitOptions(lifecycleState.worktreeDir);
18383
+ const run = (args) => gitOut(args, opts);
18384
+ await markUntrackedIntentToAdd(lifecycleState.worktreeDir);
18385
+ const { base, aheadCount, ref, verified } = await resolveDiffBase(opts);
18386
+ const committed = base ? {
18387
+ stat: (await run([
18388
+ "diff",
18389
+ "--stat",
18390
+ `${base}..HEAD`
18391
+ ])).trim(),
18392
+ diff: await run(["diff", `${base}..HEAD`])
18393
+ } : empty;
18394
+ const uncommitted = {
18395
+ stat: (await run([
18396
+ "diff",
18397
+ "--stat",
18398
+ "HEAD"
18399
+ ])).trim(),
18400
+ diff: await run(["diff", "HEAD"])
18401
+ };
18402
+ const healed = decideDiffSelfHeal(lifecycleState.mergeStatus, committed.diff, uncommitted.diff);
18403
+ if (healed) setMergeStatus(healed);
18404
+ return {
18405
+ committed,
18406
+ uncommitted,
18407
+ hasCommits: aheadCount !== "" && aheadCount !== "0",
18408
+ bases: base ? [{
18409
+ member: null,
18410
+ ref,
18411
+ sha: base,
18412
+ verified
18413
+ }] : []
18156
18414
  };
18157
- lifecycleState.effectiveBase = resolvedBase;
18158
- lifecycleState.worktreeDir = worktreeDir;
18159
- lifecycleState.baseSha = baseSha;
18160
- lifecycleState.commonGitDir = resolveCommonGitDir();
18161
- lifecycleState.isWorktree = true;
18162
- setMergeStatus(hasUnmerged ? "pending-review" : "none", {}, { emit });
18163
- if (watch) startWatching();
18164
- }
18165
- function syncableGitWorkspace() {
18166
- if (syncOnStart === false) return null;
18167
- if (!gitWorkspace || typeof gitWorkspace.syncIntegrationBranch !== "function") return null;
18168
- return gitWorkspace;
18169
18415
  }
18170
- async function resolveBaseForStart() {
18171
- const resolvedBase = effectiveIntegrationBranch();
18172
- if (resolvedBase) return resolvedBase;
18173
- if (!gitWorkspace || typeof gitWorkspace.detectDefaultBranch !== "function") return null;
18174
- const detectedBase = await gitWorkspace.detectDefaultBranch({ projectPath: currentProjectPath() });
18175
- lifecycleState.effectiveBase = detectedBase;
18176
- return detectedBase;
18416
+ return {
18417
+ resolveEffectiveBase,
18418
+ resolveVerifiedBaseRef,
18419
+ diffGitOptions,
18420
+ getChangeScopes,
18421
+ getDiff
18422
+ };
18423
+ }
18424
+ //#endregion
18425
+ //#region session/worktree/worktree-branch-sync.ts
18426
+ function createWorktreeBranchSync(context) {
18427
+ const { id, lifecycleState, currentProjectPath, gitOut, readUpstreamOf, effectiveIntegrationBranch, setMergeStatus } = context;
18428
+ function noUpstream(branch) {
18429
+ return {
18430
+ branch: branch || null,
18431
+ upstream: null,
18432
+ state: decideBranchSyncState({ hasUpstream: false }),
18433
+ ahead: 0,
18434
+ behind: 0,
18435
+ fetched: null
18436
+ };
18177
18437
  }
18178
- async function syncIntegrationBranchForStart(trigger, branch) {
18179
- const syncGitWorkspace = syncableGitWorkspace();
18180
- if (!syncGitWorkspace || !branch) return null;
18438
+ async function fetchBranch(remote, branch, opts) {
18181
18439
  try {
18182
- const sync = await syncGitWorkspace.syncIntegrationBranch({
18183
- projectPath: currentProjectPath(),
18440
+ await gitOut([
18441
+ "fetch",
18442
+ "--quiet",
18443
+ remote,
18184
18444
  branch
18445
+ ], {
18446
+ ...opts,
18447
+ timeoutMs: GIT_FETCH_TIMEOUT_MS,
18448
+ replaceEnv: {
18449
+ ...process.env,
18450
+ GIT_TERMINAL_PROMPT: "0"
18451
+ }
18185
18452
  });
18186
- port.recordDecision({
18187
- kind: "integration-sync",
18188
- ts: Date.now(),
18189
- decision: trigger,
18190
- outcome: sync.outcome,
18191
- from: sync.from,
18192
- to: sync.to
18193
- });
18194
- if (sync.outcome === "fetch-failed" || sync.outcome === "update-failed") {
18195
- const detail = sync.error ? `${sync.outcome}: ${sync.error}` : sync.outcome;
18196
- console.warn(`[session ${id}] integration sync failed during ${trigger}: ${detail}`);
18197
- }
18198
- return sync;
18453
+ return true;
18199
18454
  } catch (error) {
18200
- console.warn(`[session ${id}] integration sync failed during ${trigger}: ${errorMessage(error)}`);
18201
- return null;
18455
+ console.warn(`[session ${id}] fetch of ${remote}/${branch} failed: ${errorMessage(error)}`);
18456
+ return false;
18202
18457
  }
18203
18458
  }
18204
- function forkSyncWarning(sync, branch) {
18205
- if (!sync || !branch) return null;
18206
- if (sync.outcome === "ahead") return `base ${branch} is ahead of origin/${branch} (unpushed commits); forked from local`;
18207
- if (sync.outcome === "diverged") return `base ${branch} has diverged from origin/${branch}; forked from local`;
18208
- if (sync.outcome === "fetch-failed") return `could not fetch origin/${branch}; forked from local`;
18209
- if (sync.outcome === "checked-out") return `${branch} is checked out with local changes and behind origin/${branch}; forked from local`;
18210
- if (sync.outcome === "update-failed") return `could not fast-forward ${branch} from origin/${branch}; forked from local`;
18211
- return null;
18459
+ async function branchCounts(upstream, branch, opts) {
18460
+ const counts = parseLeftRightCount(await gitOut([
18461
+ "rev-list",
18462
+ "--left-right",
18463
+ "--count",
18464
+ `${upstream}...${branch}`
18465
+ ], opts));
18466
+ return {
18467
+ ahead: counts ? counts.ahead : 0,
18468
+ behind: counts ? counts.behind : 0,
18469
+ state: decideBranchSyncState({
18470
+ hasUpstream: true,
18471
+ ahead: counts?.ahead,
18472
+ behind: counts?.behind
18473
+ })
18474
+ };
18212
18475
  }
18213
- async function syncFreshWorktree() {
18214
- if (!syncableGitWorkspace()) return;
18215
- await syncIntegrationBranchForStart(SPAWN_GAP_TRIGGER, await resolveBaseForStart());
18216
- if (port.state().isDestroyed) return;
18217
- if (!lifecycleState.workspace) return;
18218
- const signature = await api.computeWorktreeSignature();
18219
- if (!signature) return;
18220
- await runAutoRebase(SPAWN_GAP_TRIGGER, signature);
18476
+ function applyBaseSyncDemotion(sync) {
18477
+ const nextStatus = decideBaseSyncDemotion(lifecycleState.mergeStatus, lifecycleState.mergeReason, sync.state);
18478
+ if (nextStatus !== null) setMergeStatus(nextStatus);
18479
+ return sync;
18221
18480
  }
18222
- async function provisionWorkspaceMembers(setup) {
18223
- if (!setup.ok) {
18224
- port.emit("worktree-blocked", {
18225
- id,
18226
- branch: null,
18227
- notice: setup.error
18228
- });
18229
- return false;
18230
- }
18231
- const provisioned = await setup.members.provision();
18232
- if (provisioned.ok) {
18233
- lifecycleState.provisionedMembers = provisioned.members;
18234
- for (const member of provisioned.members) await seedWorktreeDependencies(member.repoPath, member.dir, member.base ?? null);
18235
- return true;
18236
- }
18237
- port.emit("worktree-blocked", {
18238
- id,
18239
- branch: setup.members.branch,
18240
- notice: provisioned.error
18241
- });
18242
- return false;
18481
+ function branchSyncFailure(branch, error) {
18482
+ console.warn(`[session ${id}] branch sync check of ${branch} failed: ${errorMessage(error)}`);
18483
+ return {
18484
+ branch,
18485
+ upstream: null,
18486
+ state: decideBranchSyncState({ hasUpstream: true }),
18487
+ ahead: 0,
18488
+ behind: 0,
18489
+ fetched: null,
18490
+ error: firstGitErrorLine(error)
18491
+ };
18243
18492
  }
18244
- async function provision({ fresh = false } = {}) {
18245
- if (workspaceMembers) return provisionWorkspaceMembers(workspaceMembers);
18246
- if (!gitWorkspace) return true;
18247
- if (lifecycleState.worktreeDir && fs.existsSync(lifecycleState.worktreeDir)) {
18248
- await Promise.resolve(gitWorkspace.populate({
18249
- projectPath: currentProjectPath(),
18250
- wtDir: lifecycleState.worktreeDir,
18251
- shareList: worktreeShare
18252
- })).catch(() => {});
18253
- if (fresh) await syncFreshWorktree();
18254
- await seedWorktreeDependencies(currentProjectPath(), lifecycleState.worktreeDir, effectiveIntegrationBranch());
18255
- return true;
18256
- }
18257
- const baseBranch = await resolveBaseForStart();
18258
- const initialSync = await syncIntegrationBranchForStart("initial-create", baseBranch);
18259
- if (port.state().isDestroyed) return false;
18260
- let workspace;
18493
+ async function getBranchSync() {
18494
+ const branch = effectiveIntegrationBranch();
18495
+ if (!branch || !currentProjectPath()) return noUpstream(branch);
18496
+ return readBranchSync(branch).catch((error) => branchSyncFailure(branch, error));
18497
+ }
18498
+ async function isGitRepository(opts) {
18261
18499
  try {
18262
- workspace = await gitWorkspace.create({
18263
- projectPath: currentProjectPath(),
18264
- owner: `session:${id}`,
18265
- teamId: "session",
18266
- label: id,
18267
- baseBranch,
18268
- configuredIntegrationBranch: integrationBranch,
18269
- worktreeBase: worktreeRoot,
18270
- shareList: worktreeShare
18271
- });
18272
- } catch (error) {
18273
- console.warn(`[session ${id}] worktree create failed: ${errorMessage(error)} - running in place`);
18274
- return true;
18275
- }
18276
- if (workspace?.reason === "no-base-branch") {
18277
- lifecycleState.worktreeNotice = integrationBranch ? `Integration branch "${integrationBranch}" not found. Create it, then start this session.` : "No default branch found. Configure integrationBranch or create main or master, then start this session.";
18278
- port.emit("worktree-blocked", {
18279
- id,
18280
- branch: integrationBranch,
18281
- notice: lifecycleState.worktreeNotice
18282
- });
18283
- return false;
18284
- }
18285
- if (workspace?.reason === "branch-in-use") {
18286
- let adopted = false;
18287
- if (workspace.branch && workspace.conflictPath && fs.existsSync(workspace.conflictPath) && !isSameDirectoryPath(workspace.conflictPath, currentProjectPath())) try {
18288
- adoptWorktree({
18289
- worktreeDir: workspace.conflictPath,
18290
- branch: workspace.branch,
18291
- base: workspace.base || integrationBranch
18292
- });
18293
- adopted = true;
18294
- } catch (error) {
18295
- console.warn(`[session ${id}] survivor adopt failed: ${errorMessage(error)} - running in place`);
18296
- }
18297
- if (adopted && lifecycleState.worktreeDir) {
18298
- lifecycleState.worktreeNotice = null;
18299
- await Promise.resolve(gitWorkspace.populate({
18300
- projectPath: currentProjectPath(),
18301
- wtDir: lifecycleState.worktreeDir,
18302
- shareList: worktreeShare
18303
- })).catch(() => {});
18304
- port.emit("worktree-ready", {
18305
- id,
18306
- worktreeDir: lifecycleState.worktreeDir,
18307
- branch: workspace.branch,
18308
- base: effectiveIntegrationBranch()
18309
- });
18310
- await seedWorktreeDependencies(currentProjectPath(), lifecycleState.worktreeDir, effectiveIntegrationBranch());
18311
- return true;
18312
- }
18313
- lifecycleState.worktreeNotice = `session branch already checked out at ${workspace.conflictPath}; running in place`;
18314
- port.emit("worktree-blocked", {
18315
- id,
18316
- branch: effectiveIntegrationBranch(),
18317
- notice: lifecycleState.worktreeNotice
18318
- });
18319
- }
18320
- if (!workspace || !workspace.isGit) {
18321
- lifecycleState.worktreeDir = null;
18322
- lifecycleState.isWorktree = false;
18500
+ await gitOut(["rev-parse", "--is-inside-work-tree"], opts);
18323
18501
  return true;
18502
+ } catch (error) {
18503
+ const failure = error;
18504
+ if (`${String(failure?.stderr ?? "")}\n${String(failure?.message ?? "")}`.includes("not a git repository")) return false;
18505
+ throw error;
18324
18506
  }
18325
- lifecycleState.workspace = workspace;
18326
- lifecycleState.effectiveBase = workspace.base || null;
18327
- lifecycleState.worktreeDir = workspace.cwd;
18328
- lifecycleState.commonGitDir = resolveCommonGitDir();
18329
- lifecycleState.baseSha = workspace.baseSha || null;
18330
- lifecycleState.worktreeNotice = null;
18331
- setMergeStatus("none", {}, { emit: false });
18332
- lifecycleState.isWorktree = true;
18333
- const syncWarning = forkSyncWarning(initialSync, workspace.base || baseBranch);
18334
- if (syncWarning) port.emit("worktree-warning", {
18335
- id,
18336
- branch: workspace.base || null,
18337
- notice: syncWarning
18338
- });
18339
- port.emit("worktree-ready", {
18340
- id,
18341
- worktreeDir: workspace.cwd,
18342
- branch: workspace.branch,
18343
- base: workspace.base || null
18344
- });
18345
- await seedWorktreeDependencies(currentProjectPath(), workspace.cwd, workspace.base || null);
18346
- return true;
18347
18507
  }
18348
- async function seedWorktreeDependencies(mainCheckout, worktreeDir, branch) {
18349
- if (!seedDependencies) return;
18350
- const outcome = await seedDependencies({
18351
- mainCheckout,
18352
- worktreeDir
18353
- });
18354
- if (outcome.action === "cloned") {
18355
- console.log(`[session ${id}] cloned node_modules into ${worktreeDir} (${outcome.dirs.join(", ")}) in ${outcome.elapsedMs}ms`);
18356
- if (!outcome.staleDirs.length) return;
18357
- const staleNotice = describeStaleDirs(outcome.staleDirs);
18358
- console.log(`[session ${id}] ${staleNotice}`);
18359
- port.emit("worktree-warning", {
18360
- id,
18361
- branch,
18362
- notice: staleNotice
18363
- });
18364
- return;
18365
- }
18366
- const reason = describeDependencyCloneSkip(outcome.reason);
18367
- console.log(`[session ${id}] did not clone node_modules into ${worktreeDir}: ${reason}`);
18368
- if (outcome.notify) port.emit("worktree-warning", {
18369
- id,
18508
+ async function readBranchSync(branch) {
18509
+ const opts = {
18510
+ cwd: currentProjectPath(),
18511
+ timeoutMs: 1e4
18512
+ };
18513
+ if (!await isGitRepository(opts)) return noUpstream(branch);
18514
+ const upstream = await readUpstreamOf(branch, opts);
18515
+ if (!upstream) return noUpstream(branch);
18516
+ return applyBaseSyncDemotion({
18370
18517
  branch,
18371
- notice: reason
18518
+ upstream,
18519
+ fetched: await fetchBranch(parseRemoteFromUpstream(upstream), branch, opts),
18520
+ ...await branchCounts(upstream, branch, opts)
18372
18521
  });
18373
18522
  }
18374
- async function hasUnmergedWork() {
18375
- if (!lifecycleState.worktreeDir) return false;
18376
- if (!gitWorkspace || !lifecycleState.workspace) return true;
18377
- try {
18378
- return await gitWorkspace.hasUnmergedWork({
18379
- projectPath: currentProjectPath(),
18380
- workspace: lifecycleState.workspace,
18381
- integrationBranch: effectiveIntegrationBranch(),
18382
- configuredIntegrationBranch: integrationBranch
18383
- });
18384
- } catch {
18385
- return true;
18386
- }
18387
- }
18388
- function clearWorktreeState(status) {
18389
- lifecycleState.workspace = null;
18390
- lifecycleState.worktreeDir = null;
18391
- lifecycleState.commonGitDir = null;
18392
- lifecycleState.isWorktree = false;
18393
- setMergeStatus(status);
18394
- }
18395
- let isWorkspaceWorkDiscardConfirmed = false;
18396
- function confirmWorkspaceWorkDiscard() {
18397
- isWorkspaceWorkDiscardConfirmed = true;
18523
+ async function resyncBranchBody() {
18524
+ const branch = effectiveIntegrationBranch();
18525
+ if (!branch || !currentProjectPath()) return {
18526
+ ...noUpstream(branch),
18527
+ action: "none",
18528
+ error: null
18529
+ };
18530
+ return resyncKnownBranch(branch).catch((error) => ({
18531
+ ...branchSyncFailure(branch, error),
18532
+ action: "none"
18533
+ }));
18398
18534
  }
18399
- async function findWorkspaceKeptWork() {
18400
- if (!workspaceMembers?.ok) return [];
18401
- return workspaceMembers.members.findKeptWork();
18402
- }
18403
- async function releaseWorkspaceMembers(members, keepRepoPaths = []) {
18404
- const released = await members.release({
18405
- keepRepoPaths,
18406
- discardWork: isWorkspaceWorkDiscardConfirmed
18407
- });
18408
- if (released.kept.length === 0) return;
18409
- console.warn(`[session ${id}] kept workspace members: ${released.kept.map((kept) => `${kept.path} (${kept.reason})`).join(", ")}`);
18410
- }
18411
- async function releaseDroppedWorkspaceMembers(keepRepoPaths) {
18412
- if (!workspaceMembers?.ok) return;
18413
- await releaseWorkspaceMembers(workspaceMembers.members, keepRepoPaths);
18414
- }
18415
- async function discardWorktree() {
18416
- if (workspaceMembers?.ok) return releaseWorkspaceMembers(workspaceMembers.members);
18417
- stopWatching();
18418
- if (gitWorkspace && lifecycleState.workspace) try {
18419
- await gitWorkspace.discard({
18420
- projectPath: currentProjectPath(),
18421
- workspace: lifecycleState.workspace,
18422
- cause: "session"
18423
- });
18424
- } catch {}
18425
- clearWorktreeState("none");
18426
- }
18427
- async function discardIfClean() {
18428
- if (!lifecycleState.worktreeDir) return false;
18429
- if (await hasUnmergedWork()) return false;
18430
- await discardWorktree();
18431
- return true;
18432
- }
18433
- async function settleOnExit() {
18434
- const session = port.state();
18435
- if (session.isDestroyed || !gitWorkspace || !lifecycleState.workspace) return;
18436
- if (!RESTARTABLE_STATES.includes(session.state)) return;
18437
- if (await discardIfClean()) return;
18438
- setMergeStatus("pending-review");
18439
- }
18440
- function pasteMergePrompt() {
18441
- const session = port.state();
18442
- if (session.isDestroyed) return {
18443
- ok: false,
18444
- reason: "destroyed"
18535
+ async function resyncKnownBranch(branch) {
18536
+ const opts = {
18537
+ cwd: currentProjectPath(),
18538
+ timeoutMs: 1e4
18445
18539
  };
18446
- if (lifecycleState.mergeStatus !== "parked") return {
18447
- ok: false,
18448
- reason: "not-parked"
18540
+ if (!await isGitRepository(opts)) return {
18541
+ ...noUpstream(branch),
18542
+ action: "none",
18543
+ error: null
18449
18544
  };
18450
- if (!session.hasLivePty) return {
18451
- ok: false,
18452
- reason: "no-pty"
18545
+ const upstream = await readUpstreamOf(branch, opts);
18546
+ if (!upstream) return {
18547
+ ...noUpstream(branch),
18548
+ action: "none",
18549
+ error: null
18453
18550
  };
18454
- return port.pasteText(buildMergePrompt({
18455
- branch: lifecycleState.workspace?.branch || void 0,
18456
- target: effectiveIntegrationBranch() || void 0,
18457
- reason: lifecycleState.mergeReason || void 0,
18458
- conflicts: lifecycleState.mergeConflicts,
18459
- worktreeDir: lifecycleState.worktreeDir || void 0
18460
- }));
18461
- }
18462
- async function resolveEffectiveBase(opts) {
18463
- if (lifecycleState.workspace?.base) {
18464
- lifecycleState.effectiveBase = lifecycleState.workspace.base;
18465
- return lifecycleState.effectiveBase;
18466
- }
18467
- const branch = branchFromHeadRef((await gitLookup([
18468
- "symbolic-ref",
18469
- "--quiet",
18551
+ const remote = parseRemoteFromUpstream(upstream);
18552
+ const fetched = await fetchBranch(remote, branch, opts);
18553
+ const before = await branchCounts(upstream, branch, opts);
18554
+ const checkedOut = (await gitOut([
18555
+ "rev-parse",
18556
+ "--abbrev-ref",
18470
18557
  "HEAD"
18471
- ], opts))?.trim() ?? "");
18472
- const upstream = branch ? await readUpstreamOf(branch, opts) : null;
18473
- if (upstream && !isOwnRemoteCopy(upstream, branch)) {
18474
- lifecycleState.effectiveBase = branchFromRemoteRef(upstream);
18475
- return upstream;
18558
+ ], opts)).trim();
18559
+ const decision = decideResyncAction(before.state, checkedOut === branch);
18560
+ let action = "none";
18561
+ let error = null;
18562
+ const command = buildResyncCommand(decision, {
18563
+ upstream,
18564
+ branch,
18565
+ remote
18566
+ });
18567
+ if (command) try {
18568
+ await gitOut(command.args, {
18569
+ ...opts,
18570
+ timeoutMs: command.timeoutMs ?? opts.timeoutMs
18571
+ });
18572
+ action = command.successAction;
18573
+ } catch (commandError) {
18574
+ console.warn(`[session ${id}] resync of ${branch} failed: ${errorMessage(commandError)}`);
18575
+ error = firstGitErrorLine(commandError);
18476
18576
  }
18477
- lifecycleState.effectiveBase = effectiveIntegrationBranch();
18478
- return lifecycleState.effectiveBase;
18577
+ return applyBaseSyncDemotion({
18578
+ branch,
18579
+ upstream,
18580
+ fetched,
18581
+ ...await branchCounts(upstream, branch, opts),
18582
+ action,
18583
+ error
18584
+ });
18479
18585
  }
18480
- async function resolveVerifiedBaseRef(opts) {
18481
- const candidate = await resolveEffectiveBase(opts);
18482
- if (candidate && await gitLookup([
18483
- "rev-parse",
18484
- "--verify",
18485
- "--quiet",
18486
- candidate
18487
- ], opts) !== null) return {
18488
- ref: await freshestBaseRef(candidate, opts),
18489
- verified: true
18490
- };
18491
- return {
18492
- ref: lifecycleState.baseSha || null,
18493
- verified: false
18494
- };
18586
+ function resyncBranch() {
18587
+ if (lifecycleState.resyncPromise) return lifecycleState.resyncPromise;
18588
+ lifecycleState.resyncPromise = resyncBranchBody().finally(() => {
18589
+ lifecycleState.resyncPromise = null;
18590
+ });
18591
+ return lifecycleState.resyncPromise;
18495
18592
  }
18496
- async function freshestBaseRef(baseBranch, opts) {
18497
- const localRef = `refs/heads/${baseBranch}`;
18498
- const originRef = `refs/remotes/origin/${baseBranch}`;
18499
- const existingRefs = (await gitOut([
18500
- "for-each-ref",
18501
- "--format=%(refname)",
18502
- localRef,
18503
- originRef
18504
- ], opts)).split("\n");
18505
- if (!existingRefs.includes(localRef) || !existingRefs.includes(originRef)) return baseBranch;
18506
- return await gitLookup([
18507
- "merge-base",
18508
- "--is-ancestor",
18509
- localRef,
18510
- originRef
18511
- ], opts) !== null ? `origin/${baseBranch}` : baseBranch;
18593
+ return {
18594
+ getBranchSync,
18595
+ resyncBranch
18596
+ };
18597
+ }
18598
+ //#endregion
18599
+ //#region session/session-worktree-lifecycle.ts
18600
+ var WORKTREE_CHECK_DEBOUNCE_MS = 400;
18601
+ var GIT_NOT_FOUND_EXIT_CODE = 1;
18602
+ function workspaceMemberGit(gitWorkspace) {
18603
+ if (!gitWorkspace) return null;
18604
+ const { ensureWorkspaceMember, removeWorkspaceMember, describeWorkspaceMemberWork, recordOwnedFolder, forgetRemovedPath } = gitWorkspace;
18605
+ if (!ensureWorkspaceMember || !removeWorkspaceMember || !describeWorkspaceMemberWork || !recordOwnedFolder || !forgetRemovedPath) return null;
18606
+ return {
18607
+ ensureWorkspaceMember,
18608
+ removeWorkspaceMember,
18609
+ describeWorkspaceMemberWork,
18610
+ recordOwnedFolder,
18611
+ forgetRemovedPath
18612
+ };
18613
+ }
18614
+ async function readGitStrict(args, options) {
18615
+ const command = await runGit(args, {
18616
+ ...options,
18617
+ trim: false
18618
+ });
18619
+ if (!command.ok) throw gitCommandFailure(args, command, options.timeoutMs);
18620
+ return command.out;
18621
+ }
18622
+ function stopWatcher(watcher) {
18623
+ if (!watcher) return null;
18624
+ try {
18625
+ watcher.stop();
18626
+ } catch {}
18627
+ return null;
18628
+ }
18629
+ function detectLinkedWorktree(directory) {
18630
+ return readWorktreeGitdirPointer(directory) !== null;
18631
+ }
18632
+ function setUpWorkspaceMembers({ folder, sessionId, sessionName, repoPaths, shareList, gitWorkspace }) {
18633
+ const planned = planWorkspaceMembers({
18634
+ folder,
18635
+ sessionId,
18636
+ repoPaths
18637
+ });
18638
+ if (!planned.ok) return planned;
18639
+ const memberGit = workspaceMemberGit(gitWorkspace);
18640
+ if (!memberGit) return {
18641
+ ok: false,
18642
+ error: "Git workspace is unavailable"
18643
+ };
18644
+ return {
18645
+ ok: true,
18646
+ members: createSessionWorkspaceMembers({
18647
+ plan: planned.plan,
18648
+ owner: `session:${sessionId}`,
18649
+ sessionName,
18650
+ shareList,
18651
+ gitWorkspace: memberGit
18652
+ })
18653
+ };
18654
+ }
18655
+ function createSessionWorktreeLifecycle({ id, projectPath, integrationBranch = null, gitWorkspace = null, autoRebase = true, syncOnStart = true, liveWorktreeReview = true, worktreeRoot = null, worktreeShare = null, workspaceRepos = null, seedDependencies = null, sessionName = id, port }) {
18656
+ const currentProjectPath = () => port.projectPath ? port.projectPath() : projectPath;
18657
+ function gitOut(args, options) {
18658
+ return readGitStrict(args, options);
18512
18659
  }
18513
- function diffGitOptions(cwd) {
18514
- return {
18515
- cwd,
18516
- timeoutMs: 15e3,
18517
- maxBuffer: 67108864
18518
- };
18660
+ function gitLookup(args, options) {
18661
+ return gitOut(args, options).catch((error) => {
18662
+ if (error?.code === GIT_NOT_FOUND_EXIT_CODE) return null;
18663
+ throw error;
18664
+ });
18519
18665
  }
18520
- async function resolveDiffBase(opts) {
18521
- const { ref: baseRef, verified } = await resolveVerifiedBaseRef(opts);
18522
- if (verified) return {
18523
- base: (await gitLookup([
18524
- "merge-base",
18525
- baseRef,
18526
- "HEAD"
18527
- ], opts))?.trim() ?? "",
18528
- aheadCount: (await gitOut([
18529
- "rev-list",
18530
- "--count",
18531
- `${baseRef}..HEAD`
18532
- ], opts)).trim(),
18533
- ref: baseRef,
18534
- verified
18535
- };
18536
- if (!baseRef) return {
18537
- base: "",
18538
- aheadCount: "0",
18539
- ref: null,
18540
- verified
18541
- };
18542
- return {
18543
- base: baseRef,
18544
- aheadCount: (await gitOut([
18545
- "rev-list",
18546
- "--count",
18547
- `${baseRef}..HEAD`
18548
- ], opts)).trim(),
18549
- ref: null,
18550
- verified
18551
- };
18666
+ async function readUpstreamOf(branch, options) {
18667
+ return parseBranchUpstream(await gitOut([
18668
+ "for-each-ref",
18669
+ `--format=${BRANCH_UPSTREAM_FORMAT}`,
18670
+ `refs/heads/${branch}`
18671
+ ], options), branch);
18552
18672
  }
18553
- async function readChangeScope(name, root, base, sessionPathPrefix) {
18554
- const run = (args) => gitOut(args, diffGitOptions(root));
18555
- const nul = String.fromCharCode(0);
18556
- const trackedNameStatus = await run([
18557
- "diff",
18558
- "-z",
18559
- "--name-status",
18560
- "-M",
18561
- "HEAD"
18562
- ]);
18563
- const untrackedPaths = (await run([
18564
- "ls-files",
18565
- "-z",
18566
- "--others",
18567
- "--exclude-standard"
18568
- ])).split(nul).filter(Boolean);
18569
- return {
18570
- name,
18571
- root,
18572
- sessionPathPrefix,
18573
- base: base || null,
18574
- committedNameStatus: base ? await run([
18575
- "diff",
18576
- "-z",
18577
- "--name-status",
18578
- "-M",
18579
- `${base}..HEAD`
18580
- ]) : "",
18581
- uncommittedNameStatus: trackedNameStatus + untrackedPaths.map((untrackedPath) => `?${nul}${untrackedPath}${nul}`).join("")
18582
- };
18673
+ const workspaceMembers = workspaceRepos ? setUpWorkspaceMembers({
18674
+ folder: currentProjectPath(),
18675
+ sessionId: id,
18676
+ sessionName,
18677
+ repoPaths: workspaceRepos,
18678
+ shareList: worktreeShare,
18679
+ gitWorkspace
18680
+ }) : null;
18681
+ const lifecycleState = {
18682
+ worktreeDir: null,
18683
+ commonGitDir: null,
18684
+ baseSha: null,
18685
+ workspace: null,
18686
+ mergeStatus: "none",
18687
+ mergeReason: null,
18688
+ mergeConflicts: [],
18689
+ worktreeNotice: null,
18690
+ effectiveBase: null,
18691
+ isWorktree: detectLinkedWorktree(currentProjectPath()),
18692
+ autoRebasing: false,
18693
+ rebaseConflictKey: null,
18694
+ resyncPromise: null,
18695
+ worktreeWatcher: null,
18696
+ integrationWatcher: null,
18697
+ rerereWatcher: null,
18698
+ checkTimer: createCoalescedTimer({
18699
+ mode: "leading",
18700
+ delayMs: WORKTREE_CHECK_DEBOUNCE_MS,
18701
+ run: () => {
18702
+ api.checkWorktreeChange().catch(recordWorktreeCheckFailure);
18703
+ }
18704
+ }),
18705
+ lastSignature: null,
18706
+ lastLoggedCheckFailure: null,
18707
+ provisionedMembers: null
18708
+ };
18709
+ function effectiveIntegrationBranch() {
18710
+ return lifecycleState.workspace?.base || lifecycleState.effectiveBase || integrationBranch || null;
18583
18711
  }
18584
- async function memberMergeBase(member) {
18585
- const opts = diffGitOptions(member.dir);
18586
- const candidates = member.base ? [
18587
- await freshestBaseRef(member.base, opts),
18588
- `origin/${member.base}`,
18589
- "origin/HEAD"
18590
- ] : ["origin/HEAD"];
18591
- for (const candidate of candidates) {
18592
- if (await gitLookup([
18593
- "rev-parse",
18594
- "--verify",
18595
- "--quiet",
18596
- candidate
18597
- ], opts) === null) continue;
18598
- return {
18599
- ref: candidate,
18600
- sha: (await gitLookup([
18601
- "merge-base",
18602
- candidate,
18603
- "HEAD"
18604
- ], opts))?.trim() ?? ""
18605
- };
18606
- }
18712
+ function snapshot() {
18607
18713
  return {
18608
- ref: null,
18609
- sha: ""
18714
+ worktreeDir: lifecycleState.worktreeDir,
18715
+ commonGitDir: lifecycleState.commonGitDir,
18716
+ baseSha: lifecycleState.baseSha,
18717
+ mergeStatus: lifecycleState.mergeStatus,
18718
+ mergeReason: lifecycleState.mergeReason,
18719
+ mergeConflicts: [...lifecycleState.mergeConflicts],
18720
+ worktreeNotice: lifecycleState.worktreeNotice,
18721
+ effectiveBase: effectiveIntegrationBranch(),
18722
+ isWorktree: lifecycleState.isWorktree,
18723
+ isWorkspace: workspaceMembers !== null,
18724
+ isAutoRebasing: lifecycleState.autoRebasing,
18725
+ hasConflictCooldown: Boolean(lifecycleState.rebaseConflictKey),
18726
+ hasPendingCheck: lifecycleState.checkTimer.isArmed
18610
18727
  };
18611
18728
  }
18612
- async function getChangeScopes() {
18613
- const members = lifecycleState.provisionedMembers;
18614
- if (members) {
18615
- const scopes = [];
18616
- for (const member of members) {
18617
- if (!(await fs.promises.stat(member.dir).catch(() => null))?.isDirectory()) continue;
18618
- scopes.push(await readChangeScope(member.name, member.dir, (await memberMergeBase(member)).sha, `${member.name}/`));
18619
- }
18620
- return scopes;
18621
- }
18622
- const worktreeDir = lifecycleState.worktreeDir;
18623
- if (!worktreeDir) return [];
18624
- const { base } = await resolveDiffBase(diffGitOptions(worktreeDir));
18625
- return [await readChangeScope(path.basename(currentProjectPath()), worktreeDir, base, "")];
18626
- }
18627
- async function readMemberDiff(member) {
18628
- const run = (args) => gitOut(args, diffGitOptions(member.dir));
18629
- const prefixArgs = [`--src-prefix=a/${member.name}/`, `--dst-prefix=b/${member.name}/`];
18630
- await markUntrackedIntentToAdd(member.dir);
18631
- const { ref: baseRef, sha: base } = await memberMergeBase(member);
18632
- const aheadCount = base ? (await run([
18633
- "rev-list",
18634
- "--count",
18635
- `${base}..HEAD`
18636
- ])).trim() : "0";
18637
- const readPrefixedDiff = async (range) => prefixRenameAndCopyHeaders(await run([
18638
- "diff",
18639
- ...prefixArgs,
18640
- range
18641
- ]), member.name);
18729
+ function getCarry() {
18730
+ if (!lifecycleState.worktreeDir || !lifecycleState.workspace) return null;
18642
18731
  return {
18643
- name: member.name,
18644
- committed: base ? {
18645
- stat: (await run([
18646
- "diff",
18647
- "--stat",
18648
- `${base}..HEAD`
18649
- ])).trim(),
18650
- diff: await readPrefixedDiff(`${base}..HEAD`)
18651
- } : {
18652
- stat: "",
18653
- diff: ""
18654
- },
18655
- uncommitted: {
18656
- stat: (await run([
18657
- "diff",
18658
- "--stat",
18659
- "HEAD"
18660
- ])).trim(),
18661
- diff: await readPrefixedDiff("HEAD")
18662
- },
18663
- hasCommits: aheadCount !== "" && aheadCount !== "0",
18664
- baseRef,
18665
- baseSha: base
18732
+ worktreeDir: lifecycleState.worktreeDir,
18733
+ branch: lifecycleState.workspace.branch || null,
18734
+ base: lifecycleState.workspace.base || null
18666
18735
  };
18667
18736
  }
18668
- async function getWorkspaceDiff(members) {
18669
- const memberDiffs = [];
18670
- for (const member of members) {
18671
- if (!(await fs.promises.stat(member.dir).catch(() => null))?.isDirectory()) continue;
18672
- memberDiffs.push(await readMemberDiff(member));
18673
- }
18674
- const joinSection = (section) => ({
18675
- stat: memberDiffs.filter((memberDiff) => memberDiff[section].stat).map((memberDiff) => `${memberDiff.name}/\n${memberDiff[section].stat}`).join("\n"),
18676
- diff: memberDiffs.map((memberDiff) => memberDiff[section].diff).join("")
18737
+ function hasOwnWorktree() {
18738
+ return Boolean(gitWorkspace && lifecycleState.workspace);
18739
+ }
18740
+ function setMergeStatus(status, detail = {}, { emit = true } = {}) {
18741
+ Object.assign(lifecycleState, projectMergeState(status, detail));
18742
+ if (!emit) return;
18743
+ port.emit("merge-status", {
18744
+ id,
18745
+ mergeStatus: status,
18746
+ ...detail
18677
18747
  });
18678
- return {
18679
- committed: joinSection("committed"),
18680
- uncommitted: joinSection("uncommitted"),
18681
- hasCommits: memberDiffs.some((memberDiff) => memberDiff.hasCommits),
18682
- bases: memberDiffs.filter((memberDiff) => memberDiff.baseSha).map((memberDiff) => ({
18683
- member: memberDiff.name,
18684
- ref: memberDiff.baseRef,
18685
- sha: memberDiff.baseSha,
18686
- verified: true
18687
- }))
18688
- };
18689
18748
  }
18690
- async function markUntrackedIntentToAdd(dir) {
18749
+ const isMerging = () => lifecycleState.mergeStatus === "merging";
18750
+ function effectiveCwd() {
18751
+ return lifecycleState.worktreeDir || currentProjectPath();
18752
+ }
18753
+ function refreshGitContext() {
18754
+ const next = detectLinkedWorktree(effectiveCwd());
18755
+ if (next === lifecycleState.isWorktree) return false;
18756
+ lifecycleState.isWorktree = next;
18757
+ return true;
18758
+ }
18759
+ function resolveCommonGitDir() {
18760
+ if (!lifecycleState.worktreeDir) return null;
18691
18761
  try {
18692
- await gitOut([
18693
- "add",
18694
- "-N",
18695
- "--",
18696
- "."
18697
- ], diffGitOptions(dir));
18698
- } catch (error) {
18699
- console.warn(`[session ${id}] intent-to-add in ${dir} failed: ${errorMessage(error)}`);
18762
+ const invocation = {
18763
+ args: ["rev-parse", "--git-common-dir"],
18764
+ env: process.env
18765
+ };
18766
+ const commonDir = execFileSync("git", invocation.args, {
18767
+ env: invocation.env,
18768
+ cwd: lifecycleState.worktreeDir,
18769
+ encoding: "utf8",
18770
+ stdio: [
18771
+ "ignore",
18772
+ "pipe",
18773
+ "pipe"
18774
+ ],
18775
+ timeout: 1e4
18776
+ });
18777
+ return path.resolve(lifecycleState.worktreeDir, commonDir.trim());
18778
+ } catch {
18779
+ return null;
18700
18780
  }
18701
18781
  }
18702
- async function getDiff() {
18703
- const empty = {
18704
- stat: "",
18705
- diff: ""
18706
- };
18707
- if (lifecycleState.provisionedMembers) return getWorkspaceDiff(lifecycleState.provisionedMembers);
18708
- if (!lifecycleState.worktreeDir) return {
18709
- committed: empty,
18710
- uncommitted: empty,
18711
- hasCommits: false,
18712
- bases: []
18713
- };
18714
- const opts = diffGitOptions(lifecycleState.worktreeDir);
18715
- const run = (args) => gitOut(args, opts);
18716
- await markUntrackedIntentToAdd(lifecycleState.worktreeDir);
18717
- const { base, aheadCount, ref, verified } = await resolveDiffBase(opts);
18718
- const committed = base ? {
18719
- stat: (await run([
18720
- "diff",
18721
- "--stat",
18722
- `${base}..HEAD`
18723
- ])).trim(),
18724
- diff: await run(["diff", `${base}..HEAD`])
18725
- } : empty;
18726
- const uncommitted = {
18727
- stat: (await run([
18728
- "diff",
18729
- "--stat",
18730
- "HEAD"
18731
- ])).trim(),
18732
- diff: await run(["diff", "HEAD"])
18733
- };
18734
- const healed = decideDiffSelfHeal(lifecycleState.mergeStatus, committed.diff, uncommitted.diff);
18735
- if (healed) setMergeStatus(healed);
18736
- return {
18737
- committed,
18738
- uncommitted,
18739
- hasCommits: aheadCount !== "" && aheadCount !== "0",
18740
- bases: base ? [{
18741
- member: null,
18742
- ref,
18743
- sha: base,
18744
- verified
18745
- }] : []
18746
- };
18782
+ function clearCheckTimer() {
18783
+ lifecycleState.checkTimer.cancel();
18784
+ }
18785
+ function scheduleCheck() {
18786
+ if (port.state().isDestroyed) return;
18787
+ if (!lifecycleState.worktreeDir && !lifecycleState.provisionedMembers) return;
18788
+ lifecycleState.checkTimer.schedule();
18789
+ }
18790
+ function stopWatching() {
18791
+ lifecycleState.worktreeWatcher = stopWatcher(lifecycleState.worktreeWatcher);
18792
+ lifecycleState.integrationWatcher = stopWatcher(lifecycleState.integrationWatcher);
18793
+ lifecycleState.rerereWatcher = stopWatcher(lifecycleState.rerereWatcher);
18794
+ clearCheckTimer();
18795
+ lifecycleState.lastSignature = null;
18796
+ }
18797
+ function onRerereRecorded() {
18798
+ const session = port.state();
18799
+ const verdict = decideRerereCooldownClear({
18800
+ enabled: autoRebase !== false && Boolean(gitWorkspace && lifecycleState.workspace),
18801
+ hasCooldown: Boolean(lifecycleState.rebaseConflictKey),
18802
+ teardownPending: session.isTeardownPending
18803
+ });
18804
+ if (!verdict.clear) return;
18805
+ port.recordDecision({
18806
+ kind: "rebase",
18807
+ ts: Date.now(),
18808
+ decision: "cooldown-cleared",
18809
+ reason: verdict.reason
18810
+ });
18811
+ lifecycleState.rebaseConflictKey = null;
18812
+ scheduleCheck();
18813
+ }
18814
+ function startWatching() {
18815
+ stopWatching();
18816
+ if (port.state().isDestroyed || !lifecycleState.worktreeDir) return;
18817
+ const onChange = () => scheduleCheck();
18818
+ lifecycleState.worktreeWatcher = createWorktreeWatcher({
18819
+ worktreeDir: lifecycleState.worktreeDir,
18820
+ onChange
18821
+ });
18822
+ lifecycleState.worktreeWatcher.start();
18823
+ const watchedBranch = effectiveIntegrationBranch();
18824
+ if (liveWorktreeReview === false || !lifecycleState.commonGitDir || !watchedBranch) return;
18825
+ lifecycleState.integrationWatcher = createIntegrationRefWatcher({
18826
+ commonGitDir: lifecycleState.commonGitDir,
18827
+ branch: watchedBranch,
18828
+ onChange
18829
+ });
18830
+ lifecycleState.integrationWatcher.start();
18831
+ lifecycleState.rerereWatcher = createRerereWatcher({
18832
+ commonGitDir: lifecycleState.commonGitDir,
18833
+ onChange: onRerereRecorded
18834
+ });
18835
+ lifecycleState.rerereWatcher.start();
18747
18836
  }
18748
- function noUpstream(branch) {
18749
- return {
18750
- branch: branch || null,
18751
- upstream: null,
18752
- state: decideBranchSyncState({ hasUpstream: false }),
18753
- ahead: 0,
18754
- behind: 0,
18755
- fetched: null
18837
+ function adoptWorktree({ worktreeDir, branch, base, baseSha = null, hasUnmergedWork: hasUnmerged = true, watch = true, emit = true }) {
18838
+ if (!worktreeDir) return;
18839
+ const resolvedBase = base || integrationBranch || null;
18840
+ lifecycleState.workspace = {
18841
+ cwd: worktreeDir,
18842
+ isGit: true,
18843
+ branch,
18844
+ base: resolvedBase,
18845
+ baseSha
18756
18846
  };
18847
+ lifecycleState.effectiveBase = resolvedBase;
18848
+ lifecycleState.worktreeDir = worktreeDir;
18849
+ lifecycleState.baseSha = baseSha;
18850
+ lifecycleState.commonGitDir = resolveCommonGitDir();
18851
+ lifecycleState.isWorktree = true;
18852
+ setMergeStatus(hasUnmerged ? "pending-review" : "none", {}, { emit });
18853
+ if (watch) startWatching();
18757
18854
  }
18758
- async function fetchBranch(remote, branch, opts) {
18855
+ const context = {
18856
+ id,
18857
+ projectPath,
18858
+ integrationBranch,
18859
+ gitWorkspace,
18860
+ syncOnStart,
18861
+ worktreeRoot,
18862
+ worktreeShare,
18863
+ seedDependencies,
18864
+ port,
18865
+ workspaceMembers,
18866
+ lifecycleState,
18867
+ currentProjectPath,
18868
+ gitOut,
18869
+ gitLookup,
18870
+ readUpstreamOf,
18871
+ effectiveIntegrationBranch,
18872
+ setMergeStatus
18873
+ };
18874
+ const { provision } = createWorktreeProvisioning(context, {
18875
+ adoptWorktree,
18876
+ resolveCommonGitDir,
18877
+ runAutoRebase,
18878
+ api: { computeWorktreeSignature: () => api.computeWorktreeSignature() }
18879
+ });
18880
+ const { resolveEffectiveBase, resolveVerifiedBaseRef, diffGitOptions, getChangeScopes, getDiff } = createWorktreeDiffScopes(context);
18881
+ const { getBranchSync, resyncBranch } = createWorktreeBranchSync(context);
18882
+ async function hasUnmergedWork() {
18883
+ if (!lifecycleState.worktreeDir) return false;
18884
+ if (!gitWorkspace || !lifecycleState.workspace) return true;
18759
18885
  try {
18760
- await gitOut([
18761
- "fetch",
18762
- "--quiet",
18763
- remote,
18764
- branch
18765
- ], {
18766
- ...opts,
18767
- timeoutMs: GIT_FETCH_TIMEOUT_MS,
18768
- replaceEnv: {
18769
- ...process.env,
18770
- GIT_TERMINAL_PROMPT: "0"
18771
- }
18886
+ return await gitWorkspace.hasUnmergedWork({
18887
+ projectPath: currentProjectPath(),
18888
+ workspace: lifecycleState.workspace,
18889
+ integrationBranch: effectiveIntegrationBranch(),
18890
+ configuredIntegrationBranch: integrationBranch
18772
18891
  });
18892
+ } catch {
18773
18893
  return true;
18774
- } catch (error) {
18775
- console.warn(`[session ${id}] fetch of ${remote}/${branch} failed: ${errorMessage(error)}`);
18776
- return false;
18777
18894
  }
18778
18895
  }
18779
- async function branchCounts(upstream, branch, opts) {
18780
- const counts = parseLeftRightCount(await gitOut([
18781
- "rev-list",
18782
- "--left-right",
18783
- "--count",
18784
- `${upstream}...${branch}`
18785
- ], opts));
18786
- return {
18787
- ahead: counts ? counts.ahead : 0,
18788
- behind: counts ? counts.behind : 0,
18789
- state: decideBranchSyncState({
18790
- hasUpstream: true,
18791
- ahead: counts?.ahead,
18792
- behind: counts?.behind
18793
- })
18794
- };
18896
+ function clearWorktreeState(status) {
18897
+ lifecycleState.workspace = null;
18898
+ lifecycleState.worktreeDir = null;
18899
+ lifecycleState.commonGitDir = null;
18900
+ lifecycleState.isWorktree = false;
18901
+ setMergeStatus(status);
18795
18902
  }
18796
- function applyBaseSyncDemotion(sync) {
18797
- const nextStatus = decideBaseSyncDemotion(lifecycleState.mergeStatus, lifecycleState.mergeReason, sync.state);
18798
- if (nextStatus !== null) setMergeStatus(nextStatus);
18799
- return sync;
18903
+ let isWorkspaceWorkDiscardConfirmed = false;
18904
+ function confirmWorkspaceWorkDiscard() {
18905
+ isWorkspaceWorkDiscardConfirmed = true;
18800
18906
  }
18801
- function branchSyncFailure(branch, error) {
18802
- console.warn(`[session ${id}] branch sync check of ${branch} failed: ${errorMessage(error)}`);
18803
- return {
18804
- branch,
18805
- upstream: null,
18806
- state: decideBranchSyncState({ hasUpstream: true }),
18807
- ahead: 0,
18808
- behind: 0,
18809
- fetched: null,
18810
- error: firstGitErrorLine(error)
18811
- };
18907
+ async function findWorkspaceKeptWork() {
18908
+ if (!workspaceMembers?.ok) return [];
18909
+ return workspaceMembers.members.findKeptWork();
18812
18910
  }
18813
- async function getBranchSync() {
18814
- const branch = effectiveIntegrationBranch();
18815
- if (!branch || !currentProjectPath()) return noUpstream(branch);
18816
- return readBranchSync(branch).catch((error) => branchSyncFailure(branch, error));
18911
+ async function releaseWorkspaceMembers(members, keepRepoPaths = []) {
18912
+ const released = await members.release({
18913
+ keepRepoPaths,
18914
+ discardWork: isWorkspaceWorkDiscardConfirmed
18915
+ });
18916
+ if (released.kept.length === 0) return;
18917
+ console.warn(`[session ${id}] kept workspace members: ${released.kept.map((kept) => `${kept.path} (${kept.reason})`).join(", ")}`);
18817
18918
  }
18818
- async function isGitRepository(opts) {
18819
- try {
18820
- await gitOut(["rev-parse", "--is-inside-work-tree"], opts);
18821
- return true;
18822
- } catch (error) {
18823
- const failure = error;
18824
- if (`${String(failure?.stderr ?? "")}\n${String(failure?.message ?? "")}`.includes("not a git repository")) return false;
18825
- throw error;
18826
- }
18919
+ async function releaseDroppedWorkspaceMembers(keepRepoPaths) {
18920
+ if (!workspaceMembers?.ok) return;
18921
+ await releaseWorkspaceMembers(workspaceMembers.members, keepRepoPaths);
18827
18922
  }
18828
- async function readBranchSync(branch) {
18829
- const opts = {
18830
- cwd: currentProjectPath(),
18831
- timeoutMs: 1e4
18832
- };
18833
- if (!await isGitRepository(opts)) return noUpstream(branch);
18834
- const upstream = await readUpstreamOf(branch, opts);
18835
- if (!upstream) return noUpstream(branch);
18836
- return applyBaseSyncDemotion({
18837
- branch,
18838
- upstream,
18839
- fetched: await fetchBranch(parseRemoteFromUpstream(upstream), branch, opts),
18840
- ...await branchCounts(upstream, branch, opts)
18841
- });
18923
+ async function discardWorktree() {
18924
+ if (workspaceMembers?.ok) return releaseWorkspaceMembers(workspaceMembers.members);
18925
+ stopWatching();
18926
+ if (gitWorkspace && lifecycleState.workspace) try {
18927
+ await gitWorkspace.discard({
18928
+ projectPath: currentProjectPath(),
18929
+ workspace: lifecycleState.workspace,
18930
+ cause: "session"
18931
+ });
18932
+ } catch {}
18933
+ clearWorktreeState("none");
18842
18934
  }
18843
- async function resyncBranchBody() {
18844
- const branch = effectiveIntegrationBranch();
18845
- if (!branch || !currentProjectPath()) return {
18846
- ...noUpstream(branch),
18847
- action: "none",
18848
- error: null
18849
- };
18850
- return resyncKnownBranch(branch).catch((error) => ({
18851
- ...branchSyncFailure(branch, error),
18852
- action: "none"
18853
- }));
18935
+ async function discardIfClean() {
18936
+ if (!lifecycleState.worktreeDir) return false;
18937
+ if (await hasUnmergedWork()) return false;
18938
+ await discardWorktree();
18939
+ return true;
18854
18940
  }
18855
- async function resyncKnownBranch(branch) {
18856
- const opts = {
18857
- cwd: currentProjectPath(),
18858
- timeoutMs: 1e4
18941
+ async function settleOnExit() {
18942
+ const session = port.state();
18943
+ if (session.isDestroyed || !gitWorkspace || !lifecycleState.workspace) return;
18944
+ if (!RESTARTABLE_STATES.includes(session.state)) return;
18945
+ if (await discardIfClean()) return;
18946
+ setMergeStatus("pending-review");
18947
+ }
18948
+ function pasteMergePrompt() {
18949
+ const session = port.state();
18950
+ if (session.isDestroyed) return {
18951
+ ok: false,
18952
+ reason: "destroyed"
18859
18953
  };
18860
- if (!await isGitRepository(opts)) return {
18861
- ...noUpstream(branch),
18862
- action: "none",
18863
- error: null
18954
+ if (lifecycleState.mergeStatus !== "parked") return {
18955
+ ok: false,
18956
+ reason: "not-parked"
18864
18957
  };
18865
- const upstream = await readUpstreamOf(branch, opts);
18866
- if (!upstream) return {
18867
- ...noUpstream(branch),
18868
- action: "none",
18869
- error: null
18958
+ if (!session.hasLivePty) return {
18959
+ ok: false,
18960
+ reason: "no-pty"
18870
18961
  };
18871
- const remote = parseRemoteFromUpstream(upstream);
18872
- const fetched = await fetchBranch(remote, branch, opts);
18873
- const before = await branchCounts(upstream, branch, opts);
18874
- const checkedOut = (await gitOut([
18875
- "rev-parse",
18876
- "--abbrev-ref",
18877
- "HEAD"
18878
- ], opts)).trim();
18879
- const decision = decideResyncAction(before.state, checkedOut === branch);
18880
- let action = "none";
18881
- let error = null;
18882
- const command = buildResyncCommand(decision, {
18883
- upstream,
18884
- branch,
18885
- remote
18886
- });
18887
- if (command) try {
18888
- await gitOut(command.args, {
18889
- ...opts,
18890
- timeoutMs: command.timeoutMs ?? opts.timeoutMs
18891
- });
18892
- action = command.successAction;
18893
- } catch (commandError) {
18894
- console.warn(`[session ${id}] resync of ${branch} failed: ${errorMessage(commandError)}`);
18895
- error = firstGitErrorLine(commandError);
18896
- }
18897
- return applyBaseSyncDemotion({
18898
- branch,
18899
- upstream,
18900
- fetched,
18901
- ...await branchCounts(upstream, branch, opts),
18902
- action,
18903
- error
18904
- });
18905
- }
18906
- function resyncBranch() {
18907
- if (lifecycleState.resyncPromise) return lifecycleState.resyncPromise;
18908
- lifecycleState.resyncPromise = resyncBranchBody().finally(() => {
18909
- lifecycleState.resyncPromise = null;
18910
- });
18911
- return lifecycleState.resyncPromise;
18962
+ return port.pasteText(buildMergePrompt({
18963
+ branch: lifecycleState.workspace?.branch || void 0,
18964
+ target: effectiveIntegrationBranch() || void 0,
18965
+ reason: lifecycleState.mergeReason || void 0,
18966
+ conflicts: lifecycleState.mergeConflicts,
18967
+ worktreeDir: lifecycleState.worktreeDir || void 0
18968
+ }));
18912
18969
  }
18913
18970
  async function computeWorktreeSignature() {
18914
18971
  const worktreeDir = lifecycleState.worktreeDir;