claude-code-session-manager 0.131.0 → 0.133.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 (90) hide show
  1. package/README.md +3 -3
  2. package/dist/assets/{AgentLibrary-CYXre0J-.js → AgentLibrary-DOAG-mcG.js} +1 -1
  3. package/dist/assets/{AppSettings-xNSfCj8e.js → AppSettings-BHKM_AKh.js} +2 -2
  4. package/dist/assets/{Button-BWljh5IK.js → Button-CmO1wmPw.js} +1 -1
  5. package/dist/assets/{DocumentEditorPane-FUC2hZlp.js → DocumentEditorPane-8QMNrNRt.js} +1 -1
  6. package/dist/assets/{Extensions-CsyUoklz.js → Extensions-Boo21B3b.js} +2 -2
  7. package/dist/assets/{History-BvNmY9OQ.js → History-C4epd1hp.js} +1 -1
  8. package/dist/assets/{Library-DVXk77zA.js → Library-CrgzRQzL.js} +1 -1
  9. package/dist/assets/{ListDetail-DAAx__24.js → ListDetail-DA7y1DQ-.js} +1 -1
  10. package/dist/assets/{Panel-g2D-e-RM.js → Panel-D-WMBhKH.js} +1 -1
  11. package/dist/assets/{ProjectClaudeConfig-BDuHJwaO.js → ProjectClaudeConfig-CuUADpIu.js} +1 -1
  12. package/dist/assets/{ProvenanceBadge-wew4_nf3.js → ProvenanceBadge-B7AsoRk6.js} +1 -1
  13. package/dist/assets/{Scheduler-CbeUIqD-.js → Scheduler-C86gRh51.js} +1 -1
  14. package/dist/assets/{Settings-B23RsRfm.js → Settings-B4Q9DwVS.js} +1 -1
  15. package/dist/assets/{SkillReferenceGraph-BxQPCfsg.js → SkillReferenceGraph-DX4ZgvlY.js} +1 -1
  16. package/dist/assets/{Skills-4AR2FQrI.js → Skills-DqKI37yi.js} +1 -1
  17. package/dist/assets/{SourceChip-jrC0vjfw.js → SourceChip-C974LROr.js} +1 -1
  18. package/dist/assets/{SystemPrompt-hHoBEnYb.js → SystemPrompt-C502jIwO.js} +1 -1
  19. package/dist/assets/{TiptapBody-FkUqxO9u.js → TiptapBody-DwNXN6Ki.js} +1 -1
  20. package/dist/assets/{Toggle-DQMNWZKT.js → Toggle-C2OsxnPK.js} +1 -1
  21. package/dist/assets/{ViewTabs-DGU0ZuxB.js → ViewTabs-DBxKGbAK.js} +1 -1
  22. package/dist/assets/{VoiceButton-BPPvDllh.js → VoiceButton-C680wpmX.js} +1 -1
  23. package/dist/assets/{historyTotals-D8Oc3wUK.js → historyTotals-Cz-VYPEc.js} +1 -1
  24. package/dist/assets/{index-oXqzajWV.css → index-CMwAikUb.css} +1 -1
  25. package/dist/assets/index-Dh5geJe3.js +3111 -0
  26. package/dist/index.html +2 -2
  27. package/dist-web/app.css +1 -1
  28. package/dist-web/app.js +428 -414
  29. package/package.json +1 -1
  30. package/scripts/scheduler-mcp-server.cjs +12 -4
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +77 -14
  33. package/src/main/index.cjs +15 -0
  34. package/src/main/ipcSchemas.cjs +54 -0
  35. package/src/main/lib/CLAUDE.md +2 -0
  36. package/src/main/lib/agent-cli/adapters/antigravity.cjs +147 -0
  37. package/src/main/lib/agent-cli/adapters/codex.cjs +170 -0
  38. package/src/main/lib/agent-cli/adapters/cursor.cjs +138 -0
  39. package/src/main/lib/agent-cli/adapters/gemini.cjs +119 -0
  40. package/src/main/lib/agent-cli/adapters/opencode.cjs +117 -0
  41. package/src/main/lib/agent-cli/agentCliEvents.cjs +94 -0
  42. package/src/main/lib/agent-cli/agentCliIpc.cjs +109 -0
  43. package/src/main/lib/agent-cli/agentCliRegistry.cjs +213 -0
  44. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +152 -0
  45. package/src/main/lib/agent-cli/agentCliTurn.cjs +99 -0
  46. package/src/main/lib/app-preview/appPreviewIpc.cjs +125 -0
  47. package/src/main/lib/app-preview/appPreviewManager.cjs +317 -0
  48. package/src/main/lib/app-preview/appPreviewScripts.cjs +106 -0
  49. package/src/main/lib/app-preview/appPreviewSweep.cjs +92 -0
  50. package/src/main/lib/chatBootRecovery.cjs +41 -1
  51. package/src/main/lib/claude/agentEffortResolve.cjs +11 -3
  52. package/src/main/lib/epic/activeIndexMerge.cjs +25 -2
  53. package/src/main/lib/epic/archivedTranscript.cjs +39 -6
  54. package/src/main/lib/epic/epicChanges.cjs +466 -0
  55. package/src/main/lib/epic/epicMint.cjs +45 -1
  56. package/src/main/lib/epic/epicReopen.cjs +8 -2
  57. package/src/main/lib/epic/epicSpawnPlan.cjs +12 -0
  58. package/src/main/lib/epic/epicWorktreeMerge.cjs +39 -4
  59. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +9 -4
  60. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
  61. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  62. package/src/main/lib/git/gitExec.cjs +9 -1
  63. package/src/main/lib/git/gitWorktree.cjs +94 -0
  64. package/src/main/lib/git/unifiedDiff.cjs +207 -0
  65. package/src/main/lib/mcpToolCatalog.cjs +15 -6
  66. package/src/main/lib/mdDocCensus.cjs +364 -0
  67. package/src/main/lib/mdDocRefs.cjs +249 -0
  68. package/src/main/lib/mdNetworkScan.cjs +158 -15
  69. package/src/main/lib/persona-macro/builtinMacros.cjs +17 -0
  70. package/src/main/lib/persona-macro/macroJobDispatch.cjs +4 -1
  71. package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
  72. package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
  73. package/src/main/lib/prd/prdCreate.cjs +7 -2
  74. package/src/main/lib/prd/prdFrontmatter.cjs +10 -3
  75. package/src/main/lib/promptSessionSchema.cjs +6 -0
  76. package/src/main/lib/remoteTranscriptTail.cjs +23 -4
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +2 -1
  78. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  79. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  80. package/src/main/projectPages.cjs +19 -4
  81. package/src/main/promptSessionEvents.cjs +10 -6
  82. package/src/main/scheduler/gitTreeGuard.cjs +2 -1
  83. package/src/main/scheduler/prdParser.cjs +2 -1
  84. package/src/main/scheduler.cjs +7 -2
  85. package/src/main/transcripts.cjs +18 -4
  86. package/src/main/webRemote.cjs +10 -5
  87. package/src/preload/api.d.ts +150 -3
  88. package/src/preload/apiSurface.json +56 -0
  89. package/src/preload/index.cjs +22 -0
  90. package/dist/assets/index-9ajPMXBg.js +0 -3097
@@ -22,7 +22,7 @@ const { listRestorableSessions } = require('./restorableSessions.cjs');
22
22
  const { validatePath } = require('../../config.cjs');
23
23
 
24
24
  /**
25
- * createEpicViaIpc(cwd, { goalText, tag?, agentType?, source?, restoreSessionId? }) → Promise<{ epicId, session }>
25
+ * createEpicViaIpc(cwd, { goalText, tag?, agentType?, source?, restoreSessionId?, agentCli?, agentCliModel? }) → Promise<{ epicId, session }>
26
26
  *
27
27
  * THE one Epic-creation path (epicMint.cjs's SINGLE-CREATOR LAW): this handler
28
28
  * holds `MINT_AUTHORITY_NEW_EPIC_UI`, the token that unlocks ensureEpic's mint
@@ -49,8 +49,11 @@ const { validatePath } = require('../../config.cjs');
49
49
  * `restoreSessionId` (absent = a normal mint) asks ensureEpic to adopt that
50
50
  * existing Claude Code CLI session as the new Epic's claudeSessionId. ensureEpic's
51
51
  * restore gate decides; a refused id rejects the call, never mints a fresh session.
52
+ *
53
+ * `agentCli` / `agentCliModel` (absent = Claude Code) pick the agent CLI. ensureEpic
54
+ * owns the Claude-only rules; a broken rule throws, so the call rejects and nothing is minted.
52
55
  */
53
- async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId } = {}) {
56
+ async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId, agentCli, agentCliModel } = {}) {
54
57
  validatePath(cwd);
55
58
  const { epicId } = await ensureEpic(cwd, {
56
59
  goalText,
@@ -63,6 +66,8 @@ async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort,
63
66
  openingPrompt,
64
67
  sections,
65
68
  restoreSessionId,
69
+ agentCli,
70
+ agentCliModel,
66
71
  mintAuthority: MINT_AUTHORITY_NEW_EPIC_UI,
67
72
  status: 'proposed',
68
73
  });
@@ -88,8 +93,8 @@ function registerPromptSessionsCreateEpicHandlers() {
88
93
  const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
89
94
  ipcMain.handle(
90
95
  'promptSessions:create-epic',
91
- v(s.promptSessionsCreateEpic, ({ cwd, goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId }) =>
92
- createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId })),
96
+ v(s.promptSessionsCreateEpic, ({ cwd, goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId, agentCli, agentCliModel }) =>
97
+ createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId, agentCli, agentCliModel })),
93
98
  );
94
99
  ipcMain.handle(
95
100
  'promptSessions:list-restorable',
@@ -14,7 +14,10 @@
14
14
  * cwd resolution matches projectHomeAdminRoutes.cjs's resolveCwd exactly
15
15
  * (reused, not copied). `surface` ('sessions' | 'project-home') is accepted on
16
16
  * create and update; a create defaults it to 'sessions' and `projects` to
17
- * [resolvedCwd]. `projects` is accepted ONLY as exactly ["*"] (show in every
17
+ * [resolvedCwd]. A Project Home tool is part of Session Manager and shown in
18
+ * every project's Project Home, so any save whose resulting surface is
19
+ * 'project-home' stores projects ["*"]; only what it generates is per project.
20
+ * `projects` is accepted ONLY as exactly ["*"] (show in every
18
21
  * project); anything else is a 400. An update without `projects` leaves them
19
22
  * unchanged. An update is refused (400) if the macro is not visible to the
20
23
  * resolved cwd (macroLibrary.macroVisibleIn, so '*' macros are reachable), if
@@ -24,7 +27,7 @@
24
27
  * A save whose existing or resulting macro is shown in every project needs a
25
28
  * VERIFIED human request: body.humanRequestQuote must appear in a prompt the
26
29
  * human typed into body.originClaudeSessionId (humanPromptLedger) AND name
27
- * every/all projects. Otherwise 400, no write, no onChanged, no audit.
30
+ * every/all projects (or, for a 'project-home' macro, Project Home). Otherwise 400, no write, no onChanged, no audit.
28
31
  *
29
32
  * Every successful save appends one `admin_macro_save` audit event and calls
30
33
  * `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
@@ -47,23 +50,36 @@ function quoteNamesEveryProject(quote) {
47
50
  return EVERY_PROJECT_RE.test(q) || /(^|[^a-z0-9])everywhere($|[^a-z0-9])/.test(q);
48
51
  }
49
52
 
53
+ const PROJECT_HOME_RE = /(^|[^a-z0-9])project\s*home($|[^a-z0-9])/;
54
+
55
+ /** True when the quote names Project Home (project home / project-home / project_home). */
56
+ function quoteNamesProjectHome(quote) {
57
+ if (typeof quote !== 'string') return false;
58
+ const q = quote.toLowerCase().replace(/[-_]/g, ' ');
59
+ return PROJECT_HOME_RE.test(q);
60
+ }
61
+
50
62
  const HUMAN_HINT = "the human can set 'Show in every project' in the macro editor";
63
+ const PROJECT_HOME_HINT =
64
+ "a Project Home tool is shown in every project's Project Home, so it needs humanRequestQuote (the human's words asking for a Project Home tool); the human can add one from Project Home ▸ Tools ▸ Add a tool";
51
65
 
52
- /** Fail-closed check that a human asked for an all-projects macro. */
53
- function verifyAllProjectsRequest(body) {
66
+ /** Fail-closed check that a human asked for an all-projects macro (or a Project Home tool). */
67
+ function verifyAllProjectsRequest(body, { projectHome = false } = {}) {
68
+ const hint = projectHome ? PROJECT_HOME_HINT : HUMAN_HINT;
54
69
  const quote = body.humanRequestQuote;
55
70
  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}` };
71
+ return { ok: false, reason: `a macro shown in every project needs humanRequestQuote (a verbatim human request); ${hint}` };
57
72
  }
58
73
  const origin = body.originClaudeSessionId;
59
74
  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}` };
75
+ return { ok: false, reason: `a macro shown in every project needs originClaudeSessionId (1-128 chars); ${hint}` };
61
76
  }
62
77
  if (!findHumanPromptContaining(origin, quote)) {
63
- return { ok: false, reason: `humanRequestQuote was not found in a prompt the human typed in this session; ${HUMAN_HINT}` };
78
+ return { ok: false, reason: `humanRequestQuote was not found in a prompt the human typed in this session; ${hint}` };
64
79
  }
65
- if (!quoteNamesEveryProject(quote)) {
66
- return { ok: false, reason: `humanRequestQuote does not name every/all projects; ${HUMAN_HINT}` };
80
+ if (!quoteNamesEveryProject(quote) && !(projectHome && quoteNamesProjectHome(quote))) {
81
+ const named = projectHome ? 'Project Home or every/all projects' : 'every/all projects';
82
+ return { ok: false, reason: `humanRequestQuote does not name ${named}; ${hint}` };
67
83
  }
68
84
  return { ok: true, quote };
69
85
  }
@@ -153,10 +169,12 @@ function saveHandler(onChanged, libOpts) {
153
169
  return;
154
170
  }
155
171
  }
156
- const allProjects = Boolean(existing?.projects.includes(macroLibrary.ALL_PROJECTS)) || wantsAll;
172
+ const resultSurface = input.surface ?? existing?.surface ?? 'sessions';
173
+ const projectHome = resultSurface === 'project-home';
174
+ const allProjects = Boolean(existing?.projects.includes(macroLibrary.ALL_PROJECTS)) || wantsAll || projectHome;
157
175
  let quote = null;
158
176
  if (allProjects) {
159
- const v = verifyAllProjectsRequest(body);
177
+ const v = verifyAllProjectsRequest(body, { projectHome });
160
178
  if (!v.ok) {
161
179
  sendJson(res, 400, { ok: false, error: v.reason });
162
180
  return;
@@ -164,8 +182,12 @@ function saveHandler(onChanged, libOpts) {
164
182
  quote = v.quote;
165
183
  }
166
184
  if (!input.id) {
167
- input = { ...input, projects: wantsAll ? [macroLibrary.ALL_PROJECTS] : [resolved.cwd], surface: input.surface ?? 'sessions' };
168
- } else if (wantsAll) {
185
+ input = {
186
+ ...input,
187
+ projects: wantsAll || projectHome ? [macroLibrary.ALL_PROJECTS] : [resolved.cwd],
188
+ surface: input.surface ?? 'sessions',
189
+ };
190
+ } else if (wantsAll || projectHome) {
169
191
  input = { ...input, projects: [macroLibrary.ALL_PROJECTS] };
170
192
  }
171
193
  let macro;
@@ -238,4 +260,5 @@ function registerAdminRoute(adminHttp, { onChanged } = {}, opts = {}) {
238
260
  module.exports = {
239
261
  registerAdminRoute,
240
262
  quoteNamesEveryProject,
263
+ quoteNamesProjectHome,
241
264
  };
@@ -64,6 +64,8 @@ const PATH_FENCED_CHANNELS = Object.freeze({
64
64
  'project-pages:md-network': { field: 'cwd', mode: 'root' },
65
65
  // Project Home ▸ Tools ▸ Competitor matrix (main/projectPages.cjs): read-only, cwd inside a registered root.
66
66
  'project-pages:matrix': { field: 'cwd', mode: 'root' },
67
+ // Epic Changes view (main/lib/epic/epicChanges.cjs): diffs a repo, so cwd must sit inside a registered root.
68
+ 'epicChanges:get': { field: 'cwd', mode: 'root' },
67
69
  })
68
70
 
69
71
  const SECRET_DIRS = new Set(['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.password-store', '.azure', '.terraform.d'])
@@ -83,4 +83,12 @@ const STRANDED_REF_PREFIX = 'refs/sm-stranded/';
83
83
  */
84
84
  const UNCOMMITTED_REF_PREFIX = 'refs/sm-uncommitted/';
85
85
 
86
- module.exports = { execGit, parseWorktreePorcelain, STRANDED_REF_PREFIX, UNCOMMITTED_REF_PREFIX };
86
+ /**
87
+ * Namespace for an Epic's review range: refs/sm-epic-review/<epicId>/<tipSha>/
88
+ * {base,head}, pinned before its sm-epic/<id> branch is deleted so a completed
89
+ * Epic can still be diffed (gitWorktree.pinEpicReviewRange). Outside
90
+ * refs/heads: a GC root that branch listings and branchSweep never touch.
91
+ */
92
+ const EPIC_REVIEW_REF_PREFIX = 'refs/sm-epic-review/';
93
+
94
+ module.exports = { execGit, parseWorktreePorcelain, STRANDED_REF_PREFIX, UNCOMMITTED_REF_PREFIX, EPIC_REVIEW_REF_PREFIX };
@@ -3556,6 +3556,98 @@ async function snapshotUncommittedWork({ cwd, dir, key }) {
3556
3556
  }
3557
3557
  }
3558
3558
 
3559
+ // ──────────────────────────────────────────── Epic review-range pins
3560
+
3561
+ /**
3562
+ * Pins an Epic's review range — its fork point and its tip — under
3563
+ * EPIC_REVIEW_REF_PREFIX/<epicId>/<headSha>/{base,head} so the Changes view can
3564
+ * still diff the Epic after its sm-epic/<id> branch is deleted. The head is the
3565
+ * branch tip, or, when `dir` holds uncommitted changes, a snapshot commit of
3566
+ * them (snapshotUncommittedWork, which leaves the checkout untouched). One pair
3567
+ * per completion cycle: a reopened, re-completed Epic keeps both.
3568
+ *
3569
+ * Returns { ok: true, base, head }, or { ok: false, reason } when the epicId is
3570
+ * unsafe, the branch is missing, nothing changed, or git fails. Never throws.
3571
+ *
3572
+ * @param {{ cwd: string, branch: string, dir?: string|null }} opts
3573
+ * @returns {Promise<{ ok: true, base: string, head: string } | { ok: false, reason: string }>}
3574
+ */
3575
+ async function pinEpicReviewRange({ cwd, branch, dir }) {
3576
+ try {
3577
+ const epicId = keyFromBranch('epic', branch);
3578
+ if (!epicId || !landBranchNameFor(epicId)) return { ok: false, reason: 'unsafe epicId' };
3579
+ const ref = `refs/heads/${branch}`;
3580
+ const tip = await tryResolveCommit(cwd, `${ref}^{commit}`);
3581
+ if (!tip) return { ok: false, reason: 'branch not found' };
3582
+ let fork = await resolveForkSha({ cwd, branch });
3583
+ if (!fork) {
3584
+ const base = await resolveDefaultBranch(cwd);
3585
+ try {
3586
+ fork = (await execGit(['merge-base', `refs/heads/${base}`, ref], { cwd, timeout: 10_000 })).trim() || null;
3587
+ } catch { fork = null; }
3588
+ }
3589
+ if (!fork) return { ok: false, reason: 'no fork point' };
3590
+ let head = tip;
3591
+ if (dir && fs.existsSync(dir)) {
3592
+ const snap = await snapshotUncommittedWork({ cwd, dir, key: epicId });
3593
+ if (snap && 'sha' in snap && snap.sha) head = snap.sha;
3594
+ }
3595
+ if (head === fork) return { ok: false, reason: 'no changes' };
3596
+ const prefix = `${sharedGitExec.EPIC_REVIEW_REF_PREFIX}${epicId}/${head}`;
3597
+ await execGit(['update-ref', `${prefix}/base`, fork], { cwd, timeout: 10_000 });
3598
+ await execGit(['update-ref', `${prefix}/head`, head], { cwd, timeout: 10_000 });
3599
+ return { ok: true, base: fork, head };
3600
+ } catch (err) {
3601
+ const e = /** @type {any} */ (err);
3602
+ const msg = String((e && (e.stderrText || e.message)) || e).trim().split('\n')[0] || 'git failure';
3603
+ return { ok: false, reason: msg };
3604
+ }
3605
+ }
3606
+
3607
+ /**
3608
+ * Every pinned review range for `epicId`, newest head commit first, from one
3609
+ * `git for-each-ref` over EPIC_REVIEW_REF_PREFIX/<epicId>/. Pairs missing base
3610
+ * or head are skipped. [] for an unsafe epicId, no refs, or any git failure.
3611
+ * Never throws.
3612
+ *
3613
+ * @param {{ cwd: string, epicId: string }} opts
3614
+ * @returns {Promise<Array<{ base: string, head: string, headCommittedAt: string }>>}
3615
+ */
3616
+ async function listEpicReviewRanges({ cwd, epicId }) {
3617
+ try {
3618
+ if (!landBranchNameFor(epicId)) return [];
3619
+ const prefix = `${sharedGitExec.EPIC_REVIEW_REF_PREFIX}${epicId}/`;
3620
+ const out = await execGit(
3621
+ ['for-each-ref', '--format=%(refname) %(objectname) %(committerdate:iso-strict)', prefix],
3622
+ { cwd, timeout: 10_000 }
3623
+ );
3624
+ /** @type {Map<string, { base?: string, head?: string, headCommittedAt?: string }>} */
3625
+ const byTip = new Map();
3626
+ for (const line of String(out).split('\n')) {
3627
+ const [refname, sha, date] = line.trim().split(' ');
3628
+ if (!refname || !sha || !refname.startsWith(prefix)) continue;
3629
+ const parts = refname.slice(prefix.length).split('/');
3630
+ if (parts.length !== 2) continue;
3631
+ const [tipSeg, role] = parts;
3632
+ const entry = byTip.get(tipSeg) || {};
3633
+ if (role === 'base') entry.base = sha;
3634
+ else if (role === 'head') { entry.head = sha; entry.headCommittedAt = date || ''; }
3635
+ else continue;
3636
+ byTip.set(tipSeg, entry);
3637
+ }
3638
+ /** @type {Array<{ base: string, head: string, headCommittedAt: string }>} */
3639
+ const ranges = [];
3640
+ for (const e of byTip.values()) {
3641
+ if (e.base && e.head) ranges.push({ base: e.base, head: e.head, headCommittedAt: e.headCommittedAt || '' });
3642
+ }
3643
+ const ts = (/** @type {string} */ d) => { const n = Date.parse(d); return Number.isFinite(n) ? n : 0; };
3644
+ ranges.sort((a, b) => ts(b.headCommittedAt) - ts(a.headCommittedAt));
3645
+ return ranges;
3646
+ } catch {
3647
+ return [];
3648
+ }
3649
+ }
3650
+
3559
3651
  /**
3560
3652
  * Number of commit / cherry-pick / revert entries in `dir`'s HEAD reflog
3561
3653
  * (same subject test as pinUnlandedWorktreeCommits) — the commits a run made
@@ -3613,6 +3705,8 @@ module.exports = {
3613
3705
  deleteBranchKeepingUniqueCommits,
3614
3706
  listStrandedPins,
3615
3707
  resolveForkSha,
3708
+ pinEpicReviewRange,
3709
+ listEpicReviewRanges,
3616
3710
  sweepStaleWorktreeCheckouts,
3617
3711
  mainTreeFromWorktreeGitFile,
3618
3712
  getObservedWorktreeCount,
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+
3
+ // unifiedDiff.cjs — pure parser: `git diff` unified text → per-file hunks and
4
+ // numbered lines, for the Epic Changes view. Never runs git; the caller
5
+ // (epic/epicChanges.cjs) runs it and hands the text here.
6
+
7
+ const { unquotePorcelainPath } = require('./gitWorktree.cjs');
8
+
9
+ const DEFAULT_MAX_LINES_PER_FILE = 3000;
10
+ const HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
11
+
12
+ /**
13
+ * @typedef {{ kind: 'add' | 'del' | 'ctx', oldNo: number | null, newNo: number | null, text: string }} DiffLine
14
+ * @typedef {{ header: string, oldStart: number, oldLines: number, newStart: number, newLines: number, lines: DiffLine[] }} DiffHunk
15
+ * @typedef {{ path: string, oldPath: string | null, status: 'added' | 'deleted' | 'modified' | 'renamed', binary: boolean, additions: number, deletions: number, hunks: DiffHunk[], truncated: boolean }} DiffFile
16
+ */
17
+
18
+ /**
19
+ * Decode a path token as git prints it: optional C-style quoting, then an
20
+ * optional `a/` or `b/` prefix, then git's trailing tab (added after a name
21
+ * that contains a space).
22
+ * @param {string} raw
23
+ * @param {string | null} prefix
24
+ */
25
+ function decodePath(raw, prefix) {
26
+ const p = unquotePorcelainPath(raw.replace(/\t+$/, ''));
27
+ if (prefix && p.startsWith(prefix)) return p.slice(prefix.length);
28
+ return p;
29
+ }
30
+
31
+ /**
32
+ * Split the `diff --git <a> <b>` header into its two raw paths. Quoted tokens
33
+ * are exact; for unquoted ones (which may contain spaces) the split relies on
34
+ * both sides naming the same path, which holds for every non-rename entry —
35
+ * renames carry `rename from`/`rename to` lines that override this.
36
+ * @param {string} rest text after `diff --git `
37
+ * @returns {{ a: string, b: string } | null}
38
+ */
39
+ function splitGitHeader(rest) {
40
+ /** @param {string} s */
41
+ const readQuoted = (s) => {
42
+ for (let i = 1; i < s.length; i += 1) {
43
+ if (s[i] === '\\') i += 1;
44
+ else if (s[i] === '"') return s.slice(0, i + 1);
45
+ }
46
+ return null;
47
+ };
48
+ if (rest.startsWith('"')) {
49
+ const a = readQuoted(rest);
50
+ if (!a) return null;
51
+ const tail = rest.slice(a.length).replace(/^ /, '');
52
+ return { a: decodePath(a, 'a/'), b: decodePath(tail, 'b/') };
53
+ }
54
+ const qi = rest.indexOf(' "b/');
55
+ if (qi >= 0) return { a: decodePath(rest.slice(0, qi), 'a/'), b: decodePath(rest.slice(qi + 1), 'b/') };
56
+ // Unquoted: "a/P b/P" — try the midpoint first, then any " b/" separator.
57
+ if ((rest.length - 1) % 2 === 0) {
58
+ const half = (rest.length - 1) / 2;
59
+ const a = rest.slice(0, half);
60
+ const b = rest.slice(half + 1);
61
+ if (rest[half] === ' ' && a.startsWith('a/') && b.startsWith('b/') && a.slice(2) === b.slice(2)) {
62
+ return { a: a.slice(2), b: b.slice(2) };
63
+ }
64
+ }
65
+ const si = rest.indexOf(' b/');
66
+ if (si >= 0) return { a: decodePath(rest.slice(0, si), 'a/'), b: decodePath(rest.slice(si + 1), 'b/') };
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * Parse `git diff` unified output into structured files.
72
+ *
73
+ * Input contract: callers run git with `--no-color --no-ext-diff -M` and the
74
+ * default `a/` `b/` prefixes (no --no-prefix / --src-prefix). Combined
75
+ * (merge) diffs are not supported.
76
+ *
77
+ * @param {unknown} text
78
+ * @param {{ maxLinesPerFile?: number }} [opts] lines past the cap are dropped
79
+ * (the file gets `truncated: true`); additions/deletions still count all.
80
+ * @returns {DiffFile[]}
81
+ */
82
+ function parseUnifiedDiff(text, opts) {
83
+ if (typeof text !== 'string' || text.trim() === '') return [];
84
+ const maxRaw = opts && opts.maxLinesPerFile;
85
+ const maxLines = typeof maxRaw === 'number' && maxRaw >= 0 ? maxRaw : DEFAULT_MAX_LINES_PER_FILE;
86
+
87
+ /** @type {DiffFile[]} */
88
+ const files = [];
89
+ /** @type {(DiffFile & { _kept: number, _headerA: string | null, _headerB: string | null, _minus: string | null, _plus: string | null, _renameFrom: string | null, _renameTo: string | null, _created: boolean, _deleted: boolean }) | null} */
90
+ let cur = null;
91
+ /** @type {DiffHunk | null} */
92
+ let hunk = null;
93
+ let oldNo = 0;
94
+ let newNo = 0;
95
+ let oldLeft = 0;
96
+ let newLeft = 0;
97
+ let inBinaryPatch = false;
98
+
99
+ const finish = () => {
100
+ if (!cur) return;
101
+ const c = cur;
102
+ let status = /** @type {DiffFile['status']} */ ('modified');
103
+ if (c._created || c._minus === '/dev/null') status = 'added';
104
+ else if (c._deleted || c._plus === '/dev/null') status = 'deleted';
105
+ else if (c._renameFrom !== null || c._renameTo !== null) status = 'renamed';
106
+
107
+ const newSide = c._renameTo ?? (c._plus && c._plus !== '/dev/null' ? c._plus : null) ?? c._headerB;
108
+ const oldSide = c._renameFrom ?? (c._minus && c._minus !== '/dev/null' ? c._minus : null) ?? c._headerA;
109
+ const filePath = status === 'deleted' ? (oldSide ?? newSide ?? '') : (newSide ?? oldSide ?? '');
110
+ files.push({
111
+ path: filePath,
112
+ oldPath: status === 'renamed' ? (oldSide ?? null) : null,
113
+ status,
114
+ binary: c.binary,
115
+ additions: c.additions,
116
+ deletions: c.deletions,
117
+ // A hunk that starts past the cap keeps no lines; drop it entirely.
118
+ hunks: c.truncated ? c.hunks.filter((h) => h.lines.length > 0) : c.hunks,
119
+ truncated: c.truncated,
120
+ });
121
+ cur = null;
122
+ hunk = null;
123
+ };
124
+
125
+ const lines = text.split('\n');
126
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
127
+
128
+ for (const line of lines) {
129
+ // Inside a hunk the remaining counts decide what a line is, so a deleted
130
+ // line like "--- a/x" is never mistaken for a file header.
131
+ if (cur && hunk && (oldLeft > 0 || newLeft > 0)) {
132
+ const c0 = line[0];
133
+ /** @type {DiffLine | null} */
134
+ let entry = null;
135
+ if (c0 === '+') {
136
+ entry = { kind: 'add', oldNo: null, newNo: newNo, text: line.slice(1) };
137
+ newNo += 1; newLeft -= 1; cur.additions += 1;
138
+ } else if (c0 === '-') {
139
+ entry = { kind: 'del', oldNo: oldNo, newNo: null, text: line.slice(1) };
140
+ oldNo += 1; oldLeft -= 1; cur.deletions += 1;
141
+ } else if (c0 === ' ' || line === '') {
142
+ entry = { kind: 'ctx', oldNo: oldNo, newNo: newNo, text: line.slice(1) };
143
+ oldNo += 1; newNo += 1; oldLeft -= 1; newLeft -= 1;
144
+ } else if (c0 === '\\') {
145
+ continue;
146
+ }
147
+ if (entry) {
148
+ if (cur._kept < maxLines) {
149
+ hunk.lines.push(entry);
150
+ cur._kept += 1;
151
+ } else {
152
+ cur.truncated = true;
153
+ }
154
+ continue;
155
+ }
156
+ // Malformed counts: fall through and treat the line as structure.
157
+ oldLeft = 0;
158
+ newLeft = 0;
159
+ }
160
+
161
+ if (line.startsWith('diff --git ')) {
162
+ finish();
163
+ const hdr = splitGitHeader(line.slice('diff --git '.length));
164
+ cur = {
165
+ path: '', oldPath: null, status: 'modified', binary: false, additions: 0, deletions: 0, hunks: [], truncated: false,
166
+ _kept: 0, _headerA: hdr ? hdr.a : null, _headerB: hdr ? hdr.b : null, _minus: null, _plus: null,
167
+ _renameFrom: null, _renameTo: null, _created: false, _deleted: false,
168
+ };
169
+ hunk = null;
170
+ inBinaryPatch = false;
171
+ continue;
172
+ }
173
+ if (!cur) continue;
174
+ if (line.startsWith('\\')) continue;
175
+
176
+ const m = HUNK_RE.exec(line);
177
+ if (m && !inBinaryPatch) {
178
+ hunk = {
179
+ header: line,
180
+ oldStart: Number(m[1]),
181
+ oldLines: m[2] === undefined ? 1 : Number(m[2]),
182
+ newStart: Number(m[3]),
183
+ newLines: m[4] === undefined ? 1 : Number(m[4]),
184
+ lines: [],
185
+ };
186
+ cur.hunks.push(hunk);
187
+ oldNo = hunk.oldStart;
188
+ newNo = hunk.newStart;
189
+ oldLeft = hunk.oldLines;
190
+ newLeft = hunk.newLines;
191
+ continue;
192
+ }
193
+ if (inBinaryPatch) continue;
194
+ if (line.startsWith('--- ')) cur._minus = decodePath(line.slice(4), 'a/');
195
+ else if (line.startsWith('+++ ')) cur._plus = decodePath(line.slice(4), 'b/');
196
+ else if (line.startsWith('new file mode')) cur._created = true;
197
+ else if (line.startsWith('deleted file mode')) cur._deleted = true;
198
+ else if (line.startsWith('rename from ')) cur._renameFrom = decodePath(line.slice(12), null);
199
+ else if (line.startsWith('rename to ')) cur._renameTo = decodePath(line.slice(10), null);
200
+ else if (line.startsWith('Binary files ') && line.endsWith(' differ')) cur.binary = true;
201
+ else if (line === 'GIT binary patch') { cur.binary = true; inBinaryPatch = true; }
202
+ }
203
+ finish();
204
+ return files;
205
+ }
206
+
207
+ module.exports = { parseUnifiedDiff };
@@ -462,8 +462,9 @@ const MCP_TOOL_CATALOG = [
462
462
  name: 'macro_list',
463
463
  group: 'macros',
464
464
  purpose: "List this project's HOT KEYS macros — the saved (agent, tag, prompt) one-click buttons shown "
465
- + "in the Sessions tab's HOT KEYS strip or the Project Home button row, via the session-manager app's admin API. "
466
- + "Each macro's `surface` tells where it shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row.",
465
+ + "in the Sessions tab's HOT KEYS strip or as tools in Project Home ▸ Tools, via the session-manager app's admin API. "
466
+ + "Each macro's `surface` tells where it shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = a tool in "
467
+ + 'Project Home ▸ Tools, shown in every project (only what it generates is per project).',
467
468
  whenToUse: 'Use to see what macros already exist for this project (including machine-wide `*` macros and '
468
469
  + 'built-ins) before deciding whether to add, update or delete one.',
469
470
  whenNotToUse: 'WHEN NOT TO USE IT: macros are scoped to the caller\'s own project — this only ever returns '
@@ -479,13 +480,18 @@ const MCP_TOOL_CATALOG = [
479
480
  + 'the Sessions HOT KEYS strip reads from.',
480
481
  whenToUse: 'Pass `id` to update an existing macro already visible to this project; omit `id` to create a new '
481
482
  + 'one scoped to this project. Use for things like a "Publish git + npm" macro a human will press '
482
- + 'repeatedly, when they have asked for that macro to exist.',
483
+ + 'repeatedly, when they have asked for that macro to exist. A surface \'project-home\' macro is a Project Home '
484
+ + 'tool and is always saved for every project; pass `humanRequestQuote` with the human\'s words naming Project Home '
485
+ + '(or every project).',
483
486
  whenNotToUse: 'WHEN NOT TO USE IT: macros are scoped to the caller\'s own project — this call is refused if '
484
487
  + '`id` resolves to a macro not visible to this project. Built-in macros (`id` starting with `builtin-`) '
485
488
  + "cannot be edited through this route. A macro is a HUMAN's one-click button, not a task runner — never "
486
489
  + 'create or update one unless the human has actually asked for that macro to exist. '
487
490
  + 'To remove a macro use macro_delete; never rewrite it into a placeholder. '
488
- + 'Never pass `projects` unless the human asked for every project in this chat; quote their words in `humanRequestQuote`.',
491
+ + 'Never pass `projects` unless the human asked for every project in this chat; quote their words in `humanRequestQuote`. '
492
+ + 'Never save a surface \'project-home\' macro unless the human asked in this chat for a Project Home tool — it is '
493
+ + 'always saved for every project, needs `humanRequestQuote` naming Project Home (or every project), and is refused '
494
+ + 'in a scheduled job or outside a Session Manager chat session.',
489
495
  exampleArgs: {
490
496
  cwd: '/home/bilko/Projects/session-manager',
491
497
  label: 'Publish git + npm',
@@ -496,10 +502,13 @@ const MCP_TOOL_CATALOG = [
496
502
  },
497
503
  notes: "cwd is optional — defaults to the calling session's own project root (SM_PROJECT_ROOT or "
498
504
  + 'process.cwd()) when omitted. label, agentName, tag and prompt are all required strings. '
499
- + "`surface` is optional: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row. "
505
+ + "`surface` is optional: 'sessions' = Sessions HOT KEYS strip, 'project-home' = a tool in Project Home ▸ Tools. "
506
+ + "A surface 'project-home' macro is always saved for every project (only what it generates is per project); it "
507
+ + 'needs `humanRequestQuote` naming Project Home (or every project) and is refused in a scheduled job or outside '
508
+ + 'a Session Manager chat session. '
500
509
  + '`projects: ["*"]` shows the macro in every project; it needs `humanRequestQuote`, the words the human typed in '
501
510
  + 'this chat that ask for every/all projects, and is refused in a scheduled job or outside a Session Manager session. '
502
- + 'Without `projects` the macro stays scoped to this project. '
511
+ + "Without `projects`, a 'sessions' macro stays scoped to this project. "
503
512
  + '`inputs` is an optional array of { name, label, default, required, options } fields the human fills in '
504
513
  + 'when pressing the macro; reference each in the prompt as {{name}}. Omitting `inputs` on update keeps '
505
514
  + 'the existing inputs; `[]` clears them.',