claude-code-session-manager 0.128.0 → 0.130.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 (108) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +2 -0
  3. package/dist/assets/AgentLibrary-ctvNes4y.js +2 -0
  4. package/dist/assets/AppSettings-C03qTDSi.js +2 -0
  5. package/dist/assets/Button-fOCJry21.js +1 -0
  6. package/dist/assets/Extensions-BWiDwigT.js +13 -0
  7. package/dist/assets/{History-4rrDdWNP.js → History-BIQFPXM8.js} +2 -2
  8. package/dist/assets/Library-BGmD-xZN.js +32 -0
  9. package/dist/assets/ListDetail-BeO3lY8t.js +1 -0
  10. package/dist/assets/{Memory-DgQlvQrO.js → Memory-BeXuYIcE.js} +8 -8
  11. package/dist/assets/{Panel-DZHiD8Ar.js → Panel-OUbLHNsS.js} +1 -1
  12. package/dist/assets/ProvenanceBadge-kr7arZqu.js +1 -0
  13. package/dist/assets/Scheduler-DycegnjH.js +16 -0
  14. package/dist/assets/Settings-BSq6VASG.js +2 -0
  15. package/dist/assets/{SkillReferenceGraph-C5lKqf5y.js → SkillReferenceGraph-CvPdxg56.js} +1 -1
  16. package/dist/assets/SourceChip-C2YMnlV8.js +1 -0
  17. package/dist/assets/SystemPrompt-fpXEK_Rm.js +1 -0
  18. package/dist/assets/{TiptapBody-C2Iu6rZd.js → TiptapBody-DusJg0je.js} +1 -1
  19. package/dist/assets/{Toggle-C-oD66BG.js → Toggle-BnJF4V6k.js} +1 -1
  20. package/dist/assets/ViewTabs-BYrRSHb6.js +1 -0
  21. package/dist/assets/VoiceButton-Bk66E-fP.js +1 -0
  22. package/dist/assets/{historyTotals-CbRSLD8f.js → historyTotals-DnuVADtI.js} +1 -1
  23. package/dist/assets/{index-DtdWBGrI.css → index-Bp8XE9A6.css} +1 -1
  24. package/dist/assets/index-DfWJO7nP.js +3086 -0
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +391 -405
  28. package/package.json +1 -1
  29. package/plugins/CLAUDE.md +2 -2
  30. package/plugins/session-manager-dev/.claude-plugin/plugin.json +2 -2
  31. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +2 -2
  32. package/plugins/session-manager-dev/skills/develop/SKILL.md +7 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +62 -0
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +169 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +183 -0
  36. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +39 -0
  37. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +79 -0
  38. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +400 -0
  39. package/scripts/hooks/lib/guard-inline-implementation-policy.cjs +10 -0
  40. package/scripts/scheduler-mcp-server.cjs +25 -6
  41. package/src/main/agentLibrary.cjs +36 -10
  42. package/src/main/build-info.json +4 -4
  43. package/src/main/chatRunner.cjs +8 -0
  44. package/src/main/config.cjs +15 -0
  45. package/src/main/health.cjs +49 -22
  46. package/src/main/index.cjs +32 -3
  47. package/src/main/ipcSchemas.cjs +39 -4
  48. package/src/main/lib/claude/agentModelResolve.cjs +5 -3
  49. package/src/main/lib/claude/effectiveModelInfo.cjs +14 -4
  50. package/src/main/lib/claude/modelCatalog.cjs +26 -15
  51. package/src/main/lib/claudeConfig.cjs +156 -0
  52. package/src/main/lib/effectiveSettings.cjs +120 -0
  53. package/src/main/lib/epic/delegationReadiness.cjs +3 -3
  54. package/src/main/lib/epic/developLoopSpawn.cjs +18 -0
  55. package/src/main/lib/epic/epicMint.cjs +4 -2
  56. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +4 -3
  57. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +21 -21
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +84 -11
  59. package/src/main/lib/git/gitWorktree.cjs +400 -9
  60. package/src/main/lib/git/runtimeStateUntrack.cjs +124 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +8 -2
  62. package/src/main/lib/memoryDirResolve.cjs +2 -8
  63. package/src/main/lib/opsOwnership.cjs +63 -2
  64. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -0
  65. package/src/main/lib/persona-macro/macroLibrary.cjs +34 -6
  66. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  67. package/src/main/lib/prd/prdCreate.cjs +15 -0
  68. package/src/main/lib/promptSessionSchema.cjs +8 -0
  69. package/src/main/lib/updateCheck.cjs +6 -1
  70. package/src/main/pluginInstall.cjs +100 -1
  71. package/src/main/scheduler.cjs +12 -2
  72. package/src/main/seedDevPlugin.cjs +2 -1
  73. package/src/main/templates/PRD_AUTHORING.md +3 -3
  74. package/src/main/updaterIpc.cjs +5 -1
  75. package/src/main/usage.cjs +5 -20
  76. package/src/main/voiceHotkey.cjs +16 -0
  77. package/src/main/voiceSettings.cjs +24 -0
  78. package/src/main/voiceWizard.cjs +27 -36
  79. package/src/preload/api.d.ts +59 -3
  80. package/src/preload/apiSurface.json +70 -7
  81. package/src/preload/index.cjs +17 -1
  82. package/src/seed/agents/architect.md +8 -8
  83. package/src/seed/agents/demo-video-builder.md +2 -2
  84. package/src/seed/agents/validator.md +2 -2
  85. package/dist/assets/AgentLibrary-cNQU5YWy.js +0 -2
  86. package/dist/assets/Button-9dIPAOBg.js +0 -1
  87. package/dist/assets/DataModel-DrDJ6ysw.js +0 -1
  88. package/dist/assets/Hooks-Bj_jF5Pa.js +0 -3
  89. package/dist/assets/Library-D-Wsxrh7.js +0 -46
  90. package/dist/assets/ListDetail-D7Om0H8j.js +0 -1
  91. package/dist/assets/McpServers-CbIbSd5o.js +0 -2
  92. package/dist/assets/Permissions-CfzduF4B.js +0 -3
  93. package/dist/assets/Plugins-D-AG5nAo.js +0 -2
  94. package/dist/assets/ProvenanceBadge-B9JSEjll.js +0 -1
  95. package/dist/assets/SaveBar-mVKig6hL.js +0 -1
  96. package/dist/assets/Scheduler-DFTCnh60.js +0 -16
  97. package/dist/assets/ScopeSwitcher-s8J-yr7Z.js +0 -1
  98. package/dist/assets/Settings-BTmxRMaP.js +0 -4
  99. package/dist/assets/Skills-CxOacq0k.js +0 -2
  100. package/dist/assets/SystemPrompt-BCWg5FAz.js +0 -1
  101. package/dist/assets/TagLibrary-BnF0_PkG.js +0 -1
  102. package/dist/assets/ViewTabs-Cs4v7vLY.js +0 -1
  103. package/dist/assets/index-DzY_GXYY.js +0 -3081
  104. package/dist/assets/listSkills-C1aWKf0T.js +0 -1
  105. package/dist/assets/settingsSchema-bSBfHuan.js +0 -1
  106. package/dist/assets/skillFrontmatter-BEseWm8r.js +0 -10
  107. package/dist/assets/useAgentsDirWatch-CdyHxKCI.js +0 -1
  108. package/src/main/lib/epic/epicStandingInstructions.cjs +0 -73
@@ -53,7 +53,10 @@ const fsp = require('node:fs/promises');
53
53
  const path = require('node:path');
54
54
  const os = require('node:os');
55
55
  const crypto = require('node:crypto');
56
- const { OPS_ROOT_DIR } = require('../opsOwnership.cjs');
56
+ const { OPS_ROOT_DIR, RUNTIME_NAMESPACES } = require('../opsOwnership.cjs');
57
+
58
+ // Runtime ops state is live data owned by the main checkout, never carried WIP.
59
+ const RUNTIME_CARRY_EXCLUDES = RUNTIME_NAMESPACES.map((ns) => `:(exclude)${OPS_ROOT_DIR}/${ns}`);
57
60
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
58
61
  const sharedGitExec = require('./gitExec.cjs');
59
62
 
@@ -560,7 +563,7 @@ async function sweepStaleWorktreeCheckouts(kind, opts = {}) {
560
563
  async function captureAndCarryBaseDiff({ cwd, dir }) {
561
564
  let paths = [];
562
565
  try {
563
- const nameOut = await execGit(['diff', 'HEAD', '--name-only'], { cwd, timeout: 15_000 });
566
+ const nameOut = await execGit(['diff', 'HEAD', '--name-only', '--', '.', ...RUNTIME_CARRY_EXCLUDES], { cwd, timeout: 15_000 });
564
567
  paths = nameOut.split('\n').map((l) => l.trim()).filter(Boolean);
565
568
  } catch (e) {
566
569
  return { ok: false, reason: `listing changed paths failed: ${(e && (e.stderrText || e.message)) || e}` };
@@ -573,7 +576,7 @@ async function captureAndCarryBaseDiff({ cwd, dir }) {
573
576
  const patchFile = path.join(dir, `.sm-worktree-carry-${crypto.randomBytes(8).toString('hex')}.patch`);
574
577
  try {
575
578
  try {
576
- await execGit(['diff', 'HEAD', '--binary', `--output=${patchFile}`], { cwd, timeout: 120_000 });
579
+ await execGit(['diff', 'HEAD', '--binary', `--output=${patchFile}`, '--', '.', ...RUNTIME_CARRY_EXCLUDES], { cwd, timeout: 120_000 });
577
580
  } catch (e) {
578
581
  return { ok: false, reason: `capturing base diff failed: ${(e && (e.stderrText || e.message)) || e}` };
579
582
  }
@@ -794,6 +797,22 @@ async function reserveWorktreeSlot(kind) {
794
797
  });
795
798
  }
796
799
 
800
+ /**
801
+ * True when `dir` is a registered worktree of `cwd`'s repo checked out on
802
+ * `branch` (bare name, no refs/heads/). Any error → false, so callers fall
803
+ * back to the destructive-leftover path they had before.
804
+ */
805
+ async function isRegisteredWorktreeOnBranch(cwd, dir, branch) {
806
+ try {
807
+ const out = await execGit(['worktree', 'list', '--porcelain'], { cwd, timeout: 15_000 });
808
+ const real = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
809
+ const want = real(dir);
810
+ return parseWorktreeListPorcelain(out).some((e) => e.worktree && e.branch === branch && real(e.worktree) === want);
811
+ } catch {
812
+ return false;
813
+ }
814
+ }
815
+
797
816
  /**
798
817
  * Create a linked worktree on a fresh branch checked out from the main
799
818
  * tree's current HEAD. Returns `{ ok: true, dir, branch, baseCwd,
@@ -859,6 +878,18 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
859
878
  resolvedFromRefSha = await tryResolveCommit(cwd, `${fromRef}^{commit}`);
860
879
  }
861
880
 
881
+ // Epic mint is idempotent: a live Epic checkout (registered on its own
882
+ // branch) is returned untouched — the leftover teardown below would delete
883
+ // a running session's worktree. Runs before the slot reservation so a
884
+ // reuse never changes the epic count.
885
+ if (kind === 'epic') {
886
+ const epicDir = worktreeDirFor(kind, cwd, key);
887
+ const epicBranch = branchNameFor(kind, key);
888
+ if (fs.existsSync(epicDir) && await isRegisteredWorktreeOnBranch(cwd, epicDir, epicBranch)) {
889
+ return { ok: true, dir: epicDir, branch: epicBranch, baseCwd: cwd, reused: true };
890
+ }
891
+ }
892
+
862
893
  // Cap check + slot reservation as a single atomic step, per kind — see
863
894
  // reserveWorktreeSlot's header. Released again below on any failure path
864
895
  // so a failed create never permanently shrinks capacity.
@@ -1199,6 +1230,85 @@ function joinSegments(segments) {
1199
1230
  return out.join('\n');
1200
1231
  }
1201
1232
 
1233
+ /**
1234
+ * Blob-spec sibling of renderStagesDiff3: renders `git merge-file -p --diff3`
1235
+ * over three blob specs (`<rev>:<path>`), reading only objects — no index or
1236
+ * working tree. Returns null when any blob is missing, not valid UTF-8, or git
1237
+ * errors. Never throws.
1238
+ */
1239
+ async function renderBlobsDiff3({ cwd, oursSpec, baseSpec, theirsSpec }) {
1240
+ let tmp = null;
1241
+ try {
1242
+ tmp = await fsp.mkdtemp(path.join(os.tmpdir(), 'sm-mergefile-'));
1243
+ const files = [];
1244
+ let i = 0;
1245
+ for (const spec of [oursSpec, baseSpec, theirsSpec]) { // merge-file's argument order
1246
+ const content = await execGit(['cat-file', 'blob', spec], { cwd, timeout: 10_000 });
1247
+ if (content.includes('\uFFFD')) return null;
1248
+ const f = path.join(tmp, `blob${i++}`);
1249
+ await fsp.writeFile(f, content, 'utf8');
1250
+ files.push(f);
1251
+ }
1252
+ try {
1253
+ return await execGit(['merge-file', '-p', '--diff3', '-L', 'ours', '-L', 'base', '-L', 'theirs', ...files], { cwd, timeout: 10_000 });
1254
+ } catch (e) {
1255
+ if (e && typeof e.code === 'number' && e.code >= 1 && e.code <= 127 && typeof e.stdoutText === 'string') return e.stdoutText;
1256
+ return null;
1257
+ }
1258
+ } catch {
1259
+ return null;
1260
+ } finally {
1261
+ if (tmp) { try { await fsp.rm(tmp, { recursive: true, force: true }); } catch { /* best effort */ } }
1262
+ }
1263
+ }
1264
+
1265
+ /**
1266
+ * Replay-side pure-addition resolution. `treeOid` is the merge-tree result
1267
+ * (conflict markers in the conflicted paths). When every path is an
1268
+ * AUTO_RESOLVE_EXTENSIONS file whose diff3 hunks all have an empty base,
1269
+ * builds a tree with each path replaced by ours+theirs concatenation (same rule
1270
+ * as resolveByConcatenation). Only writes objects plus a temp index under
1271
+ * os.tmpdir(), always removed. Returns the resolved tree oid, or null on any
1272
+ * doubt/error. Never throws.
1273
+ */
1274
+ async function resolvePureAdditionInTree({ cwd, treeOid, paths, parent, tip, commit }) {
1275
+ if (process.env.SM_PURE_ADDITION_MERGE_DISABLE === '1') return null;
1276
+ if (!Array.isArray(paths) || !paths.length) return null;
1277
+ if (!paths.every((p) => AUTO_RESOLVE_EXTENSIONS.has(path.extname(p).toLowerCase()))) return null;
1278
+ let tmp = null;
1279
+ try {
1280
+ const rendered = [];
1281
+ for (const p of paths) {
1282
+ if (p.startsWith('"')) return null; // git-quoted path: don't guess
1283
+ const out = await renderBlobsDiff3({ cwd, baseSpec: `${parent}:${p}`, oursSpec: `${tip}:${p}`, theirsSpec: `${commit}:${p}` });
1284
+ if (out === null) return null;
1285
+ const segments = parseDiff3Output(out);
1286
+ if (!segments) return null;
1287
+ const hunks = segments.filter((s) => s.hunk);
1288
+ if (!hunks.length || hunks.some((s) => s.hunk.base.length !== 0)) return null;
1289
+ rendered.push({ p, text: joinSegments(segments) });
1290
+ }
1291
+ tmp = await fsp.mkdtemp(path.join(os.tmpdir(), 'sm-replay-idx-'));
1292
+ const env = { GIT_INDEX_FILE: path.join(tmp, 'index') };
1293
+ await execGit(['read-tree', treeOid], { cwd, timeout: 15_000, env });
1294
+ let n = 0;
1295
+ for (const { p, text } of rendered) {
1296
+ const f = path.join(tmp, `res${n++}`);
1297
+ await fsp.writeFile(f, text, 'utf8');
1298
+ const blob = (await execGit(['hash-object', '-w', f], { cwd, timeout: 10_000 })).trim();
1299
+ const lsOut = await execGit(['ls-tree', '-z', tip, '--', p], { cwd, timeout: 10_000 });
1300
+ const mode = (lsOut.split(' ')[0] || '').trim();
1301
+ await execGit(['update-index', '--add', '--cacheinfo', `${/^100(644|755)$/.test(mode) ? mode : '100644'},${blob},${p}`], { cwd, timeout: 10_000, env });
1302
+ }
1303
+ const resolved = (await execGit(['write-tree'], { cwd, timeout: 15_000, env })).trim();
1304
+ return /^[0-9a-f]{40,64}$/.test(resolved) ? resolved : null;
1305
+ } catch {
1306
+ return null;
1307
+ } finally {
1308
+ if (tmp) { try { await fsp.rm(tmp, { recursive: true, force: true }); } catch { /* best effort */ } }
1309
+ }
1310
+ }
1311
+
1202
1312
  /**
1203
1313
  * Resolves `cwd`'s default branch, without ever hardcoding `main`: prefers
1204
1314
  * the remote-tracked default (`origin/HEAD`, set by `git clone`/`git remote
@@ -1474,18 +1584,96 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1474
1584
  return { ok: true, integrated: false, reason: 'carried-wip-only' };
1475
1585
  }
1476
1586
 
1587
+ const clobber = await findIgnoredLivePaths({ cwd, branch, mergeBase });
1588
+ if (clobber.length) {
1589
+ return {
1590
+ ok: false,
1591
+ reason: `refusing to integrate: branch touches ignored path(s) that exist on disk in the main checkout: ${clobber.join(', ')}`,
1592
+ failureKind: 'other',
1593
+ ignoredLivePaths: clobber,
1594
+ baseHeadSha: await readHeadSha(cwd),
1595
+ };
1596
+ }
1477
1597
  try {
1478
- await execGit(['merge', '--ff-only', branch], { cwd, timeout: 30_000 });
1598
+ await execGit(['merge', '--ff-only', '--no-overwrite-ignore', branch], { cwd, timeout: 30_000 });
1479
1599
  // The branch tip we fast-forwarded to, read from the branch ref (not HEAD,
1480
1600
  // which a concurrent writer may already have moved).
1481
1601
  return { ok: true, integrated: true, fastForward: true, sha: await tryResolveCommit(cwd, `${branch}^{commit}`) };
1482
1602
  } catch {
1483
1603
  // Main tree advanced since the worktree branched (a sibling job/Epic
1484
- // merged first) — a real merge commit still lands the branch's commit(s).
1604
+ // merged first) — replay the branch linearly onto HEAD; a merge commit is
1605
+ // only the documented fallback.
1606
+ }
1607
+ let linearFallback = '';
1608
+ if (process.env.SM_LINEAR_LANDING_DISABLE === '1') {
1609
+ linearFallback = 'disabled';
1610
+ } else {
1611
+ const MAX_LINEAR_ATTEMPTS = 3;
1612
+ let landed = null;
1613
+ for (let attempt = 0; attempt < MAX_LINEAR_ATTEMPTS; attempt++) {
1614
+ const headSha = await readHeadSha(cwd);
1615
+ const r = await replayBranchOnto({ cwd, ontoSha: headSha, branch: branchHead });
1616
+ if (!r.ok) {
1617
+ if (r.failureKind === 'git_too_old' || r.failureKind === 'content_conflict') {
1618
+ linearFallback = r.failureKind;
1619
+ break;
1620
+ }
1621
+ return { ok: false, reason: r.reason, failureKind: 'other', baseHeadSha: headSha };
1622
+ }
1623
+ const success = {
1624
+ ok: true, integrated: true, linear: true, sha: r.tipSha, replayedCommits: r.replayed.length,
1625
+ ...(r.autoResolved ? { autoResolved: r.autoResolved, resolvedPaths: r.resolvedPaths } : {}),
1626
+ };
1627
+ try {
1628
+ await execGit(['merge', '--ff-only', '--no-overwrite-ignore', r.tipSha], { cwd, timeout: 30_000 });
1629
+ landed = success;
1630
+ break;
1631
+ } catch (ffErr) {
1632
+ if ((await readHeadSha(cwd)) !== headSha) continue; // base moved — replay again
1633
+ const ffText = (ffErr && (ffErr.stderrText || ffErr.message)) || String(ffErr);
1634
+ const blocking = parseBlockingMergePaths(ffText);
1635
+ if (!blocking) {
1636
+ return { ok: false, reason: `linear landing failed: ${ffText}`, failureKind: 'other', baseHeadSha: headSha };
1637
+ }
1638
+ const allPaths = [...blocking.tracked, ...blocking.untracked];
1639
+ const ignoredBlock = await filterIgnoredPaths({ cwd, paths: allPaths });
1640
+ if (ignoredBlock.length) {
1641
+ return {
1642
+ ok: false,
1643
+ reason: `merge blocked: refusing to delete git-ignored path(s) in the main checkout: ${ignoredBlock.join(', ')}`,
1644
+ failureKind: 'other',
1645
+ ignoredLivePaths: ignoredBlock,
1646
+ baseHeadSha: headSha,
1647
+ };
1648
+ }
1649
+ if (!(await pathsIdenticalToBranch({ cwd, branch: r.tipSha, paths: allPaths }))) {
1650
+ return { ok: false, reason: `linear landing failed: ${ffText}`, failureKind: 'other', baseHeadSha: headSha };
1651
+ }
1652
+ try {
1653
+ if (blocking.tracked.length) {
1654
+ await execGit(['checkout', '--', ...blocking.tracked], { cwd, timeout: 30_000 });
1655
+ }
1656
+ for (const p of blocking.untracked) {
1657
+ await fsp.rm(path.join(cwd, p), { force: true });
1658
+ }
1659
+ await execGit(['merge', '--ff-only', '--no-overwrite-ignore', r.tipSha], { cwd, timeout: 30_000 });
1660
+ landed = { ...success, autoResolved: 'identical_working_tree_duplicates', resolvedPaths: allPaths };
1661
+ break;
1662
+ } catch (retryErr) {
1663
+ if ((await readHeadSha(cwd)) !== headSha) continue;
1664
+ const retryText = (retryErr && (retryErr.stderrText || retryErr.message)) || String(retryErr);
1665
+ return { ok: false, reason: `linear landing failed: ${retryText}`, failureKind: 'other', baseHeadSha: headSha };
1666
+ }
1667
+ }
1668
+ }
1669
+ if (landed) return landed;
1670
+ if (!linearFallback) linearFallback = 'ref_race';
1485
1671
  }
1672
+ console.warn(`[gitWorktree] linear landing of ${branch} fell back to a merge commit (${linearFallback})`);
1673
+ const fb = { linearFallback };
1486
1674
  try {
1487
- await execGit(['merge', '--no-ff', '--no-edit', '-m', mergeMessage, branch], { cwd, timeout: 30_000 });
1488
- return { ok: true, integrated: true, mergeCommit: true, sha: await readHeadSha(cwd) };
1675
+ await execGit(['merge', '--no-ff', '--no-overwrite-ignore', '--no-edit', '-m', mergeMessage, branch], { cwd, timeout: 30_000 });
1676
+ return { ok: true, integrated: true, mergeCommit: true, sha: await readHeadSha(cwd), ...fb };
1489
1677
  } catch (e) {
1490
1678
  const stderrText = (e && (e.stderrText || e.message)) || String(e);
1491
1679
  // git refuses this class of merge before ever touching MERGE_HEAD, so
@@ -1494,6 +1682,16 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1494
1682
  const blocking = parseBlockingMergePaths(stderrText);
1495
1683
  if (blocking) {
1496
1684
  const allPaths = [...blocking.tracked, ...blocking.untracked];
1685
+ const ignoredBlock = await filterIgnoredPaths({ cwd, paths: allPaths });
1686
+ if (ignoredBlock.length) {
1687
+ return {
1688
+ ok: false,
1689
+ reason: `merge blocked: refusing to delete git-ignored path(s) in the main checkout: ${ignoredBlock.join(', ')}`,
1690
+ failureKind: 'other',
1691
+ ignoredLivePaths: ignoredBlock,
1692
+ baseHeadSha: await readHeadSha(cwd),
1693
+ };
1694
+ }
1497
1695
  const identical = await pathsIdenticalToBranch({ cwd, branch, paths: allPaths });
1498
1696
  if (identical) {
1499
1697
  try {
@@ -1503,7 +1701,7 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1503
1701
  for (const p of blocking.untracked) {
1504
1702
  await fsp.rm(path.join(cwd, p), { force: true });
1505
1703
  }
1506
- await execGit(['merge', '--no-ff', '--no-edit', '-m', mergeMessage, branch], { cwd, timeout: 30_000 });
1704
+ await execGit(['merge', '--no-ff', '--no-overwrite-ignore', '--no-edit', '-m', mergeMessage, branch], { cwd, timeout: 30_000 });
1507
1705
  return {
1508
1706
  ok: true,
1509
1707
  integrated: true,
@@ -1511,6 +1709,7 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1511
1709
  sha: await readHeadSha(cwd),
1512
1710
  autoResolved: 'identical_working_tree_duplicates',
1513
1711
  resolvedPaths: allPaths,
1712
+ ...fb,
1514
1713
  };
1515
1714
  } catch (retryErr) {
1516
1715
  const retryText = (retryErr && (retryErr.stderrText || retryErr.message)) || String(retryErr);
@@ -1536,7 +1735,7 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1536
1735
  await resolveByConcatenation({ cwd, paths });
1537
1736
  await execGit(['add', ...paths], { cwd, timeout: 30_000 });
1538
1737
  await execGit(['commit', '-m', mergeMessage], { cwd, timeout: 30_000 });
1539
- return { ok: true, integrated: true, mergeCommit: true, sha: await readHeadSha(cwd), autoResolved: 'pure_addition_concat', resolvedPaths: paths };
1738
+ return { ok: true, integrated: true, mergeCommit: true, sha: await readHeadSha(cwd), autoResolved: 'pure_addition_concat', resolvedPaths: paths, ...fb };
1540
1739
  }
1541
1740
  } catch (autoErr) {
1542
1741
  const autoText = [autoErr && autoErr.stderrText, autoErr && autoErr.stdoutText, autoErr && autoErr.message].filter(Boolean).join('\n');
@@ -1553,6 +1752,53 @@ async function integrateBranch({ cwd, branch, key, kind, carriedPaths, baseBranc
1553
1752
  }
1554
1753
  }
1555
1754
 
1755
+ /**
1756
+ * Subset of `paths` that `git check-ignore` reports ignored in `cwd` (tracked
1757
+ * paths are never reported). Fails closed: a git error returns every path.
1758
+ * @param {{cwd: string, paths: string[]}} a
1759
+ * @returns {Promise<string[]>}
1760
+ */
1761
+ async function filterIgnoredPaths({ cwd, paths }) {
1762
+ if (!paths.length) return [];
1763
+ try {
1764
+ const out = await new Promise((resolve, reject) => {
1765
+ const cp = require('node:child_process').spawn('git', ['check-ignore', '-z', '--stdin'], { cwd });
1766
+ let buf = '';
1767
+ cp.stdout.on('data', (d) => { buf += d; });
1768
+ cp.on('error', reject);
1769
+ cp.on('close', (code) => (code === 0 || code === 1 ? resolve(buf) : reject(new Error(`check-ignore exit ${code}`))));
1770
+ cp.stdin.on('error', () => {});
1771
+ cp.stdin.end(paths.join('\0') + '\0');
1772
+ });
1773
+ return out.split('\0').filter(Boolean);
1774
+ } catch {
1775
+ return paths.slice();
1776
+ }
1777
+ }
1778
+
1779
+ /**
1780
+ * Paths the branch changed since the merge base that are git-ignored AND
1781
+ * present on disk in `cwd` — the live files a merge would overwrite (git's
1782
+ * default --overwrite-ignore) or a later `merge --abort` would delete.
1783
+ * @param {{cwd: string, branch: string, mergeBase: string}} a
1784
+ * @returns {Promise<string[]>}
1785
+ */
1786
+ async function findIgnoredLivePaths({ cwd, branch, mergeBase }) {
1787
+ let changed;
1788
+ try {
1789
+ const out = await execGit(['diff', '--name-only', '-z', `${mergeBase || 'HEAD'}..${branch}`], { cwd, timeout: 15_000 });
1790
+ changed = out.split('\0').filter(Boolean);
1791
+ } catch {
1792
+ return [];
1793
+ }
1794
+ const ignored = await filterIgnoredPaths({ cwd, paths: changed });
1795
+ const live = [];
1796
+ for (const p of ignored) {
1797
+ try { await fsp.lstat(path.join(cwd, p)); live.push(p); } catch { /* absent — safe */ }
1798
+ }
1799
+ return live;
1800
+ }
1801
+
1556
1802
  /**
1557
1803
  * Tear down one worktree checkout after it has been integrated (or failed to
1558
1804
  * integrate). Always removes the linked-worktree checkout (freeing its
@@ -1973,6 +2219,150 @@ async function runMergeTreeWriteTree({ cwd, oldSha, branchSha }) {
1973
2219
  }
1974
2220
  }
1975
2221
 
2222
+ const REPLAY_MAX_COMMITS = 200;
2223
+
2224
+ /**
2225
+ * Checkout-free linear replay: rebuilds `branch`'s non-merge commits on top of
2226
+ * `ontoSha` purely in the object database (`git merge-tree --write-tree` +
2227
+ * `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.
2232
+ *
2233
+ * Original author name/email/date and the full message are preserved; commits
2234
+ * 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.
2236
+ * Needs git >= 2.40 (`merge-tree --merge-base`). Never throws.
2237
+ *
2238
+ * @returns {Promise<{ok:true, tipSha:string, replayed:{from:string,to:string}[], skipped:string[], fastForward?:true}
2239
+ * | {ok:false, failureKind:string, reason:string, conflictedPaths?:string[]}>}
2240
+ */
2241
+ async function replayBranchOnto({ cwd, ontoSha, branch }) {
2242
+ try {
2243
+ // Resolve once; from here on only SHAs reach git, so a branch named like an
2244
+ // option ('-x') can never be read as one (same reason as runMergeTreeWriteTree).
2245
+ const onto = await tryResolveCommit(cwd, `${ontoSha}^{commit}`);
2246
+ if (!onto) return { ok: false, failureKind: 'other', reason: `ontoSha "${ontoSha}" not found` };
2247
+ // A name starting with '-' would be read as an option by rev-parse; try the
2248
+ // fully-qualified ref first for those.
2249
+ const tipIn = (String(branch).startsWith('-') ? null : await tryResolveCommit(cwd, `${branch}^{commit}`))
2250
+ || await tryResolveCommit(cwd, `refs/heads/${branch}^{commit}`);
2251
+ if (!tipIn) return { ok: false, failureKind: 'other', reason: `branch "${branch}" not found` };
2252
+
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}` };
2259
+ }
2260
+ }
2261
+
2262
+ const lines = async (extra) => (await execGit(
2263
+ ['rev-list', '--reverse', '--topo-order', '--no-merges', ...extra, '--right-only', `${onto}...${tipIn}`],
2264
+ { cwd, timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
2265
+ )).split('\n').map((l) => l.trim()).filter(Boolean);
2266
+ const kept = await lines(['--cherry-pick']);
2267
+ const all = await lines([]);
2268
+ const keptSet = new Set(kept);
2269
+ const skipped = all.filter((c) => !keptSet.has(c));
2270
+ if (kept.length > REPLAY_MAX_COMMITS) {
2271
+ return { ok: false, failureKind: 'other', reason: `refusing to replay ${kept.length} commits (limit ${REPLAY_MAX_COMMITS})` };
2272
+ }
2273
+
2274
+ let tip = onto;
2275
+ const replayed = [];
2276
+ let autoResolved = null;
2277
+ const resolvedSet = new Set();
2278
+ for (const c of kept) {
2279
+ let parent;
2280
+ try {
2281
+ parent = (await execGit(['rev-parse', '--verify', `${c}^1`], { cwd, timeout: 10_000 })).trim();
2282
+ } catch {
2283
+ return { ok: false, failureKind: 'other', reason: `commit ${c} has no parent to replay from` };
2284
+ }
2285
+ let treeOid;
2286
+ let conflictResolved = false;
2287
+ try {
2288
+ const out = await execGit(
2289
+ ['merge-tree', '--write-tree', '--name-only', '--no-messages', `--merge-base=${parent}`, tip, c],
2290
+ { cwd, timeout: 30_000 },
2291
+ );
2292
+ treeOid = (out.split('\n')[0] || '').trim();
2293
+ } catch (e) {
2294
+ const stderrText = (e && e.stderrText) || '';
2295
+ const stdoutText = (e && e.stdoutText) || '';
2296
+ if (e && e.code === 1 && !/unknown option|usage:/i.test(stderrText)) {
2297
+ const conflictedPaths = Array.from(new Set(
2298
+ stdoutText.split('\n').slice(1).map((l) => l.trim()).filter(Boolean),
2299
+ )).sort();
2300
+ const resolvedTree = await resolvePureAdditionInTree({ cwd, treeOid: (stdoutText.split('\n')[0] || '').trim(), paths: conflictedPaths, parent, tip, commit: c });
2301
+ if (resolvedTree) {
2302
+ treeOid = resolvedTree;
2303
+ autoResolved = 'pure_addition_concat';
2304
+ for (const p of conflictedPaths) resolvedSet.add(p);
2305
+ conflictResolved = true;
2306
+ } else {
2307
+ return {
2308
+ ok: false,
2309
+ failureKind: 'content_conflict',
2310
+ conflictedPaths,
2311
+ reason: `replay of ${c} conflicts on: ${conflictedPaths.join(', ')}`,
2312
+ };
2313
+ }
2314
+ }
2315
+ if (!conflictResolved) {
2316
+ if ((e && e.code === 129) || /unknown option|usage:/i.test(stderrText)) {
2317
+ return {
2318
+ ok: false,
2319
+ failureKind: 'git_too_old',
2320
+ reason: `git merge-tree --merge-base is unsupported by this git (need >= 2.40): ${stderrText || (e && e.message)}`,
2321
+ };
2322
+ }
2323
+ return { ok: false, failureKind: 'other', reason: `git merge-tree failed: ${stderrText || (e && e.message)}` };
2324
+ }
2325
+ }
2326
+
2327
+ const tipTree = (await execGit(['rev-parse', `${tip}^{tree}`], { cwd, timeout: 10_000 })).trim();
2328
+ if (treeOid === tipTree) {
2329
+ skipped.push(c);
2330
+ continue;
2331
+ }
2332
+
2333
+ const meta = (await execGit(['log', '-1', '--format=%an%x00%ae%x00%aI%x00%B', c], { cwd, timeout: 10_000 })).split('\0');
2334
+ const [an, ae, ad] = meta;
2335
+ const message = meta.slice(3).join('\0').replace(/\n+$/, '');
2336
+ const env = { GIT_AUTHOR_NAME: an, GIT_AUTHOR_EMAIL: ae, GIT_AUTHOR_DATE: ad };
2337
+ const commitTreeArgs = ['commit-tree', treeOid, '-p', tip, '-m', message];
2338
+ let newSha;
2339
+ try {
2340
+ newSha = (await execGit(commitTreeArgs, { cwd, timeout: 15_000, env })).trim();
2341
+ } catch (e) {
2342
+ const stderrText = (e && (e.stderrText || e.message)) || String(e);
2343
+ if (!/Please tell me who you are/i.test(stderrText)) {
2344
+ return { ok: false, failureKind: 'other', reason: `git commit-tree failed: ${stderrText}` };
2345
+ }
2346
+ try {
2347
+ newSha = (await execGit(
2348
+ ['-c', 'user.name=Session Manager Scheduler', '-c', 'user.email=scheduler@session-manager.local', ...commitTreeArgs],
2349
+ { cwd, timeout: 15_000, env },
2350
+ )).trim();
2351
+ } catch (e2) {
2352
+ return { ok: false, failureKind: 'other', reason: `git commit-tree failed: ${(e2 && (e2.stderrText || e2.message)) || e2}` };
2353
+ }
2354
+ }
2355
+ replayed.push({ from: c, to: newSha });
2356
+ tip = newSha;
2357
+ }
2358
+ const result = { ok: true, tipSha: tip, replayed, skipped };
2359
+ if (autoResolved) { result.autoResolved = autoResolved; result.resolvedPaths = Array.from(resolvedSet).sort(); }
2360
+ return result;
2361
+ } catch (e) {
2362
+ return { ok: false, failureKind: 'other', reason: `replayBranchOnto failed: ${(e && (e.stderrText || e.message)) || e}` };
2363
+ }
2364
+ }
2365
+
1976
2366
  /**
1977
2367
  * One computation attempt for `integrateOntoRef` — resolves both tips fresh,
1978
2368
  * decides ff vs merge-commit vs no-op, and lands the result via a
@@ -2515,6 +2905,7 @@ async function pinStrandedHead({ cwd, dir }) {
2515
2905
  }
2516
2906
 
2517
2907
  module.exports = {
2908
+ replayBranchOnto,
2518
2909
  reconcileWorktreeHead,
2519
2910
  pinUnlandedWorktreeCommits,
2520
2911
  resolveDefaultBranch,
@@ -0,0 +1,124 @@
1
+ /**
2
+ * runtimeStateUntrack.cjs — find and safely untrack Session Manager runtime
3
+ * state that a project accidentally committed.
4
+ *
5
+ * Why the preconditions: `git rm --cached` committed in a linked worktree and
6
+ * then merged deletes the LIVE files in the main checkout. So the untrack runs
7
+ * only from the project's MAIN checkout, on the default branch, with a clean
8
+ * index, no in-flight merge/rebase/cherry-pick, and no running job.
9
+ *
10
+ * Never edits the root .gitignore: each runtime namespace carries its own
11
+ * self-ignore file (opsOwnership.ensureRuntimeIgnores). Not wired to any UI or
12
+ * MCP route — surface it in a follow-up.
13
+ */
14
+ 'use strict';
15
+
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+ const { execGit } = require('./gitExec.cjs');
19
+ const { RUNTIME_NAMESPACES, OPS_ROOT_DIR } = require('../opsOwnership.cjs');
20
+
21
+ const ATTRIBUTION = 'Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>';
22
+ const RM_BATCH = 200;
23
+
24
+ const nsPathspecs = () => RUNTIME_NAMESPACES.map((ns) => `${OPS_ROOT_DIR}/${ns}`);
25
+
26
+ /** Tracked paths (repo-relative, posix) under runtime namespaces, README.md excluded. */
27
+ async function findTrackedRuntimeState(projectRoot) {
28
+ let out;
29
+ try {
30
+ out = await execGit(projectRoot, ['ls-files', '-z', '--', ...nsPathspecs()], { maxBuffer: 64 * 1024 * 1024 });
31
+ } catch {
32
+ return [];
33
+ }
34
+ return out.split('\0').filter((p) => p && path.posix.basename(p) !== 'README.md');
35
+ }
36
+
37
+ /** Sorted list of every file on disk under the runtime namespaces. */
38
+ function listRuntimeFilesOnDisk(projectRoot) {
39
+ const found = [];
40
+ const walk = (abs, rel) => {
41
+ let entries;
42
+ try { entries = fs.readdirSync(abs, { withFileTypes: true }); } catch { return; }
43
+ for (const e of entries) {
44
+ const r = `${rel}/${e.name}`;
45
+ if (e.isDirectory()) walk(path.join(abs, e.name), r);
46
+ else found.push(r);
47
+ }
48
+ };
49
+ for (const ns of RUNTIME_NAMESPACES) {
50
+ walk(path.join(projectRoot, OPS_ROOT_DIR, ns), `${OPS_ROOT_DIR}/${ns}`);
51
+ }
52
+ return found.sort();
53
+ }
54
+
55
+ async function git(cwd, args) {
56
+ return (await execGit(cwd, args)).trim();
57
+ }
58
+
59
+ async function defaultBranchOf(cwd) {
60
+ try {
61
+ const ref = await git(cwd, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
62
+ if (ref) return ref.replace(/^origin\//, '');
63
+ } catch { /* no remote HEAD */ }
64
+ for (const b of ['main', 'master']) {
65
+ try {
66
+ await git(cwd, ['rev-parse', '--verify', '--quiet', `refs/heads/${b}`]);
67
+ return b;
68
+ } catch { /* try next */ }
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /**
74
+ * untrackRuntimeState(projectRoot, opts) → { ok, reason?, removed?, committed? }
75
+ * opts: { isProjectBusy: () => boolean|Promise<boolean> (required),
76
+ * defaultBranch?: string }
77
+ * On refusal nothing is touched.
78
+ */
79
+ async function untrackRuntimeState(projectRoot, opts = {}) {
80
+ const refuse = (reason) => ({ ok: false, reason });
81
+ try {
82
+ const gitDir = path.resolve(projectRoot, await git(projectRoot, ['rev-parse', '--git-dir']));
83
+ const commonDir = path.resolve(projectRoot, await git(projectRoot, ['rev-parse', '--git-common-dir']));
84
+ if (gitDir !== commonDir) return refuse('projectRoot is a linked worktree; run from the main checkout');
85
+
86
+ const branch = await git(projectRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
87
+ const def = opts.defaultBranch || await defaultBranchOf(projectRoot);
88
+ if (!def) return refuse('cannot determine the default branch');
89
+ if (branch !== def) return refuse(`HEAD is on '${branch}', not the default branch '${def}'`);
90
+
91
+ for (const marker of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply']) {
92
+ if (fs.existsSync(path.join(gitDir, marker))) {
93
+ return refuse(`a merge, rebase or cherry-pick is in progress (${marker})`);
94
+ }
95
+ }
96
+
97
+ if ((await git(projectRoot, ['diff', '--cached', '--name-only'])) !== '') {
98
+ return refuse('the index already has staged changes');
99
+ }
100
+
101
+ if (typeof opts.isProjectBusy !== 'function') return refuse('opts.isProjectBusy is required');
102
+ if (await opts.isProjectBusy()) return refuse('a job is running for this project');
103
+
104
+ const tracked = await findTrackedRuntimeState(projectRoot);
105
+ if (tracked.length === 0) return { ok: true, removed: 0, committed: false };
106
+
107
+ const before = listRuntimeFilesOnDisk(projectRoot);
108
+ for (let i = 0; i < tracked.length; i += RM_BATCH) {
109
+ await execGit(projectRoot, ['rm', '-r', '--cached', '-q', '--', ...tracked.slice(i, i + RM_BATCH)], { timeout: 120_000 });
110
+ }
111
+ const msg = `chore(ops): untrack Session Manager runtime state (${tracked.length} files)\n\n${ATTRIBUTION}`;
112
+ await execGit(projectRoot, ['commit', '-m', msg], { timeout: 60_000 });
113
+
114
+ const after = listRuntimeFilesOnDisk(projectRoot);
115
+ if (before.length !== after.length || before.some((f, i) => f !== after[i])) {
116
+ return { ok: false, reason: 'on-disk runtime file list changed across the untrack', removed: tracked.length, committed: true };
117
+ }
118
+ return { ok: true, removed: tracked.length, committed: true };
119
+ } catch (err) {
120
+ return refuse(`git failed: ${(err && (err.stderrText || err.message)) || err}`);
121
+ }
122
+ }
123
+
124
+ module.exports = { findTrackedRuntimeState, untrackRuntimeState, listRuntimeFilesOnDisk };
@@ -434,7 +434,8 @@ const MCP_TOOL_CATALOG = [
434
434
  name: 'macro_list',
435
435
  group: 'macros',
436
436
  purpose: "List this project's HOT KEYS macros — the saved (agent, tag, prompt) one-click buttons shown "
437
- + "in the Sessions tab's HOT KEYS strip, via the session-manager app's admin API.",
437
+ + "in the Sessions tab's HOT KEYS strip or the Project Home button row, via the session-manager app's admin API. "
438
+ + "Each macro's `surface` tells where it shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row.",
438
439
  whenToUse: 'Use to see what macros already exist for this project (including machine-wide `*` macros and '
439
440
  + 'built-ins) before deciding whether to add, update or delete one.',
440
441
  whenNotToUse: 'WHEN NOT TO USE IT: macros are scoped to the caller\'s own project — this only ever returns '
@@ -455,7 +456,8 @@ const MCP_TOOL_CATALOG = [
455
456
  + '`id` resolves to a macro not visible to this project. Built-in macros (`id` starting with `builtin-`) '
456
457
  + "cannot be edited through this route. A macro is a HUMAN's one-click button, not a task runner — never "
457
458
  + 'create or update one unless the human has actually asked for that macro to exist. '
458
- + 'To remove a macro use macro_delete; never rewrite it into a placeholder.',
459
+ + 'To remove a macro use macro_delete; never rewrite it into a placeholder. '
460
+ + 'Never pass `projects` unless the human asked for every project in this chat; quote their words in `humanRequestQuote`.',
459
461
  exampleArgs: {
460
462
  cwd: '/home/bilko/Projects/session-manager',
461
463
  label: 'Publish git + npm',
@@ -466,6 +468,10 @@ const MCP_TOOL_CATALOG = [
466
468
  },
467
469
  notes: "cwd is optional — defaults to the calling session's own project root (SM_PROJECT_ROOT or "
468
470
  + 'process.cwd()) when omitted. label, agentName, tag and prompt are all required strings. '
471
+ + "`surface` is optional: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row. "
472
+ + '`projects: ["*"]` shows the macro in every project; it needs `humanRequestQuote`, the words the human typed in '
473
+ + 'this chat that ask for every/all projects, and is refused in a scheduled job or outside a Session Manager session. '
474
+ + 'Without `projects` the macro stays scoped to this project. '
469
475
  + '`inputs` is an optional array of { name, label, default, required, options } fields the human fills in '
470
476
  + 'when pressing the macro; reference each in the prompt as {{name}}. Omitting `inputs` on update keeps '
471
477
  + 'the existing inputs; `[]` clears them.',