claude-code-session-manager 0.130.2 → 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-CYXre0J-.js +2 -0
  4. package/dist/assets/{AppSettings-Bpwynea4.js → AppSettings-xNSfCj8e.js} +2 -2
  5. package/dist/assets/{Button-DSoqrxCB.js → Button-BWljh5IK.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-FUC2hZlp.js +1 -0
  7. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  8. package/dist/assets/{History-DzMo9Otn.js → History-BvNmY9OQ.js} +2 -2
  9. package/dist/assets/{Library-C5wKMTSn.js → Library-DVXk77zA.js} +12 -12
  10. package/dist/assets/{ListDetail-DDQ1S0yu.js → ListDetail-DAAx__24.js} +1 -1
  11. package/dist/assets/{Panel-B-3NWUlv.js → Panel-g2D-e-RM.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BDuHJwaO.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-CUChwz4Z.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  14. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  15. package/dist/assets/Settings-B23RsRfm.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-C6JEdypC.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  17. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  18. package/dist/assets/{SourceChip-DcBNYYhe.js → SourceChip-jrC0vjfw.js} +1 -1
  19. package/dist/assets/SystemPrompt-hHoBEnYb.js +1 -0
  20. package/dist/assets/{TiptapBody-DiVYC-_O.js → TiptapBody-FkUqxO9u.js} +1 -1
  21. package/dist/assets/{Toggle-Cs3k6I96.js → Toggle-DQMNWZKT.js} +1 -1
  22. package/dist/assets/ViewTabs-DGU0ZuxB.js +1 -0
  23. package/dist/assets/{VoiceButton-C3NLotUZ.js → VoiceButton-BPPvDllh.js} +1 -1
  24. package/dist/assets/{historyTotals-f-E0L9Xw.js → historyTotals-D8Oc3wUK.js} +1 -1
  25. package/dist/assets/index-9ajPMXBg.js +3097 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-oXqzajWV.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +455 -427
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/scripts/scheduler-mcp-server.cjs +71 -0
  35. package/src/main/agentLibrary.cjs +81 -29
  36. package/src/main/agentsIpc.cjs +21 -16
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/index.cjs +9 -0
  39. package/src/main/ipcSchemas.cjs +35 -2
  40. package/src/main/lib/epic/epicMint.cjs +61 -6
  41. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  42. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  43. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  44. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  45. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  46. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +4 -0
  47. package/src/main/lib/git/branchSweep.cjs +9 -3
  48. package/src/main/lib/git/gitExec.cjs +8 -1
  49. package/src/main/lib/git/gitWorktree.cjs +771 -96
  50. package/src/main/lib/git/jobWorktree.cjs +3 -0
  51. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  52. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  53. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  54. package/src/main/lib/mdNetworkScan.cjs +555 -0
  55. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +22 -4
  57. package/src/main/lib/persona-macro/macroJobDispatch.cjs +17 -2
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  59. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  60. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  61. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  62. package/src/main/lib/promptSessionSchema.cjs +5 -0
  63. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  64. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  65. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  66. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  67. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  68. package/src/main/projectPages.cjs +51 -7
  69. package/src/main/runVerify.cjs +8 -3
  70. package/src/main/scheduler/budget.cjs +146 -7
  71. package/src/main/scheduler/gitTreeGuard.cjs +92 -20
  72. package/src/main/scheduler/reviewLadder.cjs +60 -0
  73. package/src/main/scheduler.cjs +477 -53
  74. package/src/main/seedAgentPersonas.cjs +1 -1
  75. package/src/preload/api.d.ts +250 -7
  76. package/src/preload/apiSurface.json +28 -0
  77. package/src/preload/index.cjs +6 -0
  78. package/src/seed/agents/competitive-analyst.md +69 -0
  79. package/src/seed/agents/competitive-researcher.md +75 -0
  80. package/src/seed/agents/validator.md +2 -2
  81. package/dist/assets/AgentLibrary-Bfj862qf.js +0 -2
  82. package/dist/assets/Extensions-BziIutWV.js +0 -13
  83. package/dist/assets/Memory-Bq5T33d2.js +0 -25
  84. package/dist/assets/Scheduler-CkGHMXvo.js +0 -16
  85. package/dist/assets/Settings-DGxvyajs.js +0 -2
  86. package/dist/assets/SystemPrompt-CfozyVQx.js +0 -1
  87. package/dist/assets/ViewTabs-DFXH03tb.js +0 -1
  88. package/dist/assets/index-CuAfFXNd.js +0 -3086
@@ -331,8 +331,15 @@ function branchNameFor(kind, key) {
331
331
  * directory, so a sibling checkout still living under the same hash dir can
332
332
  * never be destroyed by this call.
333
333
  */
334
- async function removeWorktreeDir(cwd, dir) {
334
+ async function removeWorktreeDir(cwd, dir, { key } = {}) {
335
335
  await pinStrandedHead({ cwd, dir });
336
+ // PRD 2891: never rm -rf unique uncommitted work — pin it as a commit first,
337
+ // and keep the checkout on disk when that pin cannot be made.
338
+ const snapshot = await snapshotUncommittedWork({ cwd, dir, key: key || path.basename(dir) });
339
+ if (snapshot && snapshot.error) {
340
+ console.warn(`[gitWorktree] keeping ${dir}: uncommitted work could not be snapshotted (${snapshot.error})`);
341
+ return { removed: false, snapshot };
342
+ }
336
343
  try {
337
344
  await execGit(['worktree', 'remove', '--force', dir], { cwd, timeout: 15_000 });
338
345
  } catch {
@@ -357,6 +364,7 @@ async function removeWorktreeDir(cwd, dir) {
357
364
  // Not empty (a sibling checkout survives), doesn't exist, or a race —
358
365
  // all fine to ignore.
359
366
  }
367
+ return { removed: true, snapshot };
360
368
  }
361
369
 
362
370
  /**
@@ -410,9 +418,35 @@ async function mainTreeFromWorktreeGitFile(dir) {
410
418
  * the checkout itself, in case git can still resolve it) when that lookup
411
419
  * fails. Never throws.
412
420
  */
413
- async function teardownOrphanedCheckout(dir) {
421
+ async function teardownOrphanedCheckout(dir, { key } = {}) {
414
422
  const mainTree = await mainTreeFromWorktreeGitFile(dir);
423
+ const snapKey = key || path.basename(dir);
415
424
  await pinStrandedHead({ cwd: mainTree || dir, dir });
425
+ if (!mainTree) {
426
+ // No main tree to snapshot against: a dirty (or unreadable) checkout is
427
+ // kept rather than deleted (PRD 2891).
428
+ let dirty = false;
429
+ try {
430
+ const st = await execGit(['status', '--porcelain'], { cwd: dir, timeout: 15_000 });
431
+ dirty = st.trim().length > 0;
432
+ } catch {
433
+ dirty = true;
434
+ }
435
+ if (dirty) {
436
+ const reason = 'main tree unresolved and checkout is dirty or unreadable';
437
+ console.warn(`[gitWorktree] keeping ${dir}: ${reason}`);
438
+ return { removed: false, snapshot: null, mainTree: null, reason };
439
+ }
440
+ }
441
+ let snapshot = null;
442
+ if (mainTree) {
443
+ snapshot = await snapshotUncommittedWork({ cwd: mainTree, dir, key: snapKey });
444
+ if (snapshot && snapshot.error) {
445
+ const reason = `snapshot failed: ${snapshot.error}`;
446
+ console.warn(`[gitWorktree] keeping ${dir}: ${reason}`);
447
+ return { removed: false, snapshot, mainTree, reason };
448
+ }
449
+ }
416
450
  if (mainTree) {
417
451
  try {
418
452
  await execGit(['worktree', 'remove', '--force', dir], { cwd: mainTree, timeout: 15_000 });
@@ -422,10 +456,11 @@ async function teardownOrphanedCheckout(dir) {
422
456
  }
423
457
  try { await fsp.rm(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
424
458
  try { await execGit(['worktree', 'prune'], { cwd: mainTree, timeout: 10_000 }); } catch { /* best-effort */ }
425
- return;
459
+ return { removed: true, snapshot, mainTree };
426
460
  }
427
461
  try { await execGit(['worktree', 'prune'], { cwd: dir, timeout: 10_000 }); } catch { /* best-effort */ }
428
462
  try { await fsp.rm(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
463
+ return { removed: true, snapshot: null, mainTree: null };
429
464
  }
430
465
 
431
466
  /**
@@ -464,7 +499,9 @@ async function teardownOrphanedCheckout(dir) {
464
499
  * kind's own root before any read or delete, so a maliciously-shaped on-disk
465
500
  * name can never walk this sweep outside its own tmpdir root.
466
501
  *
467
- * Returns `{ checkoutsRemoved, emptyRootsRemoved }`. Never throws.
502
+ * Returns `{ checkoutsRemoved, emptyRootsRemoved, snapshots, kept }` —
503
+ * `checkoutsRemoved` counts only checkouts actually deleted; a checkout whose
504
+ * uncommitted work could not be snapshotted lands in `kept`. Never throws.
468
505
  */
469
506
  async function sweepStaleWorktreeCheckouts(kind, opts = {}) {
470
507
  const root = worktreeRootFor(kind);
@@ -472,7 +509,7 @@ async function sweepStaleWorktreeCheckouts(kind, opts = {}) {
472
509
  ? opts.staleAgeMs
473
510
  : getStaleSweepAgeMs(kind);
474
511
  const holders = opts.holders instanceof Set ? opts.holders : listCwdHolders();
475
- const result = { checkoutsRemoved: 0, emptyRootsRemoved: 0 };
512
+ const result = { checkoutsRemoved: 0, emptyRootsRemoved: 0, snapshots: [], kept: [] };
476
513
 
477
514
  let hashEntries;
478
515
  try {
@@ -512,8 +549,17 @@ async function sweepStaleWorktreeCheckouts(kind, opts = {}) {
512
549
  }
513
550
 
514
551
  try {
515
- await teardownOrphanedCheckout(checkoutDir);
516
- result.checkoutsRemoved++;
552
+ const key = keyEntry.name;
553
+ const td = await teardownOrphanedCheckout(checkoutDir, { key });
554
+ const tdCwd = (td && td.mainTree) || null;
555
+ if (td && td.removed) {
556
+ result.checkoutsRemoved++;
557
+ if (td.snapshot && td.snapshot.sha) {
558
+ result.snapshots.push({ cwd: tdCwd, key, sha: td.snapshot.sha, ref: td.snapshot.ref, paths: td.snapshot.paths });
559
+ }
560
+ } else if (td) {
561
+ result.kept.push({ cwd: tdCwd, key, reason: td.reason || 'kept' });
562
+ }
517
563
  } catch {
518
564
  /* best-effort */
519
565
  }
@@ -763,6 +809,43 @@ function withKindLock(kind, fn) {
763
809
  return result;
764
810
  }
765
811
 
812
+ // Per-checkout promise-chain tails for `withCheckoutLock`, keyed by the
813
+ // checkout's real path. An entry exists only while its chain has work.
814
+ const checkoutLocks = new Map();
815
+
816
+ /** @param {string} cwd */
817
+ function checkoutLockKey(cwd) {
818
+ try { return fs.realpathSync(cwd); } catch { return path.resolve(cwd); }
819
+ }
820
+
821
+ /**
822
+ * Serializes `fn` per main checkout, so the callers that land into one
823
+ * checkout (scheduler finalize, mechanical recovery, the branch sweep, the
824
+ * reaper landing adopted PASS runs) never run `git merge`/`git checkout`
825
+ * there at once — two concurrent ones clash on `.git/index.lock`, which
826
+ * reports as `failureKind: 'other'` and parks a job whose work was fine.
827
+ * Different checkouts run concurrently. A rejection from `fn` is returned to
828
+ * its own caller only; the chain swallows it so later callers still run.
829
+ * Process-local: the app is single-instance, so no cross-process lock.
830
+ * @template T
831
+ * @param {string} cwd
832
+ * @param {() => T | Promise<T>} fn
833
+ * @returns {Promise<T>}
834
+ */
835
+ async function withCheckoutLock(cwd, fn) {
836
+ const key = checkoutLockKey(cwd);
837
+ const previous = checkoutLocks.get(key) || Promise.resolve();
838
+ const result = previous.then(() => fn());
839
+ const tail = result.then(() => {}, () => {});
840
+ checkoutLocks.set(key, tail);
841
+ try {
842
+ return await result;
843
+ } finally {
844
+ // Only the call that is still the chain's tail drains it.
845
+ if (checkoutLocks.get(key) === tail) checkoutLocks.delete(key);
846
+ }
847
+ }
848
+
766
849
  /**
767
850
  * Decides whether a new worktree of `kind` may be created right now, and if
768
851
  * so reserves the slot — the single choke point `createWorktree` calls
@@ -854,6 +937,12 @@ async function isRegisteredWorktreeOnBranch(cwd, dir, branch) {
854
937
  * human's dirty diff is relative to their OWN tree, not `fromRef`'s, so
855
938
  * applying it here would silently misplace or conflict with content that has
856
939
  * nothing to do with it.
940
+ *
941
+ * `forkSha` on the success result is the full SHA the checkout was forked
942
+ * from (the resolved `fromRef`, else `HEAD^{commit}`) — the SHA, never the
943
+ * name 'HEAD', is what `git worktree add` receives. Integration needs it to
944
+ * replay only the job's own commits after a base rewrite. Omitted on an
945
+ * unborn HEAD and on the Epic reuse result.
857
946
  */
858
947
  async function createWorktree({ kind, cwd, key, fromRef }) {
859
948
  configFor(kind); // throws on an unknown kind before anything else runs
@@ -877,6 +966,11 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
877
966
  if (typeof fromRef === 'string' && fromRef) {
878
967
  resolvedFromRefSha = await tryResolveCommit(cwd, `${fromRef}^{commit}`);
879
968
  }
969
+ // forkSha: the exact commit this checkout forks from, returned so
970
+ // integration can bound a replay at the fork point after the base branch is
971
+ // rewritten (rebase/reset) mid-run. Null only on an unborn HEAD, where the
972
+ // start point stays the name 'HEAD' and the result omits forkSha.
973
+ const forkSha = resolvedFromRefSha || await tryResolveCommit(cwd, 'HEAD^{commit}');
880
974
 
881
975
  // Epic mint is idempotent: a live Epic checkout (registered on its own
882
976
  // branch) is returned untouched — the leftover teardown below would delete
@@ -898,7 +992,7 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
898
992
 
899
993
  const dir = worktreeDirFor(kind, cwd, key);
900
994
  const branch = branchNameFor(kind, key);
901
- const worktreeSource = resolvedFromRefSha || 'HEAD';
995
+ const worktreeSource = forkSha || 'HEAD';
902
996
  try {
903
997
  await fsp.mkdir(path.dirname(dir), { recursive: true });
904
998
  // Defensive: a same-key leftover from a prior crashed run (same slug/id
@@ -942,6 +1036,7 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
942
1036
  registeredCheckouts.set(dir, { kind, branch });
943
1037
  const result = { ok: true, dir, branch, baseCwd: cwd, carriedPaths, baseBranch, setup };
944
1038
  if (resolvedFromRefSha) result.forkedFrom = fromRef;
1039
+ if (forkSha) result.forkSha = forkSha;
945
1040
  return result;
946
1041
  }
947
1042
 
@@ -1374,15 +1469,25 @@ async function getCurrentBranch(cwd) {
1374
1469
  * Never throws — any read failure (including no `carriedPaths`) is reported
1375
1470
  * as `false`, the safer default that falls through to a real integration
1376
1471
  * attempt rather than silently dropping a commit.
1472
+ *
1473
+ * `scopeBase` (optional): when a non-empty string, the diff's lower bound —
1474
+ * the job's fork when the base was rewritten under it, since the merge-base
1475
+ * with the rewritten HEAD would count the inherited pre-rewrite commits as
1476
+ * the branch's own changes and the shortcut would never fire. Omitted =
1477
+ * `merge-base HEAD branch`.
1377
1478
  */
1378
- async function isCarriedWipOnly({ cwd, branch, carriedPaths }) {
1479
+ async function isCarriedWipOnly({ cwd, branch, carriedPaths, scopeBase }) {
1379
1480
  if (!Array.isArray(carriedPaths) || !carriedPaths.length) return false;
1380
1481
  try {
1381
1482
  let mergeBase = '';
1382
- try {
1383
- mergeBase = (await execGit(['merge-base', 'HEAD', branch], { cwd, timeout: 10_000 })).trim();
1384
- } catch {
1385
- mergeBase = '';
1483
+ if (typeof scopeBase === 'string' && scopeBase) {
1484
+ mergeBase = scopeBase;
1485
+ } else {
1486
+ try {
1487
+ mergeBase = (await execGit(['merge-base', 'HEAD', branch], { cwd, timeout: 10_000 })).trim();
1488
+ } catch {
1489
+ mergeBase = '';
1490
+ }
1386
1491
  }
1387
1492
  const changedOut = await execGit(['diff', `${mergeBase || 'HEAD'}..${branch}`, '--name-only'], { cwd, timeout: 10_000 });
1388
1493
  const changed = changedOut.split('\n').map((l) => l.trim()).filter(Boolean);
@@ -1453,8 +1558,13 @@ async function isCarriedWipOnly({ cwd, branch, carriedPaths }) {
1453
1558
  * in-checkout path's `isCarriedWipOnly`, because `cwd` is on some other
1454
1559
  * branch and has no working tree this path could trust to content-verify
1455
1560
  * against.
1561
+ *
1562
+ * SM_LINEAR_LANDING_DISABLE=1 is not honoured on a rewritten base (forkSha no
1563
+ * longer an ancestor of the target): a merge commit would merge the
1564
+ * pre-rewrite history back in, so the fork-bounded linear replay always runs
1565
+ * and a failed replay parks instead of falling back to a merge.
1456
1566
  */
1457
- async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranch, allowRefLanding = false }) {
1567
+ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranch, allowRefLanding = false, forkSha }) {
1458
1568
  if (!cwd || !branch) return { ok: false, reason: 'missing cwd/branch' };
1459
1569
 
1460
1570
  const expectedBranch = (typeof baseBranch === 'string' && baseBranch && !isOwnManagedBranch(baseBranch))
@@ -1511,6 +1621,18 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1511
1621
  if (refMergeBase && refMergeBase === refBranchHead) {
1512
1622
  return { ok: true, integrated: false, reason: 'branch has no new commits' };
1513
1623
  }
1624
+ const refRewrite = await resolveRewrittenFork(
1625
+ cwd, forkSha, refBranchHead, await tryResolveCommit(cwd, `refs/heads/${expectedBranch}^{commit}`),
1626
+ );
1627
+ if (refRewrite.fork && refRewrite.fork === refBranchHead) {
1628
+ return { ok: true, integrated: false, reason: 'branch has no new commits' };
1629
+ }
1630
+ const refScopeBase = refRewrite.baseRewritten ? refRewrite.fork : (refMergeBase || expectedBranch);
1631
+ const refRuntimeAdds = await findRuntimeStateAdds({ cwd, branch, mergeBase: refScopeBase });
1632
+ if (refRuntimeAdds.length) {
1633
+ const refusal = await runtimeStateRefusal(cwd, refRuntimeAdds);
1634
+ return { ...refusal, baseHeadSha: await tryResolveCommit(cwd, `${expectedBranch}^{commit}`) };
1635
+ }
1514
1636
  // Carried-WIP shortcut, path membership only: `cwd` is on `actualBranch`,
1515
1637
  // not `expectedBranch`, so there is no trustworthy working tree here to
1516
1638
  // content-verify against (isCarriedWipOnly's approach, used by the
@@ -1521,7 +1643,7 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1521
1643
  // paths still lands below, same as the in-checkout path.
1522
1644
  if (Array.isArray(carriedPaths) && carriedPaths.length) {
1523
1645
  try {
1524
- const changedOut = await execGit(['diff', `${refMergeBase || expectedBranch}..${branch}`, '--name-only'], { cwd, timeout: 10_000 });
1646
+ const changedOut = await execGit(['diff', `${refScopeBase}..${branch}`, '--name-only'], { cwd, timeout: 10_000 });
1525
1647
  const changed = changedOut.split('\n').map((l) => l.trim()).filter(Boolean);
1526
1648
  if (changed.length && changed.every((p) => carriedPaths.includes(p))) {
1527
1649
  return strayCheckoutFailure;
@@ -1532,11 +1654,14 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1532
1654
  }
1533
1655
  }
1534
1656
  const refResult = await integrateOntoRef({
1535
- cwd, targetRef: `refs/heads/${expectedBranch}`, branch, message: mergeMessage,
1657
+ cwd, targetRef: `refs/heads/${expectedBranch}`, branch, message: mergeMessage, forkSha,
1536
1658
  });
1537
1659
  if (refResult.ok) {
1538
- // Spread refResult first so a fast-forward keeps `fastForward: true`
1539
- // and a merge commit keeps `mergeCommit: true` — this used to
1660
+ // Spread refResult first so the landing's own shape passes through
1661
+ // untouched: a fast-forward keeps `fastForward: true`, the normal
1662
+ // diverged case keeps `linear: true` + `replayedCommits` (the branch
1663
+ // replayed onto the ref tip, no merge commit), and only the merge
1664
+ // fallback carries `mergeCommit: true` + `linearFallback`. This used to
1540
1665
  // hard-code `fastForward: false` on every success, misreporting a
1541
1666
  // plain fast-forward as a merge.
1542
1667
  return { ...refResult, viaRef: true, sha: refResult.sha || refBranchHead };
@@ -1544,6 +1669,9 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1544
1669
  if (refResult.failureKind === 'target_checked_out') {
1545
1670
  return strayCheckoutFailure;
1546
1671
  }
1672
+ if (refResult.baseRewritten) {
1673
+ return refResult;
1674
+ }
1547
1675
  if (refResult.failureKind === 'content_conflict') {
1548
1676
  return {
1549
1677
  ok: false,
@@ -1555,6 +1683,20 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1555
1683
  return strayCheckoutFailure;
1556
1684
  }
1557
1685
 
1686
+ // Everything below runs git merge/checkout in `cwd` itself, so it is
1687
+ // serialized per checkout (see withCheckoutLock). Called through
1688
+ // module.exports so tests can spy on the lock.
1689
+ return module.exports.withCheckoutLock(cwd, () => integrateBranchInCheckout({
1690
+ cwd, branch, carriedPaths, forkSha, mergeMessage,
1691
+ }));
1692
+ }
1693
+
1694
+ /**
1695
+ * The in-checkout half of `integrateBranch`: HEAD is already verified to be
1696
+ * on the expected base branch. Only ever called under `withCheckoutLock(cwd)`.
1697
+ * @param {{cwd: string, branch: string, carriedPaths?: string[], forkSha?: string, mergeMessage: string}} a
1698
+ */
1699
+ async function integrateBranchInCheckout({ cwd, branch, carriedPaths, forkSha, mergeMessage }) {
1558
1700
  let branchHead;
1559
1701
  try {
1560
1702
  branchHead = (await execGit(['rev-parse', branch], { cwd, timeout: 10_000 })).trim();
@@ -1570,6 +1712,14 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1570
1712
  if (mergeBase && mergeBase === branchHead) {
1571
1713
  return { ok: true, integrated: false, reason: 'branch has no new commits' };
1572
1714
  }
1715
+ // Base rewritten under the job (rebase/reset): the fork commit is no longer
1716
+ // in HEAD's history, so only commits after it are the job's own — they
1717
+ // bound the replay and every "what did this branch change" diff below.
1718
+ const { fork, baseRewritten } = await resolveRewrittenFork(cwd, forkSha, branchHead, await readHeadSha(cwd));
1719
+ if (fork && fork === branchHead) {
1720
+ return { ok: true, integrated: false, reason: 'branch has no new commits' };
1721
+ }
1722
+ const scopeBase = baseRewritten && fork ? fork : mergeBase;
1573
1723
 
1574
1724
  // Path membership alone is NOT enough: a job that legitimately edits the
1575
1725
  // SAME file the base tree had carried-in WIP on (e.g. this repo's own
@@ -1580,11 +1730,14 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1580
1730
  // than the ordinary merge-conflict path (branch kept, flagged for manual
1581
1731
  // recovery) this shortcut is supposed to be a safe subset of. See
1582
1732
  // `isCarriedWipOnly` above for the content-verify logic.
1583
- if (await isCarriedWipOnly({ cwd, branch, carriedPaths })) {
1733
+ if (await isCarriedWipOnly({ cwd, branch, carriedPaths, scopeBase: baseRewritten && fork ? fork : undefined })) {
1584
1734
  return { ok: true, integrated: false, reason: 'carried-wip-only' };
1585
1735
  }
1586
1736
 
1587
- const clobber = await findIgnoredLivePaths({ cwd, branch, mergeBase });
1737
+ const runtimeAdds = await findRuntimeStateAdds({ cwd, branch, mergeBase: scopeBase });
1738
+ if (runtimeAdds.length) return runtimeStateRefusal(cwd, runtimeAdds);
1739
+
1740
+ const clobber = await findIgnoredLivePaths({ cwd, branch, mergeBase: scopeBase });
1588
1741
  if (clobber.length) {
1589
1742
  return {
1590
1743
  ok: false,
@@ -1594,27 +1747,35 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1594
1747
  baseHeadSha: await readHeadSha(cwd),
1595
1748
  };
1596
1749
  }
1597
- try {
1598
- await execGit(['merge', '--ff-only', '--no-overwrite-ignore', branch], { cwd, timeout: 30_000 });
1599
- // The branch tip we fast-forwarded to, read from the branch ref (not HEAD,
1600
- // which a concurrent writer may already have moved).
1601
- return { ok: true, integrated: true, fastForward: true, sha: await tryResolveCommit(cwd, `${branch}^{commit}`) };
1602
- } catch {
1603
- // Main tree advanced since the worktree branched (a sibling job/Epic
1604
- // merged first) — replay the branch linearly onto HEAD; a merge commit is
1605
- // only the documented fallback.
1750
+ // A rewritten base (main reset under the job) can still be an ancestor of
1751
+ // the branch; fast-forwarding would land the pre-rewrite commits the job
1752
+ // inherited, so a rewritten base always takes the fork-bounded replay below.
1753
+ if (!baseRewritten) {
1754
+ try {
1755
+ await execGit(['merge', '--ff-only', '--no-overwrite-ignore', branch], { cwd, timeout: 30_000 });
1756
+ // The branch tip we fast-forwarded to, read from the branch ref (not HEAD,
1757
+ // which a concurrent writer may already have moved).
1758
+ return { ok: true, integrated: true, fastForward: true, sha: await tryResolveCommit(cwd, `${branch}^{commit}`) };
1759
+ } catch {
1760
+ // Main tree advanced since the worktree branched (a sibling job/Epic
1761
+ // merged first) — replay the branch linearly onto HEAD; a merge commit is
1762
+ // only the documented fallback.
1763
+ }
1606
1764
  }
1607
1765
  let linearFallback = '';
1608
- if (process.env.SM_LINEAR_LANDING_DISABLE === '1') {
1766
+ if (process.env.SM_LINEAR_LANDING_DISABLE === '1' && !baseRewritten) {
1609
1767
  linearFallback = 'disabled';
1610
1768
  } else {
1611
1769
  const MAX_LINEAR_ATTEMPTS = 3;
1612
1770
  let landed = null;
1613
1771
  for (let attempt = 0; attempt < MAX_LINEAR_ATTEMPTS; attempt++) {
1614
1772
  const headSha = await readHeadSha(cwd);
1615
- const r = await replayBranchOnto({ cwd, ontoSha: headSha, branch: branchHead });
1773
+ const r = await replayBranchOnto({ cwd, ontoSha: headSha, branch: branchHead, sinceSha: fork || undefined });
1616
1774
  if (!r.ok) {
1617
- if (r.failureKind === 'git_too_old' || r.failureKind === 'content_conflict') {
1775
+ if (baseRewritten && REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
1776
+ return rewrittenBaseReplayFailure(r, headSha, { cwd, fork, tip: branchHead });
1777
+ }
1778
+ if (REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
1618
1779
  linearFallback = r.failureKind;
1619
1780
  break;
1620
1781
  }
@@ -1668,6 +1829,15 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1668
1829
  }
1669
1830
  if (landed) return landed;
1670
1831
  if (!linearFallback) linearFallback = 'ref_race';
1832
+ if (baseRewritten) {
1833
+ return {
1834
+ ok: false,
1835
+ failureKind: 'ref_race',
1836
+ baseRewritten: true,
1837
+ baseHeadSha: await readHeadSha(cwd),
1838
+ reason: 'linear landing onto the rewritten base kept racing a moving HEAD; refusing a merge-commit fallback',
1839
+ };
1840
+ }
1671
1841
  }
1672
1842
  console.warn(`[gitWorktree] linear landing of ${branch} fell back to a merge commit (${linearFallback})`);
1673
1843
  const fb = { linearFallback };
@@ -1799,6 +1969,44 @@ async function findIgnoredLivePaths({ cwd, branch, mergeBase }) {
1799
1969
  return live;
1800
1970
  }
1801
1971
 
1972
+ /**
1973
+ * Paths the branch ADDED since the merge base under an app runtime folder
1974
+ * (`session-manager-operations/<ns>/`, ns from RUNTIME_NAMESPACES — state
1975
+ * that must never be committed) AND that are git-ignored in `cwd`, i.e. a
1976
+ * force-added runtime file. Modified/deleted paths and deliberately
1977
+ * un-ignored ones are never returned. A diff error returns [].
1978
+ * @param {{cwd: string, branch: string, mergeBase: string}} a
1979
+ * @returns {Promise<string[]>}
1980
+ */
1981
+ async function findRuntimeStateAdds({ cwd, branch, mergeBase }) {
1982
+ let added;
1983
+ try {
1984
+ const pathspecs = RUNTIME_NAMESPACES.map((ns) => `:(top)${OPS_ROOT_DIR}/${ns}/`);
1985
+ const out = await execGit(
1986
+ ['diff', '--name-only', '-z', '--diff-filter=A', `${mergeBase || 'HEAD'}..${branch}`, '--', ...pathspecs],
1987
+ { cwd, timeout: 15_000 },
1988
+ );
1989
+ added = out.split('\0').filter(Boolean);
1990
+ } catch {
1991
+ return [];
1992
+ }
1993
+ return filterIgnoredPaths({ cwd, paths: added });
1994
+ }
1995
+
1996
+ /**
1997
+ * Integration refusal for a branch that adds app runtime state. Base branch
1998
+ * is untouched and the job branch is kept for recovery.
1999
+ */
2000
+ async function runtimeStateRefusal(cwd, paths) {
2001
+ return {
2002
+ ok: false,
2003
+ reason: `refusing to integrate: branch adds app runtime state (never committed): ${paths.join(', ')}`,
2004
+ failureKind: 'other',
2005
+ runtimeStatePaths: paths,
2006
+ baseHeadSha: await readHeadSha(cwd),
2007
+ };
2008
+ }
2009
+
1802
2010
  /**
1803
2011
  * Tear down one worktree checkout after it has been integrated (or failed to
1804
2012
  * integrate). Always removes the linked-worktree checkout (freeing its
@@ -1808,8 +2016,16 @@ async function findIgnoredLivePaths({ cwd, branch, mergeBase }) {
1808
2016
  */
1809
2017
  async function cleanupWorktree({ kind, cwd, dir, branch, keepBranch }) {
1810
2018
  configFor(kind); // throws on an unknown kind before anything else runs
1811
- if (dir) await removeWorktreeDir(cwd, dir);
1812
- if (branch && !keepBranch) {
2019
+ let snapshot = null;
2020
+ let removed = false;
2021
+ if (dir) {
2022
+ const res = await removeWorktreeDir(cwd, dir, { key: keyFromBranch(kind, branch) || path.basename(dir) });
2023
+ snapshot = res.snapshot;
2024
+ removed = res.removed;
2025
+ }
2026
+ // A kept checkout still has the branch checked out (git would refuse the
2027
+ // delete anyway) — leave both for recovery.
2028
+ if (branch && !keepBranch && (!dir || removed)) {
1813
2029
  try { await execGit(['branch', '-D', branch], { cwd, timeout: 10_000 }); } catch { /* already gone */ }
1814
2030
  }
1815
2031
  try { await execGit(['worktree', 'prune'], { cwd, timeout: 10_000 }); } catch { /* best effort */ }
@@ -1821,6 +2037,7 @@ async function cleanupWorktree({ kind, cwd, dir, branch, keepBranch }) {
1821
2037
  const alreadyExpired = dir ? expiredCheckoutDirs.delete(dir) : false;
1822
2038
  if (dir) registeredCheckouts.delete(dir);
1823
2039
  if (dir && !alreadyExpired) activeWorktreeCount[kind] = Math.max(0, activeWorktreeCount[kind] - 1);
2040
+ return { snapshot, removed };
1824
2041
  }
1825
2042
 
1826
2043
  /**
@@ -1944,19 +2161,201 @@ async function salvageDirtyDelta({ cwd, paths, outFile }) {
1944
2161
  }
1945
2162
 
1946
2163
  /**
1947
- * True when every commit on `branch` is already an ancestor of (or equal to)
1948
- * `cwd`'s current HEAD — i.e. the branch holds no work that isn't already
1949
- * landed. Used by the stranded-branch sweep (branchSweep.cjs) to tell a
1950
- * genuinely stranded `sm-job/*` branch from one that's already a no-op.
2164
+ * True when `branch` holds no work that isn't already landed on `cwd`'s
2165
+ * current HEAD: its tip is an ancestor of (or equal to) HEAD, or, failing
2166
+ * that, `isBranchContentLanded({ cwd, base: 'HEAD', branch })` proves its
2167
+ * content is there. Linear landing (PRDs 2743, 2825) replays a branch, so a
2168
+ * landed branch's own commits never become ancestors of HEAD. Ancestry alone
2169
+ * made the stranded-branch sweep (branchSweep.cjs) re-integrate such a branch
2170
+ * once per process lifetime, and `reclaimTerminalJobOrphans` keep its checkout
2171
+ * (validator finding I-2). Used by both to tell a genuinely stranded
2172
+ * `sm-job/*` branch from one that's already a no-op.
2173
+ * `forkSha` (the commit the branch forked from, e.g. from resolveForkSha)
2174
+ * bounds the content check to the branch's own commits, so after main is
2175
+ * rebased or reset the pre-rewrite commits the branch inherited don't keep
2176
+ * a replay-landed branch reading as unmerged; null/unusable = unbounded.
1951
2177
  * Never throws; a branch that doesn't exist, or any other git failure, is
1952
2178
  * conservatively reported as NOT merged so a caller never treats an
1953
2179
  * unreadable branch as safe to skip.
1954
2180
  */
1955
- async function isBranchMergedIntoHead(cwd, branch) {
2181
+ async function isBranchMergedIntoHead(cwd, branch, forkSha = null) {
2182
+ let branchHead;
2183
+ try {
2184
+ branchHead = (await execGit(['rev-parse', '--verify', branch], { cwd, timeout: 10_000 })).trim();
2185
+ } catch {
2186
+ return false;
2187
+ }
1956
2188
  try {
1957
- const branchHead = (await execGit(['rev-parse', '--verify', branch], { cwd, timeout: 10_000 })).trim();
1958
2189
  const mergeBase = (await execGit(['merge-base', 'HEAD', branch], { cwd, timeout: 10_000 })).trim();
1959
- return mergeBase !== '' && mergeBase === branchHead;
2190
+ if (mergeBase !== '' && mergeBase === branchHead) return true;
2191
+ } catch {
2192
+ // No merge base, or git failed: ancestry proves nothing, so the content check decides.
2193
+ }
2194
+ return (await isBranchContentLanded({ cwd, base: 'HEAD', branch, sinceSha: forkSha || undefined })) === true;
2195
+ }
2196
+
2197
+ /**
2198
+ * True when `branch`'s CONTENT is already in `base`, by any of three proofs,
2199
+ * cheapest first. Linear landing (PRDs 2743, 2825) replays a branch, so its
2200
+ * original commits never become ancestors of the base, and an ancestry-only
2201
+ * check reads a landed branch as unmerged (validator finding I-2).
2202
+ * 1. Ancestry: the branch tip is an ancestor of (or equal to) base.
2203
+ * 2. Patch-ids: `rev-list --right-only --cherry-pick --no-merges --count
2204
+ * <base>...<branch>` prints 0. Every non-merge branch commit has a
2205
+ * patch-equivalent commit on base, as a clean replay leaves. This proof
2206
+ * never sees a merge commit's own resolution.
2207
+ * 3. Merged tree: `merge-tree --write-tree <base> <branch>` exits 0 with
2208
+ * base's own tree. Merging the branch would change nothing. This catches
2209
+ * a replay whose diff context shifted, which changes the patch-id but
2210
+ * not the content.
2211
+ * Returns null when `branch` or `base` does not resolve to a commit. Returns
2212
+ * false otherwise, including a merge-tree conflict, a git too old for
2213
+ * `--write-tree` (< 2.38), or any other git failure, so an unreadable answer
2214
+ * never reads as landed. Never throws. Both names resolve to SHAs first and
2215
+ * only SHAs reach git. A name starting with '-' resolves only via
2216
+ * `refs/heads/`, as in replayBranchOnto.
2217
+ * `sinceSha` (the commit the branch forked from) bounds proofs 2 and 3 to the
2218
+ * branch's own commits, so a base rewritten while the job ran does not count
2219
+ * the pre-rewrite commits the branch inherited as unlanded; an unusable
2220
+ * `sinceSha` (empty, unresolvable, not an ancestor of the tip) is ignored.
2221
+ *
2222
+ * @param {{ cwd?: string, base?: string, branch?: string, sinceSha?: string }} [opts]
2223
+ * @returns {Promise<boolean|null>}
2224
+ */
2225
+ /**
2226
+ * Resolves `sinceSha` (the commit a job branch forked from) to a SHA, or null
2227
+ * when it is empty, unresolvable, or not an ancestor of (or equal to) `tipSha`
2228
+ * — a null bound leaves the caller's range unbounded, exactly as before.
2229
+ *
2230
+ * @param {string} cwd
2231
+ * @param {unknown} sinceSha
2232
+ * @param {string} tipSha
2233
+ * @returns {Promise<string|null>}
2234
+ */
2235
+ async function resolveForkBound(cwd, sinceSha, tipSha) {
2236
+ if (typeof sinceSha !== 'string' || !sinceSha || sinceSha.startsWith('-')) return null;
2237
+ const since = await tryResolveCommit(cwd, `${sinceSha}^{commit}`);
2238
+ if (!since) return null;
2239
+ try {
2240
+ await execGit(['merge-base', '--is-ancestor', since, tipSha], { cwd, timeout: 10_000 });
2241
+ return since;
2242
+ } catch {
2243
+ return null;
2244
+ }
2245
+ }
2246
+
2247
+ /**
2248
+ * Resolves the job's fork commit against the branch tip and the landing
2249
+ * target: `fork` is `forkSha` resolved (null unless it is an ancestor of, or
2250
+ * equal to, `branchSha`), and `baseRewritten` is true when that fork is NOT
2251
+ * an ancestor of `targetSha` — the base was rebased/reset under the job, so
2252
+ * only commits after the fork are the job's own. Never throws.
2253
+ *
2254
+ * @param {string} cwd
2255
+ * @param {unknown} forkSha
2256
+ * @param {string} branchSha
2257
+ * @param {string|null} targetSha
2258
+ * @returns {Promise<{fork: string|null, baseRewritten: boolean}>}
2259
+ */
2260
+ async function resolveRewrittenFork(cwd, forkSha, branchSha, targetSha) {
2261
+ const fork = await resolveForkBound(cwd, forkSha, branchSha);
2262
+ if (!fork || !targetSha) return { fork, baseRewritten: false };
2263
+ try {
2264
+ await execGit(['merge-base', '--is-ancestor', fork, targetSha], { cwd, timeout: 10_000 });
2265
+ return { fork, baseRewritten: false };
2266
+ } catch (e) {
2267
+ return { fork, baseRewritten: !!(e && e.code === 1) };
2268
+ }
2269
+ }
2270
+
2271
+ /**
2272
+ * Terminal result for a replay that failed while the base was rewritten: the
2273
+ * two-parent merge fallback would merge the pre-rewrite history back in, so
2274
+ * nothing lands. A conflict names every conflicted path; any other failure
2275
+ * (git_too_old, branch_has_merges) names the job's own paths
2276
+ * (`git diff --name-only <fork> <tip>`) in `conflictedPaths` + `reason`, so the
2277
+ * park still says what needs a manual landing.
2278
+ *
2279
+ * @param {{failureKind?: string, reason?: string, conflictedPaths?: string[]}} r
2280
+ * @param {string|null} baseHeadSha
2281
+ * @param {{cwd?: string, fork?: string|null, tip?: string|null}} [scope]
2282
+ */
2283
+ async function rewrittenBaseReplayFailure(r, baseHeadSha, { cwd, fork, tip } = {}) {
2284
+ if (r.failureKind === 'content_conflict') {
2285
+ const conflictedPaths = r.conflictedPaths || [];
2286
+ return {
2287
+ ok: false,
2288
+ failureKind: 'content_conflict',
2289
+ conflictedPaths,
2290
+ baseRewritten: true,
2291
+ baseHeadSha,
2292
+ reason: `replay of the job's own commits onto the rewritten base conflicts on: ${conflictedPaths.join(', ')}`,
2293
+ };
2294
+ }
2295
+ let conflictedPaths = [];
2296
+ if (cwd && fork && tip) {
2297
+ try {
2298
+ const out = await execGit(['diff', '--name-only', fork, tip], { cwd, timeout: 10_000 });
2299
+ conflictedPaths = out.split('\n').map((l) => l.trim()).filter(Boolean);
2300
+ } catch {
2301
+ conflictedPaths = [];
2302
+ }
2303
+ }
2304
+ const named = conflictedPaths.length ? ` (job's own paths: ${conflictedPaths.join(', ')})` : '';
2305
+ return {
2306
+ ok: false,
2307
+ failureKind: 'other',
2308
+ conflictedPaths,
2309
+ baseRewritten: true,
2310
+ baseHeadSha,
2311
+ reason: `replay of the job's own commits onto the rewritten base failed (${r.failureKind}); refusing a merge-commit fallback${named}: ${r.reason}`,
2312
+ };
2313
+ }
2314
+
2315
+ async function isBranchContentLanded({ cwd, base = 'HEAD', branch, sinceSha } = {}) {
2316
+ try {
2317
+ if (typeof cwd !== 'string' || !cwd) return null;
2318
+ const resolveName = async (name) => {
2319
+ if (typeof name !== 'string' || !name) return null;
2320
+ return (name.startsWith('-') ? null : await tryResolveCommit(cwd, `${name}^{commit}`))
2321
+ || tryResolveCommit(cwd, `refs/heads/${name}^{commit}`);
2322
+ };
2323
+ const baseSha = await resolveName(base);
2324
+ const tipSha = await resolveName(branch);
2325
+ if (!baseSha || !tipSha) return null;
2326
+
2327
+ try {
2328
+ await execGit(['merge-base', '--is-ancestor', tipSha, baseSha], { cwd, timeout: 10_000 });
2329
+ return true;
2330
+ } catch {
2331
+ // Exit 1 = not an ancestor. On any other failure, try the content proofs.
2332
+ }
2333
+
2334
+ const since = await resolveForkBound(cwd, sinceSha, tipSha);
2335
+ if (since && since === tipSha) return true;
2336
+
2337
+ try {
2338
+ const out = await execGit(
2339
+ ['rev-list', '--right-only', '--cherry-pick', '--no-merges', '--count', `${baseSha}...${tipSha}`, ...(since ? [`^${since}`] : [])],
2340
+ { cwd, timeout: 30_000 },
2341
+ );
2342
+ if (Number.parseInt(out.trim(), 10) === 0) return true;
2343
+ } catch {
2344
+ // Fall through to the merged-tree proof.
2345
+ }
2346
+
2347
+ try {
2348
+ const out = await execGit(
2349
+ ['merge-tree', '--write-tree', '--no-messages', ...(since ? [`--merge-base=${since}`] : []), baseSha, tipSha],
2350
+ { cwd, timeout: 30_000 },
2351
+ );
2352
+ const mergedTree = (out.split('\n')[0] || '').trim();
2353
+ const baseTree = (await execGit(['rev-parse', '--verify', `${baseSha}^{tree}`], { cwd, timeout: 10_000 })).trim();
2354
+ return mergedTree !== '' && mergedTree === baseTree;
2355
+ } catch {
2356
+ // Exit 1 = conflict, 129 = git < 2.38. Neither proves the content landed.
2357
+ return false;
2358
+ }
1960
2359
  } catch {
1961
2360
  return false;
1962
2361
  }
@@ -1988,10 +2387,12 @@ function keyFromBranch(kind, branch) {
1988
2387
  *
1989
2388
  * Never assumes it's safe to delete — proves it, two ways, for each
1990
2389
  * candidate:
1991
- * 1. `isBranchMergedIntoHead`: the branch holds ZERO commits that aren't
1992
- * already on `cwd`'s HEAD (equivalently, zero commits ahead of main) —
1993
- * so integrating it again could add nothing, and removing it loses no
1994
- * committed work.
2390
+ * 1. `isBranchMergedIntoHead`: the branch holds no work that isn't already
2391
+ * on `cwd`'s HEAD (zero commits ahead of main, or its commits landed
2392
+ * there as a linear replay) — so integrating it again could add
2393
+ * nothing, and removing it loses no committed work
2394
+ * (`deleteBranchKeepingUniqueCommits` still pins a tip no other ref
2395
+ * holds).
1995
2396
  * 2. Every path still dirty in the checkout itself (`git status
1996
2397
  * --porcelain` run with cwd = the checkout dir) lives under
1997
2398
  * `session-manager-operations/` — i.e. it's carried-over ops-folder
@@ -2044,7 +2445,10 @@ async function reclaimTerminalJobOrphans({ cwd, terminalSlugs, isLive }) {
2044
2445
  if (live) continue;
2045
2446
  }
2046
2447
 
2047
- const merged = await isBranchMergedIntoHead(cwd, entry.branch);
2448
+ // Bound the merged check at the branch's fork (reflog fallback — no row
2449
+ // here) so a branch landed by replay onto a rewritten base reads merged.
2450
+ const forkSha = await resolveForkSha({ cwd, branch: entry.branch, recorded: null });
2451
+ const merged = await isBranchMergedIntoHead(cwd, entry.branch, forkSha);
2048
2452
  if (!merged) continue; // real un-landed work — never touch
2049
2453
 
2050
2454
  let statusOut = '';
@@ -2062,7 +2466,8 @@ async function reclaimTerminalJobOrphans({ cwd, terminalSlugs, isLive }) {
2062
2466
  );
2063
2467
  if (!opsOnly) continue; // real non-ops dirty content present — leave for a human
2064
2468
 
2065
- await removeWorktreeDir(cwd, entry.worktree);
2469
+ const res = await removeWorktreeDir(cwd, entry.worktree, { key: slug });
2470
+ if (!res.removed) continue; // snapshot failed — checkout (and branch) kept
2066
2471
  if (entry.branch) {
2067
2472
  await deleteBranchKeepingUniqueCommits({ cwd, branch: entry.branch, key: slug });
2068
2473
  }
@@ -2113,6 +2518,8 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
2113
2518
  const root = worktreeRootFor(kind);
2114
2519
  const list = Array.isArray(cwds) ? cwds.filter(Boolean) : [];
2115
2520
  let checkoutsRemoved = 0;
2521
+ const snapshots = [];
2522
+ const kept = [];
2116
2523
  for (const cwd of list) {
2117
2524
  if (!(await isGitRepo(cwd))) continue;
2118
2525
  let out = '';
@@ -2129,8 +2536,15 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
2129
2536
  // even when the checkout is detached or on a branch we do not own.
2130
2537
  const key = branchKey || path.basename(entry.worktree);
2131
2538
  if (isLive && key && (await isLive(key, entry))) continue;
2132
- await removeWorktreeDir(cwd, entry.worktree);
2539
+ const res = await removeWorktreeDir(cwd, entry.worktree, { key });
2540
+ if (!res.removed) {
2541
+ kept.push({ cwd, key, reason: `snapshot failed: ${(res.snapshot && res.snapshot.error) || 'unknown'}` });
2542
+ continue; // keep its branch too — the checkout still holds it
2543
+ }
2133
2544
  checkoutsRemoved++;
2545
+ if (res.snapshot && res.snapshot.sha) {
2546
+ snapshots.push({ cwd, key, sha: res.snapshot.sha, ref: res.snapshot.ref, paths: res.snapshot.paths });
2547
+ }
2134
2548
  // sm-land/* is the per-Epic integration branch, never a throwaway
2135
2549
  // worktree branch — even if something else checked it out onto a
2136
2550
  // worktree under this kind's root, this sweep must never delete it.
@@ -2142,7 +2556,8 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
2142
2556
  try { await execGit(['worktree', 'prune'], { cwd, timeout: 10_000 }); } catch { /* best effort */ }
2143
2557
  }
2144
2558
 
2145
- let sweep = { checkoutsRemoved: 0, emptyRootsRemoved: 0 };
2559
+ /** @type {{ checkoutsRemoved: number, emptyRootsRemoved: number, snapshots: any[], kept: any[] }} */
2560
+ let sweep = { checkoutsRemoved: 0, emptyRootsRemoved: 0, snapshots: [], kept: [] };
2146
2561
  try {
2147
2562
  sweep = await sweepStaleWorktreeCheckouts(kind, { staleAgeMs: opts.staleAgeMs, holders: opts.holders });
2148
2563
  } catch {
@@ -2151,10 +2566,13 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
2151
2566
  const totals = {
2152
2567
  checkoutsRemoved: checkoutsRemoved + sweep.checkoutsRemoved,
2153
2568
  emptyRootsRemoved: sweep.emptyRootsRemoved,
2569
+ snapshots: snapshots.concat(sweep.snapshots || []),
2570
+ kept: kept.concat(sweep.kept || []),
2154
2571
  };
2155
2572
  console.log(
2156
2573
  `[gitWorktree] boot sweep (kind:${kind}): reclaimed ${totals.checkoutsRemoved} checkout(s), ` +
2157
- `${totals.emptyRootsRemoved} empty root dir(s)`
2574
+ `${totals.emptyRootsRemoved} empty root dir(s), ` +
2575
+ `${totals.snapshots.length} uncommitted snapshot(s), ${totals.kept.length} kept`
2158
2576
  );
2159
2577
  return totals;
2160
2578
  }
@@ -2221,24 +2639,46 @@ async function runMergeTreeWriteTree({ cwd, oldSha, branchSha }) {
2221
2639
 
2222
2640
  const REPLAY_MAX_COMMITS = 200;
2223
2641
 
2642
+ /**
2643
+ * The `replayBranchOnto` failure kinds both landing paths answer with their
2644
+ * logged two-parent merge fallback (`linearFallback` = the kind); every other
2645
+ * replay failure lands nothing.
2646
+ */
2647
+ const REPLAY_MERGE_FALLBACK_KINDS = new Set(['git_too_old', 'content_conflict', 'branch_has_merges']);
2648
+
2224
2649
  /**
2225
2650
  * Checkout-free linear replay: rebuilds `branch`'s non-merge commits on top of
2226
2651
  * `ontoSha` purely in the object database (`git merge-tree --write-tree` +
2227
2652
  * `git commit-tree`). Touches no checkout, index, HEAD or ref — the caller
2228
- * decides what to do with the returned `tipSha`. It exists so scheduler-job and
2229
- * Epic landings can be linear: `integrateBranch` / `attemptIntegrateOntoRef`
2230
- * create "merge ..." commits, and Bilko's scripts/sync-local-main.sh refuses a
2231
- * local main carrying merge commits origin lacks.
2653
+ * decides what to do with the returned `tipSha`. It is the linear step of both
2654
+ * landing paths — `integrateBranch` in the checkout and `attemptIntegrateOntoRef`
2655
+ * onto a bare ref: fast-forward first, then this replay, and a two-parent
2656
+ * "merge ..." commit only as their logged fallback (git too old, a replay
2657
+ * conflict, a branch merge the replay cannot reproduce, or
2658
+ * SM_LINEAR_LANDING_DISABLE=1). Landings stay linear because Bilko's
2659
+ * scripts/sync-local-main.sh refuses a local main carrying merge commits
2660
+ * origin lacks.
2232
2661
  *
2233
2662
  * Original author name/email/date and the full message are preserved; commits
2234
2663
  * whose patch is already in `ontoSha`'s history (cherry-pick equivalence) or
2235
- * that become empty are listed in `skipped`. Merge commits are never replayed.
2664
+ * that become empty are listed in `skipped`. Merge commits are never replayed,
2665
+ * so a merge's resolution (e.g. a conflict resolved with `git merge` in an Epic
2666
+ * worktree) can hold content no replayed commit carries: when the replayed
2667
+ * range holds a merge commit, the replayed tip's tree must equal the tree
2668
+ * `git merge-tree --write-tree <onto> <branch>` writes (real merge base), or
2669
+ * it fails `branch_has_merges` rather than drop that content.
2236
2670
  * Needs git >= 2.40 (`merge-tree --merge-base`). Never throws.
2671
+ * `sinceSha` (the commit the branch forked from) bounds every range to commits
2672
+ * not reachable from it: when the base was rewritten (rebase/reset) while the
2673
+ * job ran, the branch's inherited pre-rewrite commits have rebased copies with
2674
+ * other patch-ids and would replay with spurious conflicts. An unusable
2675
+ * `sinceSha` (empty, unresolvable, not an ancestor of the tip) is ignored.
2237
2676
  *
2677
+ * @param {{ cwd: string, ontoSha: string, branch: string, sinceSha?: string }} opts
2238
2678
  * @returns {Promise<{ok:true, tipSha:string, replayed:{from:string,to:string}[], skipped:string[], fastForward?:true}
2239
2679
  * | {ok:false, failureKind:string, reason:string, conflictedPaths?:string[]}>}
2240
2680
  */
2241
- async function replayBranchOnto({ cwd, ontoSha, branch }) {
2681
+ async function replayBranchOnto({ cwd, ontoSha, branch, sinceSha }) {
2242
2682
  try {
2243
2683
  // Resolve once; from here on only SHAs reach git, so a branch named like an
2244
2684
  // option ('-x') can never be read as one (same reason as runMergeTreeWriteTree).
@@ -2250,17 +2690,25 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
2250
2690
  || await tryResolveCommit(cwd, `refs/heads/${branch}^{commit}`);
2251
2691
  if (!tipIn) return { ok: false, failureKind: 'other', reason: `branch "${branch}" not found` };
2252
2692
 
2253
- try {
2254
- await execGit(['merge-base', '--is-ancestor', onto, tipIn], { cwd, timeout: 10_000 });
2255
- return { ok: true, tipSha: tipIn, replayed: [], skipped: [], fastForward: true };
2256
- } catch (e) {
2257
- if (!(e && e.code === 1)) {
2258
- return { ok: false, failureKind: 'other', reason: `merge-base --is-ancestor failed: ${(e && (e.stderrText || e.message)) || e}` };
2693
+ const since = await resolveForkBound(cwd, sinceSha, tipIn);
2694
+ // Fast-forward shortcut only when `onto` already holds the fork: an `onto`
2695
+ // that is an ancestor of the tip but NOT of the fork (base reset under the
2696
+ // job) would otherwise land the pre-rewrite commits the branch inherited.
2697
+ const ontoHoldsFork = !since || (await isAncestorOf(cwd, since, onto)) === true;
2698
+ if (ontoHoldsFork) {
2699
+ try {
2700
+ await execGit(['merge-base', '--is-ancestor', onto, tipIn], { cwd, timeout: 10_000 });
2701
+ return { ok: true, tipSha: tipIn, replayed: [], skipped: [], fastForward: true };
2702
+ } catch (e) {
2703
+ if (!(e && e.code === 1)) {
2704
+ return { ok: false, failureKind: 'other', reason: `merge-base --is-ancestor failed: ${(e && (e.stderrText || e.message)) || e}` };
2705
+ }
2259
2706
  }
2260
2707
  }
2261
2708
 
2709
+ const bound = since ? [`^${since}`] : [];
2262
2710
  const lines = async (extra) => (await execGit(
2263
- ['rev-list', '--reverse', '--topo-order', '--no-merges', ...extra, '--right-only', `${onto}...${tipIn}`],
2711
+ ['rev-list', '--reverse', '--topo-order', '--no-merges', ...extra, '--right-only', `${onto}...${tipIn}`, ...bound],
2264
2712
  { cwd, timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
2265
2713
  )).split('\n').map((l) => l.trim()).filter(Boolean);
2266
2714
  const kept = await lines(['--cherry-pick']);
@@ -2355,6 +2803,37 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
2355
2803
  replayed.push({ from: c, to: newSha });
2356
2804
  tip = newSha;
2357
2805
  }
2806
+
2807
+ // Validator finding I-1: a merge commit's resolution never reaches the
2808
+ // replay above, so prove the replay reproduced the branch's content — the
2809
+ // tree a real merge of the two tips writes — before calling it linear.
2810
+ const mergeCount = Number.parseInt((await execGit(
2811
+ ['rev-list', '--count', '--merges', `${onto}..${tipIn}`, ...bound],
2812
+ { cwd, timeout: 30_000 },
2813
+ )).trim(), 10);
2814
+ if (mergeCount > 0) {
2815
+ let mergedTree = '';
2816
+ try {
2817
+ const out = await execGit(
2818
+ ['merge-tree', '--write-tree', '--no-messages', ...(since ? [`--merge-base=${since}`] : []), onto, tipIn],
2819
+ { cwd, timeout: 30_000 },
2820
+ );
2821
+ mergedTree = (out.split('\n')[0] || '').trim();
2822
+ } catch {
2823
+ // Any non-zero exit, a conflict included, leaves no tree to prove the replay against.
2824
+ }
2825
+ const replayedTree = (await execGit(['rev-parse', `${tip}^{tree}`], { cwd, timeout: 10_000 })).trim();
2826
+ if (!mergedTree || mergedTree !== replayedTree) {
2827
+ const merges = `${mergeCount} merge commit${mergeCount === 1 ? '' : 's'}`;
2828
+ return {
2829
+ ok: false,
2830
+ failureKind: 'branch_has_merges',
2831
+ reason: mergedTree
2832
+ ? `branch holds ${merges} whose content a linear replay does not reproduce (replayed tree ${replayedTree}, merged tree ${mergedTree})`
2833
+ : `branch holds ${merges} and git merge-tree of ${onto} and ${tipIn} wrote no clean tree to check the replay against`,
2834
+ };
2835
+ }
2836
+ }
2358
2837
  const result = { ok: true, tipSha: tip, replayed, skipped };
2359
2838
  if (autoResolved) { result.autoResolved = autoResolved; result.resolvedPaths = Array.from(resolvedSet).sort(); }
2360
2839
  return result;
@@ -2364,15 +2843,31 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
2364
2843
  }
2365
2844
 
2366
2845
  /**
2367
- * One computation attempt for `integrateOntoRef` — resolves both tips fresh,
2368
- * decides ff vs merge-commit vs no-op, and lands the result via a
2846
+ * One computation attempt for `integrateOntoRef` — resolves both tips fresh
2847
+ * and decides, in order: no-op (`integrated: false`); fast-forward when
2848
+ * `targetRef` is an ancestor of `branch` (`fastForward: true`); otherwise a
2849
+ * linear replay of the branch's commits onto the ref tip via
2850
+ * `replayBranchOnto` (`linear: true`, `replayedCommits`). Only when
2851
+ * SM_LINEAR_LANDING_DISABLE=1 or the replay fails with one of
2852
+ * `REPLAY_MERGE_FALLBACK_KINDS` (`git_too_old` / `content_conflict` /
2853
+ * `branch_has_merges`) does it console.warn and fall back to a two-parent
2854
+ * merge commit (`git merge-tree --write-tree` + `git commit-tree`, parents
2855
+ * [ref tip, branch tip]) reported as `mergeCommit: true` with
2856
+ * `linearFallback` naming why; any other replay failure is
2857
+ * `failureKind: 'other'` with the ref untouched. Every outcome lands via a
2369
2858
  * compare-and-swap `git update-ref`. Returns `{ retry: true }` (never `ok`)
2370
2859
  * when the CAS lost a race against a concurrent ref update — the caller
2371
2860
  * recomputes from scratch, since a stale `oldSha` invalidates everything
2372
- * derived from it (the ff-vs-merge decision, the merge-tree/commit-tree
2373
- * inputs). Every other return is terminal: a real `{ ok: true/false, ... }`.
2861
+ * derived from it (the ff/replay/merge decision, the replayed commits, the
2862
+ * merge-tree/commit-tree inputs). Every other return is terminal: a real
2863
+ * `{ ok: true/false, ... }`.
2864
+ *
2865
+ * SM_LINEAR_LANDING_DISABLE=1 is not honoured on a rewritten base (forkSha no
2866
+ * longer an ancestor of `targetRef`): a merge commit would merge the
2867
+ * pre-rewrite history back in, so the fork-bounded replay always runs and a
2868
+ * failed replay is terminal with no merge-commit fallback.
2374
2869
  */
2375
- async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
2870
+ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message, forkSha }) {
2376
2871
  const branchSha = await tryResolveCommit(cwd, `${branch}^{commit}`);
2377
2872
  if (!branchSha) return { ok: false, reason: `branch "${branch}" not found` };
2378
2873
 
@@ -2391,6 +2886,10 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
2391
2886
  if (oldSha === branchSha) {
2392
2887
  return { ok: true, integrated: false, reason: 'branch has no new commits' };
2393
2888
  }
2889
+ const { fork, baseRewritten } = await resolveRewrittenFork(cwd, forkSha, branchSha, oldSha);
2890
+ if (fork && fork === branchSha) {
2891
+ return { ok: true, integrated: false, reason: 'branch has no new commits' };
2892
+ }
2394
2893
 
2395
2894
  // Retries only when `targetRef` actually moved since `oldSha` was read
2396
2895
  // (a real CAS race a fresh attempt can resolve); otherwise the update-ref
@@ -2429,13 +2928,44 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
2429
2928
  }
2430
2929
  }
2431
2930
 
2432
- if (isAncestor) {
2931
+ // Same rewritten-base rule as the in-checkout path: never fast-forward the
2932
+ // pre-rewrite commits back in; replay only the job's own commits below.
2933
+ if (isAncestor && !baseRewritten) {
2433
2934
  const outcome = await updateRefOrClassify([targetRef, branchSha, oldSha]);
2434
2935
  if (outcome.retry) return { retry: true };
2435
2936
  if (!outcome.ok) return outcome;
2436
2937
  return { ok: true, integrated: true, fastForward: true, sha: branchSha };
2437
2938
  }
2438
2939
 
2940
+ // Diverged: replay the branch's commits onto the ref tip and land the
2941
+ // replayed tip through the same CAS — the in-checkout path's linear landing
2942
+ // (PRD 2743), done checkout-free. `branchSha`, never the name, reaches the
2943
+ // replay so it rebuilds exactly the commits resolved above. A two-parent
2944
+ // merge is only the logged fallback for what a replay cannot do.
2945
+ let linearFallback = '';
2946
+ if (process.env.SM_LINEAR_LANDING_DISABLE === '1' && !baseRewritten) {
2947
+ linearFallback = 'disabled';
2948
+ } else {
2949
+ const r = await replayBranchOnto({ cwd, ontoSha: oldSha, branch: branchSha, sinceSha: fork || undefined });
2950
+ if (r.ok) {
2951
+ const outcome = await updateRefOrClassify([targetRef, r.tipSha, oldSha]);
2952
+ if (outcome.retry) return { retry: true };
2953
+ if (!outcome.ok) return outcome;
2954
+ return {
2955
+ ok: true, integrated: true, linear: true, sha: r.tipSha, replayedCommits: r.replayed.length,
2956
+ ...(r.autoResolved ? { autoResolved: r.autoResolved, resolvedPaths: r.resolvedPaths } : {}),
2957
+ };
2958
+ }
2959
+ if (baseRewritten && REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
2960
+ return rewrittenBaseReplayFailure(r, oldSha, { cwd, fork, tip: branchSha });
2961
+ }
2962
+ if (!REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
2963
+ return { ok: false, failureKind: 'other', reason: r.reason };
2964
+ }
2965
+ linearFallback = r.failureKind;
2966
+ }
2967
+ console.warn(`[gitWorktree] linear landing of ${branch} onto ${targetRef} fell back to a merge commit (${linearFallback})`);
2968
+
2439
2969
  const mergeTreeResult = await runMergeTreeWriteTree({ cwd, oldSha, branchSha });
2440
2970
  if (!mergeTreeResult.ok) return mergeTreeResult;
2441
2971
 
@@ -2461,29 +2991,9 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
2461
2991
  const outcome = await updateRefOrClassify([targetRef, newSha, oldSha]);
2462
2992
  if (outcome.retry) return { retry: true };
2463
2993
  if (!outcome.ok) return outcome;
2464
- return { ok: true, integrated: true, mergeCommit: true, sha: newSha };
2994
+ return { ok: true, integrated: true, mergeCommit: true, sha: newSha, linearFallback };
2465
2995
  }
2466
2996
 
2467
- /**
2468
- * Lands `branch` onto `targetRef` WITHOUT touching any working tree, index,
2469
- * or HEAD — no `git checkout`, no `git merge`, nothing in any human's or
2470
- * job's own checkout ever moves. Fast-forwards via a compare-and-swap `git
2471
- * update-ref` when `targetRef` is an ancestor of `branch`; otherwise builds a
2472
- * merge commit entirely in the object database (`git merge-tree --write-tree`
2473
- * + `git commit-tree`) and lands IT via the same CAS. This is the foundation
2474
- * for a per-Epic `sm-land/<epicId>` integration branch that scheduler jobs
2475
- * can land onto regardless of what the human's own checkout is doing.
2476
- *
2477
- * Refuses up front (`failureKind: 'target_checked_out'`, nothing touched) if
2478
- * `targetRef` is checked out in ANY worktree of this repo — updating a
2479
- * checked-out branch's ref out from under `git worktree list` would desync
2480
- * that working tree's HEAD from its own index, which no compare-and-swap can
2481
- * detect or prevent (a worktree's HEAD isn't a ref-race participant here).
2482
- *
2483
- * A CAS loss (the ref moved between our read and our write — a sibling
2484
- * caller landed first) retries the WHOLE computation, up to 3 attempts total,
2485
- * before giving up with `failureKind: 'ref_race'`.
2486
- */
2487
2997
  /**
2488
2998
  * Normalizes `targetRef` to a full `refs/heads/...` name: a short name like
2489
2999
  * `sm-land/x` becomes `refs/heads/sm-land/x`; a value already under
@@ -2598,7 +3108,35 @@ async function checkTargetRefNotCheckedOut({ cwd, targetRef }) {
2598
3108
  return { ok: true };
2599
3109
  }
2600
3110
 
2601
- async function integrateOntoRef({ cwd, targetRef, branch, message }) {
3111
+ /**
3112
+ * Lands `branch` onto `targetRef` WITHOUT touching any working tree, index,
3113
+ * or HEAD — no `git checkout`, no `git merge`, nothing in any human's or
3114
+ * job's own checkout ever moves. Fast-forwards via a compare-and-swap `git
3115
+ * update-ref` when `targetRef` is an ancestor of `branch`; otherwise replays
3116
+ * the branch's commits onto the ref tip entirely in the object database
3117
+ * (`replayBranchOnto`) and lands the replayed tip via the same CAS
3118
+ * (`linear: true` — no merge commit, so tooling that refuses merge commits,
3119
+ * like Bilko's scripts/sync-local-main.sh, keeps working). Only when
3120
+ * SM_LINEAR_LANDING_DISABLE=1, or the replay needs a newer git, conflicts
3121
+ * on one of the branch's commits, or cannot reproduce a merge commit inside
3122
+ * the branch (`branch_has_merges`), does it fall back — with a console.warn —
3123
+ * to a two-parent merge commit (`git merge-tree --write-tree` + `git
3124
+ * commit-tree`, `message` as its text) landed via the same CAS and reported
3125
+ * as `mergeCommit: true` + `linearFallback`. This is the foundation for a
3126
+ * per-Epic `sm-land/<epicId>` integration branch that scheduler jobs can land
3127
+ * onto regardless of what the human's own checkout is doing.
3128
+ *
3129
+ * Refuses up front (`failureKind: 'target_checked_out'`, nothing touched) if
3130
+ * `targetRef` is checked out in ANY worktree of this repo — updating a
3131
+ * checked-out branch's ref out from under `git worktree list` would desync
3132
+ * that working tree's HEAD from its own index, which no compare-and-swap can
3133
+ * detect or prevent (a worktree's HEAD isn't a ref-race participant here).
3134
+ *
3135
+ * A CAS loss (the ref moved between our read and our write — a sibling
3136
+ * caller landed first) retries the WHOLE computation, up to 3 attempts total,
3137
+ * before giving up with `failureKind: 'ref_race'`.
3138
+ */
3139
+ async function integrateOntoRef({ cwd, targetRef, branch, message, forkSha }) {
2602
3140
  if (!cwd || typeof cwd !== 'string') return { ok: false, reason: 'no cwd provided' };
2603
3141
  if (!targetRef || typeof targetRef !== 'string') return { ok: false, reason: 'no targetRef provided' };
2604
3142
  if (!branch || typeof branch !== 'string') return { ok: false, reason: 'no branch provided' };
@@ -2618,7 +3156,7 @@ async function integrateOntoRef({ cwd, targetRef, branch, message }) {
2618
3156
  for (let attempt = 0; attempt < 3; attempt += 1) {
2619
3157
  const guard = await checkTargetRefNotCheckedOut({ cwd, targetRef: normalizedTargetRef });
2620
3158
  if (!guard.ok) return guard;
2621
- const result = await attemptIntegrateOntoRef({ cwd, targetRef: normalizedTargetRef, branch, message: mergeMessage });
3159
+ const result = await attemptIntegrateOntoRef({ cwd, targetRef: normalizedTargetRef, branch, message: mergeMessage, forkSha });
2622
3160
  if (!result.retry) return result;
2623
3161
  }
2624
3162
  return { ok: false, failureKind: 'ref_race' };
@@ -2694,8 +3232,8 @@ async function ensureLandBranch({ cwd, epicId, baseBranch }) {
2694
3232
  async function createJobWorktree({ cwd, slug, fromRef }) {
2695
3233
  return createWorktree({ kind: 'job', cwd, key: slug, fromRef });
2696
3234
  }
2697
- async function integrateJobBranch({ cwd, branch, slug, carriedPaths, baseBranch, allowRefLanding }) {
2698
- return integrateBranch({ kind: 'job', cwd, branch, key: slug, carriedPaths, baseBranch, allowRefLanding });
3235
+ async function integrateJobBranch({ cwd, branch, slug, carriedPaths, baseBranch, allowRefLanding, forkSha }) {
3236
+ return integrateBranch({ kind: 'job', cwd, branch, key: slug, carriedPaths, baseBranch, allowRefLanding, forkSha });
2699
3237
  }
2700
3238
  async function cleanupJobWorktree({ cwd, dir, branch, keepBranch }) {
2701
3239
  return cleanupWorktree({ kind: 'job', cwd, dir, branch, keepBranch });
@@ -2710,8 +3248,8 @@ async function salvageJobDirtyDelta({ cwd, paths, outFile }) {
2710
3248
  async function createEpicWorktree({ cwd, epicId }) {
2711
3249
  return createWorktree({ kind: 'epic', cwd, key: epicId });
2712
3250
  }
2713
- async function integrateEpicBranch({ cwd, branch, epicId, baseBranch }) {
2714
- return integrateBranch({ kind: 'epic', cwd, branch, key: epicId, baseBranch });
3251
+ async function integrateEpicBranch({ cwd, branch, epicId, baseBranch, forkSha }) {
3252
+ return integrateBranch({ kind: 'epic', cwd, branch, key: epicId, baseBranch, forkSha });
2715
3253
  }
2716
3254
  async function cleanupEpicWorktree({ cwd, dir, branch, keepBranch }) {
2717
3255
  return cleanupWorktree({ kind: 'epic', cwd, dir, branch, keepBranch });
@@ -2789,6 +3327,46 @@ async function listStrandedPins({ cwd, key, sinceMs }) {
2789
3327
  }
2790
3328
  }
2791
3329
 
3330
+ /**
3331
+ * Recover the commit `branch` forked from. Returns `recorded` when it resolves
3332
+ * to a commit that is an ancestor of (or equal to) the branch tip; else the
3333
+ * oldest `git reflog` entry of refs/heads/<branch> (its creation point) when
3334
+ * that is an ancestor of the tip; else null. Never throws. The branch is
3335
+ * always addressed as refs/heads/<branch>, so a '-'-prefixed name can't be
3336
+ * read as an option.
3337
+ *
3338
+ * Why: integration can replay only a job's own commits after a base rewrite
3339
+ * only if it knows the fork point; the reflog fallback covers rows queued
3340
+ * before createWorktree started returning `forkSha`.
3341
+ *
3342
+ * @param {{ cwd: string, branch: string, recorded?: string|null }} opts
3343
+ * @returns {Promise<string|null>}
3344
+ */
3345
+ async function resolveForkSha({ cwd, branch, recorded }) {
3346
+ try {
3347
+ if (!cwd || typeof cwd !== 'string' || !branch || typeof branch !== 'string') return null;
3348
+ const ref = `refs/heads/${branch}`;
3349
+ const tip = await tryResolveCommit(cwd, `${ref}^{commit}`);
3350
+ if (!tip) return null;
3351
+ if (typeof recorded === 'string' && recorded && !recorded.startsWith('-')) {
3352
+ const sha = await tryResolveCommit(cwd, `${recorded}^{commit}`);
3353
+ if (sha && (await isAncestorOf(cwd, sha, tip)) === true) return sha;
3354
+ }
3355
+ let out = '';
3356
+ try {
3357
+ out = await execGit(['reflog', 'show', '--format=%H', ref, '--'], { cwd, timeout: 10_000 });
3358
+ } catch {
3359
+ return null;
3360
+ }
3361
+ const entries = String(out).split('\n').map((l) => l.trim()).filter(Boolean);
3362
+ const oldest = entries.length ? entries[entries.length - 1] : null;
3363
+ if (oldest && /^[0-9a-f]{40,64}$/.test(oldest) && (await isAncestorOf(cwd, oldest, tip)) === true) return oldest;
3364
+ return null;
3365
+ } catch {
3366
+ return null;
3367
+ }
3368
+ }
3369
+
2792
3370
  /** True/false for `git merge-base --is-ancestor a b`; null on a real failure. */
2793
3371
  async function isAncestorOf(cwd, a, b) {
2794
3372
  try {
@@ -2904,7 +3482,99 @@ async function pinStrandedHead({ cwd, dir }) {
2904
3482
  } catch { /* best-effort */ }
2905
3483
  }
2906
3484
 
3485
+ // ──────────────────────────────────────────── uncommitted-work snapshot (PRD 2891)
3486
+
3487
+ /**
3488
+ * Pins a checkout's uncommitted work (tracked changes + untracked,
3489
+ * non-ignored files) as a commit whose parent is the checkout's HEAD, under
3490
+ * UNCOMMITTED_REF_PREFIX/<safePinKey(key)>/<sha> in `cwd` (the main tree).
3491
+ * Built through a throwaway GIT_INDEX_FILE outside the repo, so the
3492
+ * checkout's own index and the shared stash stack are never touched.
3493
+ *
3494
+ * Returns null when there is nothing unique to keep (clean, missing dir, or
3495
+ * every dirty path byte-identical to `cwd`), `{ sha, ref, paths }` on
3496
+ * success, `{ error, paths }` on a git failure. Never throws.
3497
+ */
3498
+ async function snapshotUncommittedWork({ cwd, dir, key }) {
3499
+ /** @type {string[]} */
3500
+ let paths = [];
3501
+ if (!dir || !fs.existsSync(dir)) return null;
3502
+ // A half-created checkout with no .git entry has nothing git can snapshot.
3503
+ if (!fs.existsSync(path.join(dir, '.git'))) return null;
3504
+ let tmpIndex = null;
3505
+ try {
3506
+ const status = await execGit(['status', '--porcelain', '--untracked-files=all'], { cwd: dir, timeout: 30_000 });
3507
+ for (const line of status.split('\n')) {
3508
+ if (line.length < 4) continue;
3509
+ const rest = line.slice(3);
3510
+ const arrow = rest.indexOf(' -> ');
3511
+ const parts = arrow === -1 ? [rest] : [rest.slice(0, arrow), rest.slice(arrow + 4)];
3512
+ for (const raw of parts) {
3513
+ const p = unquotePorcelainPath(raw.trim());
3514
+ if (p && !paths.includes(p)) paths.push(p);
3515
+ }
3516
+ }
3517
+ if (!paths.length) return null;
3518
+ const identical = new Set(await unchangedCarriedPaths({ cwd, dir, paths }));
3519
+ paths = paths.filter((p) => !identical.has(p));
3520
+ if (!paths.length) return null;
3521
+
3522
+ tmpIndex = path.join(os.tmpdir(), `sm-uncommitted-${process.pid}-${crypto.randomBytes(8).toString('hex')}.index`);
3523
+ const env = { GIT_INDEX_FILE: tmpIndex };
3524
+ await execGit(['read-tree', 'HEAD'], { cwd: dir, timeout: 30_000, env });
3525
+ await execGit(['add', '-A', '--', '.'], { cwd: dir, timeout: 120_000, env });
3526
+ const tree = (await execGit(['write-tree'], { cwd: dir, timeout: 30_000, env })).trim();
3527
+ const message = `sm: uncommitted work left in ${key || path.basename(dir)} worktree`;
3528
+ const commitArgs = ['commit-tree', tree, '-p', 'HEAD', '-m', message];
3529
+ let sha;
3530
+ try {
3531
+ sha = (await execGit(commitArgs, { cwd: dir, timeout: 30_000 })).trim();
3532
+ } catch {
3533
+ // No configured identity on this machine — fall back to a neutral one.
3534
+ sha = (await execGit(commitArgs, {
3535
+ cwd: dir,
3536
+ timeout: 30_000,
3537
+ env: {
3538
+ GIT_AUTHOR_NAME: 'Session Manager', GIT_AUTHOR_EMAIL: 'session-manager@localhost',
3539
+ GIT_COMMITTER_NAME: 'Session Manager', GIT_COMMITTER_EMAIL: 'session-manager@localhost',
3540
+ },
3541
+ })).trim();
3542
+ }
3543
+ if (!/^[0-9a-f]{40,64}$/.test(sha)) throw new Error(`commit-tree returned no sha: ${sha}`);
3544
+ const ref = `${sharedGitExec.UNCOMMITTED_REF_PREFIX}${safePinKey(key || path.basename(dir))}/${sha}`;
3545
+ await execGit(['update-ref', ref, sha], { cwd: cwd || dir, timeout: 10_000 });
3546
+ return { sha, ref, paths };
3547
+ } catch (err) {
3548
+ const e = /** @type {any} */ (err);
3549
+ const msg = String((e && (e.stderrText || e.message)) || e).trim().split('\n')[0] || 'git failure';
3550
+ return { error: msg, paths };
3551
+ } finally {
3552
+ if (tmpIndex) {
3553
+ try { await fsp.rm(tmpIndex, { force: true }); } catch { /* best-effort */ }
3554
+ try { await fsp.rm(`${tmpIndex}.lock`, { force: true }); } catch { /* best-effort */ }
3555
+ }
3556
+ }
3557
+ }
3558
+
3559
+ /**
3560
+ * Number of commit / cherry-pick / revert entries in `dir`'s HEAD reflog
3561
+ * (same subject test as pinUnlandedWorktreeCommits) — the commits a run made
3562
+ * in this checkout. -1 on any failure. Never throws.
3563
+ */
3564
+ async function worktreeRunCommitCount({ dir }) {
3565
+ try {
3566
+ if (!dir || !fs.existsSync(dir)) return -1;
3567
+ const out = await execGit(['reflog', 'show', '--format=%gs', '-n', '200', 'HEAD'], { cwd: dir, timeout: 15_000 });
3568
+ return out.split('\n').filter((l) => /^(commit|cherry-pick|revert)\b/.test(l)).length;
3569
+ } catch {
3570
+ return -1;
3571
+ }
3572
+ }
3573
+
2907
3574
  module.exports = {
3575
+ snapshotUncommittedWork,
3576
+ worktreeRunCommitCount,
3577
+ findRuntimeStateAdds,
2908
3578
  replayBranchOnto,
2909
3579
  reconcileWorktreeHead,
2910
3580
  pinUnlandedWorktreeCommits,
@@ -2928,16 +3598,21 @@ module.exports = {
2928
3598
  getCurrentBranch,
2929
3599
  isCarriedWipOnly,
2930
3600
  integrateBranch,
3601
+ withCheckoutLock,
3602
+ // Test-only view of the live lock map (entries exist only while busy).
3603
+ _checkoutLocks: checkoutLocks,
2931
3604
  cleanupWorktree,
2932
3605
  salvageWorktreeDiff,
2933
3606
  salvageDirtyDelta,
2934
3607
  isBranchMergedIntoHead,
3608
+ isBranchContentLanded,
2935
3609
  parseWorktreeListPorcelain,
2936
3610
  listCwdHolders,
2937
3611
  hasLiveHolder,
2938
3612
  reconcileWorktreesOnBoot,
2939
3613
  deleteBranchKeepingUniqueCommits,
2940
3614
  listStrandedPins,
3615
+ resolveForkSha,
2941
3616
  sweepStaleWorktreeCheckouts,
2942
3617
  mainTreeFromWorktreeGitFile,
2943
3618
  getObservedWorktreeCount,