claude-code-session-manager 0.130.3 → 0.132.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.
- package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-C09MlPFx.js} +2 -2
- package/dist/assets/AppSettings-DvDKsCnD.js +2 -0
- package/dist/assets/{Button-UUr5giu8.js → Button-BzG_KdBC.js} +1 -1
- package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-fm6zsnLM.js} +1 -1
- package/dist/assets/Extensions-DgxKT_OZ.js +2 -0
- package/dist/assets/{History-Bndupj87.js → History-Nd3bKjBq.js} +2 -2
- package/dist/assets/{Library-DFn0YPIW.js → Library-R71t6VAB.js} +12 -12
- package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-CG50Ul7c.js} +1 -1
- package/dist/assets/{Panel-CIvb-XXN.js → Panel-C7EFG4eU.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-J92iNEGC.js} +7 -7
- package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-C3KB3ILO.js} +1 -1
- package/dist/assets/Scheduler-DeYBA7uc.js +16 -0
- package/dist/assets/{Settings-DqxUna06.js → Settings-B6r7N4v-.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-D7bt3fyB.js} +1 -1
- package/dist/assets/Skills-GpxtUrFP.js +29 -0
- package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-uyVMCZc7.js} +1 -1
- package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-Cv25uFSM.js} +1 -1
- package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-uP8fJkbM.js} +1 -1
- package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DRs80cX-.js} +1 -1
- package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-BDkvvzJ8.js} +1 -1
- package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-Cmtz2sQt.js} +1 -1
- package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-DHwAXunq.js} +1 -1
- package/dist/assets/index-CBCdyHbZ.js +3097 -0
- package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +414 -390
- package/package.json +1 -1
- package/scripts/scheduler-mcp-server.cjs +83 -4
- package/src/main/build-info.json +4 -4
- package/src/main/index.cjs +11 -0
- package/src/main/ipcSchemas.cjs +28 -1
- package/src/main/lib/epic/epicMint.cjs +61 -6
- package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
- package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
- package/src/main/lib/epic/restorableSessions.cjs +749 -0
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
- package/src/main/lib/git/branchSweep.cjs +9 -3
- package/src/main/lib/git/gitExec.cjs +8 -1
- package/src/main/lib/git/gitWorktree.cjs +564 -62
- package/src/main/lib/git/jobWorktree.cjs +3 -0
- package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
- package/src/main/lib/mcpToolCatalog.cjs +43 -6
- package/src/main/lib/mcpToolsProbe.cjs +831 -0
- package/src/main/lib/persona-macro/builtinMacros.cjs +33 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
- package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
- package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
- package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
- package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
- package/src/main/lib/project-pages/matrixStore.cjs +112 -0
- package/src/main/lib/promptSessionSchema.cjs +5 -0
- package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
- package/src/main/projectPages.cjs +25 -2
- package/src/main/promptSessionEvents.cjs +10 -6
- package/src/main/runVerify.cjs +8 -3
- package/src/main/scheduler/budget.cjs +146 -7
- package/src/main/scheduler/gitTreeGuard.cjs +10 -11
- package/src/main/scheduler/reviewLadder.cjs +60 -0
- package/src/main/scheduler.cjs +461 -48
- package/src/main/seedAgentPersonas.cjs +1 -1
- package/src/preload/api.d.ts +162 -2
- package/src/preload/apiSurface.json +21 -0
- package/src/preload/index.cjs +5 -0
- package/src/seed/agents/competitive-analyst.md +69 -0
- package/src/seed/agents/competitive-researcher.md +75 -0
- package/src/seed/agents/validator.md +2 -2
- package/dist/assets/AppSettings-Cs4POznd.js +0 -2
- package/dist/assets/Extensions-B9QdiNOV.js +0 -2
- package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
- package/dist/assets/Skills-DTXehVS7.js +0 -12
- package/dist/assets/index-C9w-dVzo.js +0 -3090
|
@@ -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 }
|
|
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
|
-
|
|
516
|
-
|
|
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 =
|
|
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
|
-
|
|
1383
|
-
mergeBase =
|
|
1384
|
-
}
|
|
1385
|
-
|
|
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', `${
|
|
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,7 +1654,7 @@ 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
1660
|
// Spread refResult first so the landing's own shape passes through
|
|
@@ -1547,6 +1669,9 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1547
1669
|
if (refResult.failureKind === 'target_checked_out') {
|
|
1548
1670
|
return strayCheckoutFailure;
|
|
1549
1671
|
}
|
|
1672
|
+
if (refResult.baseRewritten) {
|
|
1673
|
+
return refResult;
|
|
1674
|
+
}
|
|
1550
1675
|
if (refResult.failureKind === 'content_conflict') {
|
|
1551
1676
|
return {
|
|
1552
1677
|
ok: false,
|
|
@@ -1558,6 +1683,20 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1558
1683
|
return strayCheckoutFailure;
|
|
1559
1684
|
}
|
|
1560
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 }) {
|
|
1561
1700
|
let branchHead;
|
|
1562
1701
|
try {
|
|
1563
1702
|
branchHead = (await execGit(['rev-parse', branch], { cwd, timeout: 10_000 })).trim();
|
|
@@ -1573,6 +1712,14 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1573
1712
|
if (mergeBase && mergeBase === branchHead) {
|
|
1574
1713
|
return { ok: true, integrated: false, reason: 'branch has no new commits' };
|
|
1575
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;
|
|
1576
1723
|
|
|
1577
1724
|
// Path membership alone is NOT enough: a job that legitimately edits the
|
|
1578
1725
|
// SAME file the base tree had carried-in WIP on (e.g. this repo's own
|
|
@@ -1583,11 +1730,14 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1583
1730
|
// than the ordinary merge-conflict path (branch kept, flagged for manual
|
|
1584
1731
|
// recovery) this shortcut is supposed to be a safe subset of. See
|
|
1585
1732
|
// `isCarriedWipOnly` above for the content-verify logic.
|
|
1586
|
-
if (await isCarriedWipOnly({ cwd, branch, carriedPaths })) {
|
|
1733
|
+
if (await isCarriedWipOnly({ cwd, branch, carriedPaths, scopeBase: baseRewritten && fork ? fork : undefined })) {
|
|
1587
1734
|
return { ok: true, integrated: false, reason: 'carried-wip-only' };
|
|
1588
1735
|
}
|
|
1589
1736
|
|
|
1590
|
-
const
|
|
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 });
|
|
1591
1741
|
if (clobber.length) {
|
|
1592
1742
|
return {
|
|
1593
1743
|
ok: false,
|
|
@@ -1597,26 +1747,34 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1597
1747
|
baseHeadSha: await readHeadSha(cwd),
|
|
1598
1748
|
};
|
|
1599
1749
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
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
|
+
}
|
|
1609
1764
|
}
|
|
1610
1765
|
let linearFallback = '';
|
|
1611
|
-
if (process.env.SM_LINEAR_LANDING_DISABLE === '1') {
|
|
1766
|
+
if (process.env.SM_LINEAR_LANDING_DISABLE === '1' && !baseRewritten) {
|
|
1612
1767
|
linearFallback = 'disabled';
|
|
1613
1768
|
} else {
|
|
1614
1769
|
const MAX_LINEAR_ATTEMPTS = 3;
|
|
1615
1770
|
let landed = null;
|
|
1616
1771
|
for (let attempt = 0; attempt < MAX_LINEAR_ATTEMPTS; attempt++) {
|
|
1617
1772
|
const headSha = await readHeadSha(cwd);
|
|
1618
|
-
const r = await replayBranchOnto({ cwd, ontoSha: headSha, branch: branchHead });
|
|
1773
|
+
const r = await replayBranchOnto({ cwd, ontoSha: headSha, branch: branchHead, sinceSha: fork || undefined });
|
|
1619
1774
|
if (!r.ok) {
|
|
1775
|
+
if (baseRewritten && REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
|
|
1776
|
+
return rewrittenBaseReplayFailure(r, headSha, { cwd, fork, tip: branchHead });
|
|
1777
|
+
}
|
|
1620
1778
|
if (REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
|
|
1621
1779
|
linearFallback = r.failureKind;
|
|
1622
1780
|
break;
|
|
@@ -1671,6 +1829,15 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
|
|
|
1671
1829
|
}
|
|
1672
1830
|
if (landed) return landed;
|
|
1673
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
|
+
}
|
|
1674
1841
|
}
|
|
1675
1842
|
console.warn(`[gitWorktree] linear landing of ${branch} fell back to a merge commit (${linearFallback})`);
|
|
1676
1843
|
const fb = { linearFallback };
|
|
@@ -1802,6 +1969,44 @@ async function findIgnoredLivePaths({ cwd, branch, mergeBase }) {
|
|
|
1802
1969
|
return live;
|
|
1803
1970
|
}
|
|
1804
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
|
+
|
|
1805
2010
|
/**
|
|
1806
2011
|
* Tear down one worktree checkout after it has been integrated (or failed to
|
|
1807
2012
|
* integrate). Always removes the linked-worktree checkout (freeing its
|
|
@@ -1811,8 +2016,16 @@ async function findIgnoredLivePaths({ cwd, branch, mergeBase }) {
|
|
|
1811
2016
|
*/
|
|
1812
2017
|
async function cleanupWorktree({ kind, cwd, dir, branch, keepBranch }) {
|
|
1813
2018
|
configFor(kind); // throws on an unknown kind before anything else runs
|
|
1814
|
-
|
|
1815
|
-
|
|
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)) {
|
|
1816
2029
|
try { await execGit(['branch', '-D', branch], { cwd, timeout: 10_000 }); } catch { /* already gone */ }
|
|
1817
2030
|
}
|
|
1818
2031
|
try { await execGit(['worktree', 'prune'], { cwd, timeout: 10_000 }); } catch { /* best effort */ }
|
|
@@ -1824,6 +2037,7 @@ async function cleanupWorktree({ kind, cwd, dir, branch, keepBranch }) {
|
|
|
1824
2037
|
const alreadyExpired = dir ? expiredCheckoutDirs.delete(dir) : false;
|
|
1825
2038
|
if (dir) registeredCheckouts.delete(dir);
|
|
1826
2039
|
if (dir && !alreadyExpired) activeWorktreeCount[kind] = Math.max(0, activeWorktreeCount[kind] - 1);
|
|
2040
|
+
return { snapshot, removed };
|
|
1827
2041
|
}
|
|
1828
2042
|
|
|
1829
2043
|
/**
|
|
@@ -1956,11 +2170,15 @@ async function salvageDirtyDelta({ cwd, paths, outFile }) {
|
|
|
1956
2170
|
* once per process lifetime, and `reclaimTerminalJobOrphans` keep its checkout
|
|
1957
2171
|
* (validator finding I-2). Used by both to tell a genuinely stranded
|
|
1958
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.
|
|
1959
2177
|
* Never throws; a branch that doesn't exist, or any other git failure, is
|
|
1960
2178
|
* conservatively reported as NOT merged so a caller never treats an
|
|
1961
2179
|
* unreadable branch as safe to skip.
|
|
1962
2180
|
*/
|
|
1963
|
-
async function isBranchMergedIntoHead(cwd, branch) {
|
|
2181
|
+
async function isBranchMergedIntoHead(cwd, branch, forkSha = null) {
|
|
1964
2182
|
let branchHead;
|
|
1965
2183
|
try {
|
|
1966
2184
|
branchHead = (await execGit(['rev-parse', '--verify', branch], { cwd, timeout: 10_000 })).trim();
|
|
@@ -1973,7 +2191,7 @@ async function isBranchMergedIntoHead(cwd, branch) {
|
|
|
1973
2191
|
} catch {
|
|
1974
2192
|
// No merge base, or git failed: ancestry proves nothing, so the content check decides.
|
|
1975
2193
|
}
|
|
1976
|
-
return (await isBranchContentLanded({ cwd, base: 'HEAD', branch })) === true;
|
|
2194
|
+
return (await isBranchContentLanded({ cwd, base: 'HEAD', branch, sinceSha: forkSha || undefined })) === true;
|
|
1977
2195
|
}
|
|
1978
2196
|
|
|
1979
2197
|
/**
|
|
@@ -1996,11 +2214,105 @@ async function isBranchMergedIntoHead(cwd, branch) {
|
|
|
1996
2214
|
* never reads as landed. Never throws. Both names resolve to SHAs first and
|
|
1997
2215
|
* only SHAs reach git. A name starting with '-' resolves only via
|
|
1998
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.
|
|
1999
2221
|
*
|
|
2000
|
-
* @param {{ cwd?: string, base?: string, branch?: string }} [opts]
|
|
2222
|
+
* @param {{ cwd?: string, base?: string, branch?: string, sinceSha?: string }} [opts]
|
|
2001
2223
|
* @returns {Promise<boolean|null>}
|
|
2002
2224
|
*/
|
|
2003
|
-
|
|
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 } = {}) {
|
|
2004
2316
|
try {
|
|
2005
2317
|
if (typeof cwd !== 'string' || !cwd) return null;
|
|
2006
2318
|
const resolveName = async (name) => {
|
|
@@ -2019,9 +2331,12 @@ async function isBranchContentLanded({ cwd, base = 'HEAD', branch } = {}) {
|
|
|
2019
2331
|
// Exit 1 = not an ancestor. On any other failure, try the content proofs.
|
|
2020
2332
|
}
|
|
2021
2333
|
|
|
2334
|
+
const since = await resolveForkBound(cwd, sinceSha, tipSha);
|
|
2335
|
+
if (since && since === tipSha) return true;
|
|
2336
|
+
|
|
2022
2337
|
try {
|
|
2023
2338
|
const out = await execGit(
|
|
2024
|
-
['rev-list', '--right-only', '--cherry-pick', '--no-merges', '--count', `${baseSha}...${tipSha}`],
|
|
2339
|
+
['rev-list', '--right-only', '--cherry-pick', '--no-merges', '--count', `${baseSha}...${tipSha}`, ...(since ? [`^${since}`] : [])],
|
|
2025
2340
|
{ cwd, timeout: 30_000 },
|
|
2026
2341
|
);
|
|
2027
2342
|
if (Number.parseInt(out.trim(), 10) === 0) return true;
|
|
@@ -2030,7 +2345,10 @@ async function isBranchContentLanded({ cwd, base = 'HEAD', branch } = {}) {
|
|
|
2030
2345
|
}
|
|
2031
2346
|
|
|
2032
2347
|
try {
|
|
2033
|
-
const out = await execGit(
|
|
2348
|
+
const out = await execGit(
|
|
2349
|
+
['merge-tree', '--write-tree', '--no-messages', ...(since ? [`--merge-base=${since}`] : []), baseSha, tipSha],
|
|
2350
|
+
{ cwd, timeout: 30_000 },
|
|
2351
|
+
);
|
|
2034
2352
|
const mergedTree = (out.split('\n')[0] || '').trim();
|
|
2035
2353
|
const baseTree = (await execGit(['rev-parse', '--verify', `${baseSha}^{tree}`], { cwd, timeout: 10_000 })).trim();
|
|
2036
2354
|
return mergedTree !== '' && mergedTree === baseTree;
|
|
@@ -2127,7 +2445,10 @@ async function reclaimTerminalJobOrphans({ cwd, terminalSlugs, isLive }) {
|
|
|
2127
2445
|
if (live) continue;
|
|
2128
2446
|
}
|
|
2129
2447
|
|
|
2130
|
-
|
|
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);
|
|
2131
2452
|
if (!merged) continue; // real un-landed work — never touch
|
|
2132
2453
|
|
|
2133
2454
|
let statusOut = '';
|
|
@@ -2145,7 +2466,8 @@ async function reclaimTerminalJobOrphans({ cwd, terminalSlugs, isLive }) {
|
|
|
2145
2466
|
);
|
|
2146
2467
|
if (!opsOnly) continue; // real non-ops dirty content present — leave for a human
|
|
2147
2468
|
|
|
2148
|
-
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
|
|
2149
2471
|
if (entry.branch) {
|
|
2150
2472
|
await deleteBranchKeepingUniqueCommits({ cwd, branch: entry.branch, key: slug });
|
|
2151
2473
|
}
|
|
@@ -2196,6 +2518,8 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
|
|
|
2196
2518
|
const root = worktreeRootFor(kind);
|
|
2197
2519
|
const list = Array.isArray(cwds) ? cwds.filter(Boolean) : [];
|
|
2198
2520
|
let checkoutsRemoved = 0;
|
|
2521
|
+
const snapshots = [];
|
|
2522
|
+
const kept = [];
|
|
2199
2523
|
for (const cwd of list) {
|
|
2200
2524
|
if (!(await isGitRepo(cwd))) continue;
|
|
2201
2525
|
let out = '';
|
|
@@ -2212,8 +2536,15 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
|
|
|
2212
2536
|
// even when the checkout is detached or on a branch we do not own.
|
|
2213
2537
|
const key = branchKey || path.basename(entry.worktree);
|
|
2214
2538
|
if (isLive && key && (await isLive(key, entry))) continue;
|
|
2215
|
-
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
|
+
}
|
|
2216
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
|
+
}
|
|
2217
2548
|
// sm-land/* is the per-Epic integration branch, never a throwaway
|
|
2218
2549
|
// worktree branch — even if something else checked it out onto a
|
|
2219
2550
|
// worktree under this kind's root, this sweep must never delete it.
|
|
@@ -2225,7 +2556,8 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
|
|
|
2225
2556
|
try { await execGit(['worktree', 'prune'], { cwd, timeout: 10_000 }); } catch { /* best effort */ }
|
|
2226
2557
|
}
|
|
2227
2558
|
|
|
2228
|
-
|
|
2559
|
+
/** @type {{ checkoutsRemoved: number, emptyRootsRemoved: number, snapshots: any[], kept: any[] }} */
|
|
2560
|
+
let sweep = { checkoutsRemoved: 0, emptyRootsRemoved: 0, snapshots: [], kept: [] };
|
|
2229
2561
|
try {
|
|
2230
2562
|
sweep = await sweepStaleWorktreeCheckouts(kind, { staleAgeMs: opts.staleAgeMs, holders: opts.holders });
|
|
2231
2563
|
} catch {
|
|
@@ -2234,10 +2566,13 @@ async function reconcileWorktreesOnBoot(cwds, opts = {}) {
|
|
|
2234
2566
|
const totals = {
|
|
2235
2567
|
checkoutsRemoved: checkoutsRemoved + sweep.checkoutsRemoved,
|
|
2236
2568
|
emptyRootsRemoved: sweep.emptyRootsRemoved,
|
|
2569
|
+
snapshots: snapshots.concat(sweep.snapshots || []),
|
|
2570
|
+
kept: kept.concat(sweep.kept || []),
|
|
2237
2571
|
};
|
|
2238
2572
|
console.log(
|
|
2239
2573
|
`[gitWorktree] boot sweep (kind:${kind}): reclaimed ${totals.checkoutsRemoved} checkout(s), ` +
|
|
2240
|
-
`${totals.emptyRootsRemoved} empty root dir(s)`
|
|
2574
|
+
`${totals.emptyRootsRemoved} empty root dir(s), ` +
|
|
2575
|
+
`${totals.snapshots.length} uncommitted snapshot(s), ${totals.kept.length} kept`
|
|
2241
2576
|
);
|
|
2242
2577
|
return totals;
|
|
2243
2578
|
}
|
|
@@ -2333,11 +2668,17 @@ const REPLAY_MERGE_FALLBACK_KINDS = new Set(['git_too_old', 'content_conflict',
|
|
|
2333
2668
|
* `git merge-tree --write-tree <onto> <branch>` writes (real merge base), or
|
|
2334
2669
|
* it fails `branch_has_merges` rather than drop that content.
|
|
2335
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.
|
|
2336
2676
|
*
|
|
2677
|
+
* @param {{ cwd: string, ontoSha: string, branch: string, sinceSha?: string }} opts
|
|
2337
2678
|
* @returns {Promise<{ok:true, tipSha:string, replayed:{from:string,to:string}[], skipped:string[], fastForward?:true}
|
|
2338
2679
|
* | {ok:false, failureKind:string, reason:string, conflictedPaths?:string[]}>}
|
|
2339
2680
|
*/
|
|
2340
|
-
async function replayBranchOnto({ cwd, ontoSha, branch }) {
|
|
2681
|
+
async function replayBranchOnto({ cwd, ontoSha, branch, sinceSha }) {
|
|
2341
2682
|
try {
|
|
2342
2683
|
// Resolve once; from here on only SHAs reach git, so a branch named like an
|
|
2343
2684
|
// option ('-x') can never be read as one (same reason as runMergeTreeWriteTree).
|
|
@@ -2349,17 +2690,25 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
|
|
|
2349
2690
|
|| await tryResolveCommit(cwd, `refs/heads/${branch}^{commit}`);
|
|
2350
2691
|
if (!tipIn) return { ok: false, failureKind: 'other', reason: `branch "${branch}" not found` };
|
|
2351
2692
|
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
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
|
+
}
|
|
2358
2706
|
}
|
|
2359
2707
|
}
|
|
2360
2708
|
|
|
2709
|
+
const bound = since ? [`^${since}`] : [];
|
|
2361
2710
|
const lines = async (extra) => (await execGit(
|
|
2362
|
-
['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],
|
|
2363
2712
|
{ cwd, timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
|
|
2364
2713
|
)).split('\n').map((l) => l.trim()).filter(Boolean);
|
|
2365
2714
|
const kept = await lines(['--cherry-pick']);
|
|
@@ -2459,13 +2808,16 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
|
|
|
2459
2808
|
// replay above, so prove the replay reproduced the branch's content — the
|
|
2460
2809
|
// tree a real merge of the two tips writes — before calling it linear.
|
|
2461
2810
|
const mergeCount = Number.parseInt((await execGit(
|
|
2462
|
-
['rev-list', '--count', '--merges', `${onto}..${tipIn}
|
|
2811
|
+
['rev-list', '--count', '--merges', `${onto}..${tipIn}`, ...bound],
|
|
2463
2812
|
{ cwd, timeout: 30_000 },
|
|
2464
2813
|
)).trim(), 10);
|
|
2465
2814
|
if (mergeCount > 0) {
|
|
2466
2815
|
let mergedTree = '';
|
|
2467
2816
|
try {
|
|
2468
|
-
const out = await execGit(
|
|
2817
|
+
const out = await execGit(
|
|
2818
|
+
['merge-tree', '--write-tree', '--no-messages', ...(since ? [`--merge-base=${since}`] : []), onto, tipIn],
|
|
2819
|
+
{ cwd, timeout: 30_000 },
|
|
2820
|
+
);
|
|
2469
2821
|
mergedTree = (out.split('\n')[0] || '').trim();
|
|
2470
2822
|
} catch {
|
|
2471
2823
|
// Any non-zero exit, a conflict included, leaves no tree to prove the replay against.
|
|
@@ -2509,8 +2861,13 @@ async function replayBranchOnto({ cwd, ontoSha, branch }) {
|
|
|
2509
2861
|
* derived from it (the ff/replay/merge decision, the replayed commits, the
|
|
2510
2862
|
* merge-tree/commit-tree inputs). Every other return is terminal: a real
|
|
2511
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.
|
|
2512
2869
|
*/
|
|
2513
|
-
async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
2870
|
+
async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message, forkSha }) {
|
|
2514
2871
|
const branchSha = await tryResolveCommit(cwd, `${branch}^{commit}`);
|
|
2515
2872
|
if (!branchSha) return { ok: false, reason: `branch "${branch}" not found` };
|
|
2516
2873
|
|
|
@@ -2529,6 +2886,10 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
|
2529
2886
|
if (oldSha === branchSha) {
|
|
2530
2887
|
return { ok: true, integrated: false, reason: 'branch has no new commits' };
|
|
2531
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
|
+
}
|
|
2532
2893
|
|
|
2533
2894
|
// Retries only when `targetRef` actually moved since `oldSha` was read
|
|
2534
2895
|
// (a real CAS race a fresh attempt can resolve); otherwise the update-ref
|
|
@@ -2567,7 +2928,9 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
|
2567
2928
|
}
|
|
2568
2929
|
}
|
|
2569
2930
|
|
|
2570
|
-
|
|
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) {
|
|
2571
2934
|
const outcome = await updateRefOrClassify([targetRef, branchSha, oldSha]);
|
|
2572
2935
|
if (outcome.retry) return { retry: true };
|
|
2573
2936
|
if (!outcome.ok) return outcome;
|
|
@@ -2580,10 +2943,10 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
|
2580
2943
|
// replay so it rebuilds exactly the commits resolved above. A two-parent
|
|
2581
2944
|
// merge is only the logged fallback for what a replay cannot do.
|
|
2582
2945
|
let linearFallback = '';
|
|
2583
|
-
if (process.env.SM_LINEAR_LANDING_DISABLE === '1') {
|
|
2946
|
+
if (process.env.SM_LINEAR_LANDING_DISABLE === '1' && !baseRewritten) {
|
|
2584
2947
|
linearFallback = 'disabled';
|
|
2585
2948
|
} else {
|
|
2586
|
-
const r = await replayBranchOnto({ cwd, ontoSha: oldSha, branch: branchSha });
|
|
2949
|
+
const r = await replayBranchOnto({ cwd, ontoSha: oldSha, branch: branchSha, sinceSha: fork || undefined });
|
|
2587
2950
|
if (r.ok) {
|
|
2588
2951
|
const outcome = await updateRefOrClassify([targetRef, r.tipSha, oldSha]);
|
|
2589
2952
|
if (outcome.retry) return { retry: true };
|
|
@@ -2593,6 +2956,9 @@ async function attemptIntegrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
|
2593
2956
|
...(r.autoResolved ? { autoResolved: r.autoResolved, resolvedPaths: r.resolvedPaths } : {}),
|
|
2594
2957
|
};
|
|
2595
2958
|
}
|
|
2959
|
+
if (baseRewritten && REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
|
|
2960
|
+
return rewrittenBaseReplayFailure(r, oldSha, { cwd, fork, tip: branchSha });
|
|
2961
|
+
}
|
|
2596
2962
|
if (!REPLAY_MERGE_FALLBACK_KINDS.has(r.failureKind)) {
|
|
2597
2963
|
return { ok: false, failureKind: 'other', reason: r.reason };
|
|
2598
2964
|
}
|
|
@@ -2770,7 +3136,7 @@ async function checkTargetRefNotCheckedOut({ cwd, targetRef }) {
|
|
|
2770
3136
|
* caller landed first) retries the WHOLE computation, up to 3 attempts total,
|
|
2771
3137
|
* before giving up with `failureKind: 'ref_race'`.
|
|
2772
3138
|
*/
|
|
2773
|
-
async function integrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
3139
|
+
async function integrateOntoRef({ cwd, targetRef, branch, message, forkSha }) {
|
|
2774
3140
|
if (!cwd || typeof cwd !== 'string') return { ok: false, reason: 'no cwd provided' };
|
|
2775
3141
|
if (!targetRef || typeof targetRef !== 'string') return { ok: false, reason: 'no targetRef provided' };
|
|
2776
3142
|
if (!branch || typeof branch !== 'string') return { ok: false, reason: 'no branch provided' };
|
|
@@ -2790,7 +3156,7 @@ async function integrateOntoRef({ cwd, targetRef, branch, message }) {
|
|
|
2790
3156
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
2791
3157
|
const guard = await checkTargetRefNotCheckedOut({ cwd, targetRef: normalizedTargetRef });
|
|
2792
3158
|
if (!guard.ok) return guard;
|
|
2793
|
-
const result = await attemptIntegrateOntoRef({ cwd, targetRef: normalizedTargetRef, branch, message: mergeMessage });
|
|
3159
|
+
const result = await attemptIntegrateOntoRef({ cwd, targetRef: normalizedTargetRef, branch, message: mergeMessage, forkSha });
|
|
2794
3160
|
if (!result.retry) return result;
|
|
2795
3161
|
}
|
|
2796
3162
|
return { ok: false, failureKind: 'ref_race' };
|
|
@@ -2866,8 +3232,8 @@ async function ensureLandBranch({ cwd, epicId, baseBranch }) {
|
|
|
2866
3232
|
async function createJobWorktree({ cwd, slug, fromRef }) {
|
|
2867
3233
|
return createWorktree({ kind: 'job', cwd, key: slug, fromRef });
|
|
2868
3234
|
}
|
|
2869
|
-
async function integrateJobBranch({ cwd, branch, slug, carriedPaths, baseBranch, allowRefLanding }) {
|
|
2870
|
-
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 });
|
|
2871
3237
|
}
|
|
2872
3238
|
async function cleanupJobWorktree({ cwd, dir, branch, keepBranch }) {
|
|
2873
3239
|
return cleanupWorktree({ kind: 'job', cwd, dir, branch, keepBranch });
|
|
@@ -2882,8 +3248,8 @@ async function salvageJobDirtyDelta({ cwd, paths, outFile }) {
|
|
|
2882
3248
|
async function createEpicWorktree({ cwd, epicId }) {
|
|
2883
3249
|
return createWorktree({ kind: 'epic', cwd, key: epicId });
|
|
2884
3250
|
}
|
|
2885
|
-
async function integrateEpicBranch({ cwd, branch, epicId, baseBranch }) {
|
|
2886
|
-
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 });
|
|
2887
3253
|
}
|
|
2888
3254
|
async function cleanupEpicWorktree({ cwd, dir, branch, keepBranch }) {
|
|
2889
3255
|
return cleanupWorktree({ kind: 'epic', cwd, dir, branch, keepBranch });
|
|
@@ -2961,6 +3327,46 @@ async function listStrandedPins({ cwd, key, sinceMs }) {
|
|
|
2961
3327
|
}
|
|
2962
3328
|
}
|
|
2963
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
|
+
|
|
2964
3370
|
/** True/false for `git merge-base --is-ancestor a b`; null on a real failure. */
|
|
2965
3371
|
async function isAncestorOf(cwd, a, b) {
|
|
2966
3372
|
try {
|
|
@@ -3076,7 +3482,99 @@ async function pinStrandedHead({ cwd, dir }) {
|
|
|
3076
3482
|
} catch { /* best-effort */ }
|
|
3077
3483
|
}
|
|
3078
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
|
+
|
|
3079
3574
|
module.exports = {
|
|
3575
|
+
snapshotUncommittedWork,
|
|
3576
|
+
worktreeRunCommitCount,
|
|
3577
|
+
findRuntimeStateAdds,
|
|
3080
3578
|
replayBranchOnto,
|
|
3081
3579
|
reconcileWorktreeHead,
|
|
3082
3580
|
pinUnlandedWorktreeCommits,
|
|
@@ -3100,6 +3598,9 @@ module.exports = {
|
|
|
3100
3598
|
getCurrentBranch,
|
|
3101
3599
|
isCarriedWipOnly,
|
|
3102
3600
|
integrateBranch,
|
|
3601
|
+
withCheckoutLock,
|
|
3602
|
+
// Test-only view of the live lock map (entries exist only while busy).
|
|
3603
|
+
_checkoutLocks: checkoutLocks,
|
|
3103
3604
|
cleanupWorktree,
|
|
3104
3605
|
salvageWorktreeDiff,
|
|
3105
3606
|
salvageDirtyDelta,
|
|
@@ -3111,6 +3612,7 @@ module.exports = {
|
|
|
3111
3612
|
reconcileWorktreesOnBoot,
|
|
3112
3613
|
deleteBranchKeepingUniqueCommits,
|
|
3113
3614
|
listStrandedPins,
|
|
3615
|
+
resolveForkSha,
|
|
3114
3616
|
sweepStaleWorktreeCheckouts,
|
|
3115
3617
|
mainTreeFromWorktreeGitFile,
|
|
3116
3618
|
getObservedWorktreeCount,
|