claude-code-session-manager 0.129.0 → 0.130.1

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/assets/AgentLibrary-Dlhtc8Ty.js +2 -0
  3. package/dist/assets/AppSettings-A3KoPcmL.js +2 -0
  4. package/dist/assets/Button-DvTXa_-4.js +1 -0
  5. package/dist/assets/Extensions-Ddb4sQpO.js +13 -0
  6. package/dist/assets/{History-B2x-LMlT.js → History-DcnZxMoU.js} +2 -2
  7. package/dist/assets/Library-LftcMs6C.js +32 -0
  8. package/dist/assets/ListDetail-CnL1azR0.js +1 -0
  9. package/dist/assets/{Memory-CnalwnFf.js → Memory-smN9-Yoo.js} +8 -8
  10. package/dist/assets/{Panel-BzIklgKf.js → Panel-CA6TdCHv.js} +1 -1
  11. package/dist/assets/ProvenanceBadge-Y3DhyiJo.js +1 -0
  12. package/dist/assets/Scheduler-Ca1qo_kp.js +16 -0
  13. package/dist/assets/Settings-BFwlV-as.js +2 -0
  14. package/dist/assets/{SkillReferenceGraph-DOhiCxuL.js → SkillReferenceGraph-2WMsKdmr.js} +1 -1
  15. package/dist/assets/SourceChip-CeprSxwb.js +1 -0
  16. package/dist/assets/SystemPrompt-B8TXIGXo.js +1 -0
  17. package/dist/assets/{TiptapBody-Du6jRBoW.js → TiptapBody-BvxcQ_tS.js} +1 -1
  18. package/dist/assets/{Toggle-Qdi2Z7VD.js → Toggle-keTV_HDb.js} +1 -1
  19. package/dist/assets/ViewTabs-fupn9keJ.js +1 -0
  20. package/dist/assets/VoiceButton-5ETBv9eI.js +1 -0
  21. package/dist/assets/{historyTotals-8ecP_6wF.js → historyTotals-NAZqiuzd.js} +1 -1
  22. package/dist/assets/{index-DtdWBGrI.css → index-Bp8XE9A6.css} +1 -1
  23. package/dist/assets/index-QJxszEhM.js +3086 -0
  24. package/dist/index.html +2 -2
  25. package/dist-web/app.css +1 -1
  26. package/dist-web/app.js +396 -412
  27. package/package.json +1 -1
  28. package/plugins/CLAUDE.md +2 -2
  29. package/plugins/session-manager-dev/.claude-plugin/plugin.json +2 -2
  30. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +2 -2
  31. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -3
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +62 -0
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +169 -0
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +183 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +39 -0
  36. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +79 -0
  37. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +400 -0
  38. package/scripts/scheduler-mcp-server.cjs +25 -6
  39. package/src/main/agentLibrary.cjs +36 -10
  40. package/src/main/build-info.json +4 -4
  41. package/src/main/config.cjs +15 -0
  42. package/src/main/health.cjs +49 -22
  43. package/src/main/index.cjs +19 -3
  44. package/src/main/ipcSchemas.cjs +36 -3
  45. package/src/main/lib/activeSessions.cjs +6 -2
  46. package/src/main/lib/claude/modelCatalog.cjs +15 -31
  47. package/src/main/lib/claudeConfig.cjs +156 -0
  48. package/src/main/lib/effectiveSettings.cjs +120 -0
  49. package/src/main/lib/epic/delegationReadiness.cjs +3 -3
  50. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +84 -11
  51. package/src/main/lib/git/gitWorktree.cjs +400 -9
  52. package/src/main/lib/git/runtimeStateUntrack.cjs +124 -0
  53. package/src/main/lib/mcpToolCatalog.cjs +8 -2
  54. package/src/main/lib/memoryDirResolve.cjs +2 -8
  55. package/src/main/lib/opsOwnership.cjs +63 -2
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -0
  57. package/src/main/lib/persona-macro/macroLibrary.cjs +34 -6
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +22 -0
  59. package/src/main/lib/updateCheck.cjs +6 -1
  60. package/src/main/pluginInstall.cjs +100 -1
  61. package/src/main/promptSessionsIpc.cjs +39 -1
  62. package/src/main/scheduler.cjs +12 -2
  63. package/src/main/seedDevPlugin.cjs +2 -1
  64. package/src/main/templates/PRD_AUTHORING.md +3 -3
  65. package/src/main/updaterIpc.cjs +5 -1
  66. package/src/main/usage.cjs +5 -20
  67. package/src/main/voiceHotkey.cjs +16 -0
  68. package/src/main/voiceSettings.cjs +24 -0
  69. package/src/main/voiceWizard.cjs +27 -36
  70. package/src/preload/api.d.ts +53 -2
  71. package/src/preload/apiSurface.json +63 -7
  72. package/src/preload/index.cjs +12 -1
  73. package/src/seed/agents/demo-video-builder.md +2 -2
  74. package/src/seed/agents/validator.md +2 -2
  75. package/dist/assets/AgentLibrary-Cp250YHF.js +0 -2
  76. package/dist/assets/Button-DU5UF-6L.js +0 -1
  77. package/dist/assets/DataModel-CPf6f17e.js +0 -1
  78. package/dist/assets/Hooks-BWr33C4Q.js +0 -3
  79. package/dist/assets/Library-DBNLTAa8.js +0 -46
  80. package/dist/assets/ListDetail-BGBw6egp.js +0 -1
  81. package/dist/assets/McpServers-DywZ50Ec.js +0 -2
  82. package/dist/assets/Permissions-mgRifwQc.js +0 -3
  83. package/dist/assets/Plugins-CV42zfid.js +0 -2
  84. package/dist/assets/ProvenanceBadge-DYmX4xgB.js +0 -1
  85. package/dist/assets/SaveBar-DxrAfnlC.js +0 -1
  86. package/dist/assets/Scheduler-iyUl1NDl.js +0 -16
  87. package/dist/assets/ScopeSwitcher-CC8BDPgf.js +0 -1
  88. package/dist/assets/Settings-CWBnQghD.js +0 -4
  89. package/dist/assets/Skills-3Er-9YA9.js +0 -2
  90. package/dist/assets/SystemPrompt-BLxdvZ9K.js +0 -1
  91. package/dist/assets/TagLibrary-BZ6QHYMQ.js +0 -1
  92. package/dist/assets/ViewTabs-BKfFsziD.js +0 -1
  93. package/dist/assets/index-GI6F_j41.js +0 -3083
  94. package/dist/assets/listSkills-C1aWKf0T.js +0 -1
  95. package/dist/assets/settingsSchema-lHTHAabD.js +0 -1
  96. package/dist/assets/skillFrontmatter-8X1Uc282.js +0 -10
  97. package/dist/assets/useAgentsDirWatch-CcsoD1bp.js +0 -1
@@ -12,14 +12,23 @@
12
12
  * event on success; every refusal is a 400 with no onChanged and no audit.
13
13
  *
14
14
  * cwd resolution matches projectHomeAdminRoutes.cjs's resolveCwd exactly
15
- * (reused, not copied). A create always stores `projects: [resolvedCwd]`,
16
- * `surface: 'sessions'`; an update is refused (400) if the resolved cwd is
17
- * not already in the macro's `projects` (no cross-project hijack), if `id`
18
- * starts with `builtin-`, or if `id` is not found. Field validation reuses
19
- * macroLibrary's `MacroSaveSchema`.
15
+ * (reused, not copied). `surface` ('sessions' | 'project-home') is accepted on
16
+ * create and update; a create defaults it to 'sessions' and `projects` to
17
+ * [resolvedCwd]. `projects` is accepted ONLY as exactly ["*"] (show in every
18
+ * project); anything else is a 400. An update without `projects` leaves them
19
+ * unchanged. An update is refused (400) if the macro is not visible to the
20
+ * resolved cwd (macroLibrary.macroVisibleIn, so '*' macros are reachable), if
21
+ * `id` starts with `builtin-`, or if `id` is not found. Field validation
22
+ * reuses macroLibrary's `MacroSaveSchema`.
20
23
  *
21
- * A successful save calls `onChanged()` exactly once so the Sessions HOT
22
- * KEYS strip updates live, matching the IPC handlers in index.cjs.
24
+ * A save whose existing or resulting macro is shown in every project needs a
25
+ * VERIFIED human request: body.humanRequestQuote must appear in a prompt the
26
+ * human typed into body.originClaudeSessionId (humanPromptLedger) AND name
27
+ * every/all projects. Otherwise 400, no write, no onChanged, no audit.
28
+ *
29
+ * Every successful save appends one `admin_macro_save` audit event and calls
30
+ * `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
31
+ * matching the IPC handlers in index.cjs.
23
32
  */
24
33
  'use strict';
25
34
 
@@ -27,6 +36,37 @@ const { readBody, sendJson } = require('./localAdminHttp.cjs');
27
36
  const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
28
37
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
29
38
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
39
+ const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
40
+
41
+ const EVERY_PROJECT_RE = /(^|[^a-z0-9])(every|all|each)\s+(of\s+)?(my\s+|the\s+|our\s+)?projects?($|[^a-z0-9])/;
42
+
43
+ /** True when the quote asks for every/all projects (or "everywhere"). */
44
+ function quoteNamesEveryProject(quote) {
45
+ if (typeof quote !== 'string') return false;
46
+ const q = quote.toLowerCase().replace(/[-_]/g, ' ');
47
+ return EVERY_PROJECT_RE.test(q) || /(^|[^a-z0-9])everywhere($|[^a-z0-9])/.test(q);
48
+ }
49
+
50
+ const HUMAN_HINT = "the human can set 'Show in every project' in the macro editor";
51
+
52
+ /** Fail-closed check that a human asked for an all-projects macro. */
53
+ function verifyAllProjectsRequest(body) {
54
+ const quote = body.humanRequestQuote;
55
+ if (typeof quote !== 'string' || !quote.trim()) {
56
+ return { ok: false, reason: `a macro shown in every project needs humanRequestQuote (a verbatim human request); ${HUMAN_HINT}` };
57
+ }
58
+ const origin = body.originClaudeSessionId;
59
+ if (typeof origin !== 'string' || origin.length < 1 || origin.length > 128) {
60
+ return { ok: false, reason: `a macro shown in every project needs originClaudeSessionId (1-128 chars); ${HUMAN_HINT}` };
61
+ }
62
+ if (!findHumanPromptContaining(origin, quote)) {
63
+ return { ok: false, reason: `humanRequestQuote was not found in a prompt the human typed in this session; ${HUMAN_HINT}` };
64
+ }
65
+ if (!quoteNamesEveryProject(quote)) {
66
+ return { ok: false, reason: `humanRequestQuote does not name every/all projects; ${HUMAN_HINT}` };
67
+ }
68
+ return { ok: true, quote };
69
+ }
30
70
 
31
71
  /** Read + parse a JSON object body; on failure sends the 400 and returns null. */
32
72
  async function readJsonBody(req, res) {
@@ -79,6 +119,12 @@ function saveHandler(onChanged, libOpts) {
79
119
  sendJson(res, 400, { ok: false, error: 'built-in macros cannot be edited through this route' });
80
120
  return;
81
121
  }
122
+ const p = body.projects;
123
+ if (p !== undefined && !(Array.isArray(p) && p.length === 1 && p[0] === macroLibrary.ALL_PROJECTS)) {
124
+ sendJson(res, 400, { ok: false, error: 'projects: only ["*"] is accepted; omit it to use the current project' });
125
+ return;
126
+ }
127
+ const wantsAll = p !== undefined;
82
128
  let input;
83
129
  try {
84
130
  input = macroLibrary.MacroSaveSchema.parse({
@@ -88,24 +134,39 @@ function saveHandler(onChanged, libOpts) {
88
134
  tag: body.tag,
89
135
  prompt: body.prompt,
90
136
  inputs: body.inputs,
137
+ surface: body.surface,
91
138
  });
92
139
  } catch (e) {
93
140
  sendJson(res, 400, { ok: false, error: e?.issues?.[0]?.message ?? e?.message ?? 'invalid payload' });
94
141
  return;
95
142
  }
143
+ let existing;
96
144
  if (input.id) {
97
145
  const macros = await macroLibrary.listMacros(libOpts);
98
- const existing = macros.find((m) => m.id === input.id);
146
+ existing = macros.find((m) => m.id === input.id);
99
147
  if (!existing) {
100
148
  sendJson(res, 400, { ok: false, error: `macro not found: ${input.id}` });
101
149
  return;
102
150
  }
103
- if (!existing.projects.includes(resolved.cwd)) {
151
+ if (!macroLibrary.macroVisibleIn(existing, resolved.cwd)) {
104
152
  sendJson(res, 400, { ok: false, error: `macro ${input.id} is not visible to ${resolved.cwd}` });
105
153
  return;
106
154
  }
107
- } else {
108
- input = { ...input, projects: [resolved.cwd], surface: 'sessions' };
155
+ }
156
+ const allProjects = Boolean(existing?.projects.includes(macroLibrary.ALL_PROJECTS)) || wantsAll;
157
+ let quote = null;
158
+ if (allProjects) {
159
+ const v = verifyAllProjectsRequest(body);
160
+ if (!v.ok) {
161
+ sendJson(res, 400, { ok: false, error: v.reason });
162
+ return;
163
+ }
164
+ quote = v.quote;
165
+ }
166
+ if (!input.id) {
167
+ input = { ...input, projects: wantsAll ? [macroLibrary.ALL_PROJECTS] : [resolved.cwd], surface: input.surface ?? 'sessions' };
168
+ } else if (wantsAll) {
169
+ input = { ...input, projects: [macroLibrary.ALL_PROJECTS] };
109
170
  }
110
171
  let macro;
111
172
  try {
@@ -114,6 +175,17 @@ function saveHandler(onChanged, libOpts) {
114
175
  sendJson(res, 400, { ok: false, error: e?.message ?? 'save failed' });
115
176
  return;
116
177
  }
178
+ const origin = body.originClaudeSessionId;
179
+ appendAuditEvent('admin_macro_save', {
180
+ route: '/admin/macros/save',
181
+ cwd: resolved.cwd,
182
+ macroId: macro.id,
183
+ projects: macro.projects,
184
+ surface: macro.surface,
185
+ created: !input.id,
186
+ humanRequestQuote: quote,
187
+ originClaudeSessionId: typeof origin === 'string' && origin.length >= 1 && origin.length <= 128 ? origin : null,
188
+ });
117
189
  if (onChanged) onChanged();
118
190
  sendJson(res, 200, { ok: true, macro });
119
191
  };
@@ -165,4 +237,5 @@ function registerAdminRoute(adminHttp, { onChanged } = {}, opts = {}) {
165
237
 
166
238
  module.exports = {
167
239
  registerAdminRoute,
240
+ quoteNamesEveryProject,
168
241
  };
@@ -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,