claude-code-session-manager 0.130.3 → 0.132.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-C09MlPFx.js} +2 -2
  2. package/dist/assets/AppSettings-DvDKsCnD.js +2 -0
  3. package/dist/assets/{Button-UUr5giu8.js → Button-BzG_KdBC.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-fm6zsnLM.js} +1 -1
  5. package/dist/assets/Extensions-DgxKT_OZ.js +2 -0
  6. package/dist/assets/{History-Bndupj87.js → History-Nd3bKjBq.js} +2 -2
  7. package/dist/assets/{Library-DFn0YPIW.js → Library-R71t6VAB.js} +12 -12
  8. package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-CG50Ul7c.js} +1 -1
  9. package/dist/assets/{Panel-CIvb-XXN.js → Panel-C7EFG4eU.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-J92iNEGC.js} +7 -7
  11. package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-C3KB3ILO.js} +1 -1
  12. package/dist/assets/Scheduler-DeYBA7uc.js +16 -0
  13. package/dist/assets/{Settings-DqxUna06.js → Settings-B6r7N4v-.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-D7bt3fyB.js} +1 -1
  15. package/dist/assets/Skills-GpxtUrFP.js +29 -0
  16. package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-uyVMCZc7.js} +1 -1
  17. package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-Cv25uFSM.js} +1 -1
  18. package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-uP8fJkbM.js} +1 -1
  19. package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DRs80cX-.js} +1 -1
  20. package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-BDkvvzJ8.js} +1 -1
  21. package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-Cmtz2sQt.js} +1 -1
  22. package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-DHwAXunq.js} +1 -1
  23. package/dist/assets/index-CBCdyHbZ.js +3097 -0
  24. package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +414 -390
  28. package/package.json +1 -1
  29. package/scripts/scheduler-mcp-server.cjs +83 -4
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/index.cjs +11 -0
  32. package/src/main/ipcSchemas.cjs +28 -1
  33. package/src/main/lib/epic/epicMint.cjs +61 -6
  34. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  35. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  36. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  37. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
  38. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  39. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  40. package/src/main/lib/git/branchSweep.cjs +9 -3
  41. package/src/main/lib/git/gitExec.cjs +8 -1
  42. package/src/main/lib/git/gitWorktree.cjs +564 -62
  43. package/src/main/lib/git/jobWorktree.cjs +3 -0
  44. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  45. package/src/main/lib/mcpToolCatalog.cjs +43 -6
  46. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  47. package/src/main/lib/persona-macro/builtinMacros.cjs +33 -0
  48. package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
  49. package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
  50. package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
  51. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  52. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  53. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  54. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  55. package/src/main/lib/promptSessionSchema.cjs +5 -0
  56. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  57. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  58. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  59. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  60. package/src/main/projectPages.cjs +25 -2
  61. package/src/main/promptSessionEvents.cjs +10 -6
  62. package/src/main/runVerify.cjs +8 -3
  63. package/src/main/scheduler/budget.cjs +146 -7
  64. package/src/main/scheduler/gitTreeGuard.cjs +10 -11
  65. package/src/main/scheduler/reviewLadder.cjs +60 -0
  66. package/src/main/scheduler.cjs +461 -48
  67. package/src/main/seedAgentPersonas.cjs +1 -1
  68. package/src/preload/api.d.ts +162 -2
  69. package/src/preload/apiSurface.json +21 -0
  70. package/src/preload/index.cjs +5 -0
  71. package/src/seed/agents/competitive-analyst.md +69 -0
  72. package/src/seed/agents/competitive-researcher.md +75 -0
  73. package/src/seed/agents/validator.md +2 -2
  74. package/dist/assets/AppSettings-Cs4POznd.js +0 -2
  75. package/dist/assets/Extensions-B9QdiNOV.js +0 -2
  76. package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
  77. package/dist/assets/Skills-DTXehVS7.js +0 -12
  78. package/dist/assets/index-C9w-dVzo.js +0 -3090
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.130.3",
3
+ "version": "0.132.0",
4
4
  "description": "Local cockpit for the Claude Code CLI — multi-tab terminal, full config surface, scheduler, voice dictation, and live observability.",
5
5
  "type": "module",
6
6
  "main": "src/main/index.cjs",
@@ -14,6 +14,8 @@
14
14
  * project_home_write({ cwd?, html }) -> POST /admin/project-home/write
15
15
  * project_demo_video_write({ cwd?, html? | htmlPath? }) -> POST /admin/project-home/demo-video/write
16
16
  * project_page_write({ cwd?, pageId, title, topic?, html? | htmlPath? }) -> POST /admin/project-home/pages/write
17
+ * project_matrix_read({ cwd? }) -> POST /admin/project-home/matrix/read
18
+ * project_matrix_write({ cwd?, matrix? | matrixPath?, model? }) -> POST /admin/project-home/matrix/write
17
19
  * project_character_write({ cwd?, json, js? | jsPath?, replace? }) -> POST /admin/project-home/character/write
18
20
  * project_video_write({ cwd?, videoId, title, kind, lengthS, html? | htmlPath?, meta? }) -> POST /admin/project-home/videos/write
19
21
  *
@@ -64,6 +66,7 @@ function withPointer(text) {
64
66
 
65
67
  const MAX_DEMO_VIDEO_BYTES = 2 * 1024 * 1024;
66
68
  const MAX_CHARACTER_JS_BYTES = 300 * 1024;
69
+ const MAX_MATRIX_JSON_BYTES = 1048576;
67
70
 
68
71
  /** Reads a local .js file for project_character_write; errors carry only the reason, never file contents. */
69
72
  async function readCharacterJsFile(p) {
@@ -107,6 +110,37 @@ async function resolveHtmlArg(args) {
107
110
  return { html: args.html };
108
111
  }
109
112
 
113
+ /** Reads + parses a local .json file for project_matrix_write; errors carry only the reason, never file contents. */
114
+ async function readMatrixJsonFile(p) {
115
+ if (typeof p !== 'string' || !path.isAbsolute(p)) return { error: 'matrixPath must be an absolute path' };
116
+ if (!/\.json$/i.test(p)) return { error: 'matrixPath must end in .json' };
117
+ let raw;
118
+ try {
119
+ const st = await fsp.stat(p);
120
+ if (!st.isFile()) return { error: 'matrixPath is not a regular file' };
121
+ if (st.size > MAX_MATRIX_JSON_BYTES) return { error: `matrixPath file exceeds ${MAX_MATRIX_JSON_BYTES} bytes` };
122
+ raw = await fsp.readFile(p, 'utf8');
123
+ } catch (err) {
124
+ return { error: `cannot read matrixPath: ${err && err.code ? err.code : 'read failed'}` };
125
+ }
126
+ let parsed;
127
+ try { parsed = JSON.parse(raw); } catch (err) {
128
+ return { error: `matrixPath is not valid JSON: ${err && err.message ? err.message : 'parse failed'}` };
129
+ }
130
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { error: 'matrixPath must hold a JSON object' };
131
+ return { matrix: parsed };
132
+ }
133
+
134
+ /** Resolves exactly one of matrix / matrixPath into { matrix } or { error }. */
135
+ async function resolveJsonArg(args) {
136
+ const hasMatrix = !!args && args.matrix !== undefined && args.matrix !== null && args.matrix !== '';
137
+ const hasPath = !!args && args.matrixPath !== undefined && args.matrixPath !== null && args.matrixPath !== '';
138
+ if (hasMatrix === hasPath) return { error: 'provide exactly one of matrix or matrixPath' };
139
+ if (hasPath) return readMatrixJsonFile(args.matrixPath);
140
+ if (typeof args.matrix !== 'object' || Array.isArray(args.matrix)) return { error: 'matrix must be a JSON object' };
141
+ return { matrix: args.matrix };
142
+ }
143
+
110
144
  function errorResult(text) {
111
145
  return { content: [{ type: 'text', text: withPointer(text) }], isError: true };
112
146
  }
@@ -569,6 +603,29 @@ const TOOLS = [
569
603
  required: ['pageId', 'title'],
570
604
  },
571
605
  },
606
+ {
607
+ name: 'project_matrix_read',
608
+ description: descriptionFor('project_matrix_read'),
609
+ inputSchema: {
610
+ type: 'object',
611
+ properties: {
612
+ cwd: { type: 'string', description: "Optional: absolute path to the target project. Defaults to the calling session's own project root (SM_PROJECT_ROOT or process.cwd()) when omitted." },
613
+ },
614
+ },
615
+ },
616
+ {
617
+ name: 'project_matrix_write',
618
+ description: descriptionFor('project_matrix_write'),
619
+ inputSchema: {
620
+ type: 'object',
621
+ properties: {
622
+ cwd: { type: 'string', description: "Optional: absolute path to the target project. Defaults to the calling session's own project root (SM_PROJECT_ROOT or process.cwd()) when omitted." },
623
+ matrix: { type: 'object', description: 'The whole competitive feature matrix as a JSON object matching the schema project_matrix_read returns (<= 1MB). Replaces the stored matrix.' },
624
+ matrixPath: { type: 'string', description: 'Absolute path to a local .json file holding the matrix (<= 1MB, parsed as JSON; same rules as matrix). Give exactly one of matrix / matrixPath.' },
625
+ model: { type: 'string', description: 'Optional: id of the model that produced this matrix, recorded with the save.' },
626
+ },
627
+ },
628
+ },
572
629
  {
573
630
  name: 'project_video_write',
574
631
  description: descriptionFor('project_video_write'),
@@ -604,14 +661,14 @@ const TOOLS = [
604
661
  type: 'object',
605
662
  properties: {
606
663
  cwd: { type: 'string', description: "Optional: absolute path to the target project. Defaults to the calling session's own project root (SM_PROJECT_ROOT or process.cwd()) when omitted." },
607
- id: { type: 'string', description: 'Optional: id of an existing macro (already visible to this project) to update. Omit to create a new macro scoped to this project.' },
664
+ id: { type: 'string', description: 'Optional: id of an existing macro (already visible to this project) to update. Omit to create a new macro.' },
608
665
  label: { type: 'string', description: 'Short label shown on the HOT KEYS button.' },
609
666
  agentName: { type: 'string', description: 'Persona to run the macro as (e.g. "builder").' },
610
667
  tag: { type: 'string', description: 'Mission tag for the macro.' },
611
668
  prompt: { type: 'string', description: 'The opening prompt the macro sends. Write input placeholders as {{name}}; each is filled from the matching entry in `inputs` when the macro is pressed.' },
612
- surface: { type: 'string', enum: ['sessions', 'project-home'], description: "Where the macro shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row." },
669
+ surface: { type: 'string', enum: ['sessions', 'project-home'], description: "Where the macro shows: 'sessions' = Sessions HOT KEYS strip; 'project-home' = a tool in Project Home ▸ Tools, shown in every project (only what it generates is per project). A 'project-home' save needs humanRequestQuote and a Session Manager chat session." },
613
670
  projects: { type: 'array', items: { type: 'string' }, description: 'Optional: only ["*"] is accepted, to show the macro in every project. Needs humanRequestQuote and a Session Manager chat session.' },
614
- humanRequestQuote: { type: 'string', description: 'With projects ["*"]: the exact words the human typed in this chat that ask for every/all projects.' },
671
+ humanRequestQuote: { type: 'string', description: "With projects [\"*\"] or surface 'project-home': the exact words the human typed in this chat asking for every project or for a Project Home tool." },
615
672
  inputs: {
616
673
  type: 'array',
617
674
  description: 'Optional input fields the human fills in before the macro runs. Prompt placeholders are written as {{name}}. Omit on update to keep the existing inputs; pass [] to clear them.',
@@ -1031,6 +1088,20 @@ async function handleCallTool(request) {
1031
1088
  const result = await adminRequest('POST', '/admin/project-home/pages/write', body);
1032
1089
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1033
1090
  }
1091
+ if (name === 'project_matrix_read') {
1092
+ const cwd = resolveCwdArg(args);
1093
+ const result = await adminRequest('POST', '/admin/project-home/matrix/read', { cwd });
1094
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1095
+ }
1096
+ if (name === 'project_matrix_write') {
1097
+ const loaded = await resolveJsonArg(args);
1098
+ if (loaded.error) return errorResult(loaded.error);
1099
+ const cwd = resolveCwdArg(args);
1100
+ const body = { cwd, matrix: loaded.matrix };
1101
+ if (typeof args.model === 'string' && args.model) body.model = args.model;
1102
+ const result = await adminRequest('POST', '/admin/project-home/matrix/write', body);
1103
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1104
+ }
1034
1105
  if (name === 'project_video_write') {
1035
1106
  if (!args || typeof args.videoId !== 'string' || !args.videoId || typeof args.title !== 'string' || !args.title
1036
1107
  || typeof args.kind !== 'string' || !args.kind || typeof args.lengthS !== 'number' || !Number.isFinite(args.lengthS)) {
@@ -1056,7 +1127,15 @@ async function handleCallTool(request) {
1056
1127
  if (missing.length > 0) {
1057
1128
  return errorResult(`missing or invalid required argument(s): ${missing.join(', ')}`);
1058
1129
  }
1059
- if (args.projects !== undefined) {
1130
+ // A Project Home tool is shown in every project, so it gets the same
1131
+ // human-session refusal as projects ["*"].
1132
+ if (args.surface === 'project-home') {
1133
+ const refusal = humanSessionRefusal(
1134
+ 'refused: a Project Home tool is shown in every project and is saved only in a Session Manager chat session where the human asked for it. '
1135
+ + 'Say in your final result that the human can add it from Project Home ▸ Tools ▸ Add a tool.',
1136
+ );
1137
+ if (refusal) return refusal;
1138
+ } else if (args.projects !== undefined) {
1060
1139
  const refusal = humanSessionRefusal(
1061
1140
  'refused: a macro shown in every project is saved only in a Session Manager chat session where the human asked for it. '
1062
1141
  + 'Say in your final result that the human can set Show in every project in the macro editor.',
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.130.3",
3
- "gitSha": "88b96e8764d7f1b455f245e1f742952983cb4459",
4
- "gitShortSha": "88b96e87",
2
+ "version": "0.132.0",
3
+ "gitSha": "4930de0b7e7bf78a7a1c00c60c30ac9298458411",
4
+ "gitShortSha": "4930de0b",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-11-08T04:03:29.236Z",
6
+ "builtAt": "2026-11-08T22:44:12.441Z",
7
7
  "dirty": false
8
8
  }
@@ -38,6 +38,7 @@ const sessionsStore = require('./sessionsStore.cjs');
38
38
  const layoutStore = require('./layoutStore.cjs');
39
39
  const billing = require('./usage.cjs');
40
40
  const { probeMcpStatus } = require('./mcpStatus.cjs');
41
+ const { checkConfiguredMcpServer } = require('./lib/mcpToolsProbe.cjs');
41
42
  const logs = require('./logs.cjs');
42
43
  const crashDiagnostics = require('./crashDiagnostics.cjs');
43
44
  // Start the local minidump collector before app-ready (required by Electron).
@@ -593,6 +594,14 @@ ipcMain.handle('app:launch-mode', () => ({
593
594
  // `claude mcp list`. Read-only, single in-flight call — no polling.
594
595
  ipcMain.handle('mcp:status', () => probeMcpStatus());
595
596
 
597
+ // Extensions MCP detail: check ONE configured server on demand (initialize →
598
+ // tools/list, lib/mcpToolsProbe.cjs). The payload only NAMES the server; its
599
+ // config is read from disk in main, so the renderer can't choose what is spawned.
600
+ ipcMain.handle('mcp:check-server', validated(schemas.mcpCheckServer, async (p) => {
601
+ if (p.source === 'project') configMgr.validatePath(p.cwd);
602
+ return checkConfiguredMcpServer(p, { clientVersion: app.getVersion() });
603
+ }));
604
+
596
605
  // The Dashboard's "Agent tools" section (HomeAgentTools): the same catalog data
597
606
  // GET /admin/mcp/catalog serves to external callers, read in-process here so
598
607
  // the renderer never makes a direct HTTP call. Static data, no cwd needed.
@@ -614,6 +623,8 @@ require('./lib/persona-macro/macroJobIpc.cjs').registerMacroJobIpc(ipcMain, {
614
623
  createPrd: (input) => prdCreate.createPrd(input, scheduler.remote),
615
624
  loadJobs: async () => (await require('./lib/scheduler/queueStore.cjs').readMerged()).jobs || [],
616
625
  archivePrd: (slug, cwd) => queueOps.archiveMany([slug], cwd),
626
+ // Durable 'job-not-queued' notice on the Epic when a dispatch fails (PRD 2950).
627
+ appendResponseEventWithReason: promptSessionEvents.appendResponseEventWithReason,
617
628
  });
618
629
  // claudeConfig (lib/claudeConfig.cjs): key-scoped read/patch of Claude's JSON config files.
619
630
  // A successful patch broadcasts `config:changed` so renderer state refreshes.
@@ -15,6 +15,8 @@ const { PERSONA_NAME_RE } = require('./agentLibrary.cjs');
15
15
  const { AgentPersonaSaveSchema, PersonaNameSchema, ProjectCwdSchema } = require('./lib/persona-macro/agentPersonaSchema.cjs');
16
16
  const { MacroSaveSchema, MacroDeleteSchema, MacroSetProjectSchema, MacroRemoveFromProjectSchema, MacroInputSchema } = require('./lib/persona-macro/macroLibrary.cjs');
17
17
  const { MAX_SLOTS } = require('./lib/scheduler/sessionSlots.cjs');
18
+ // Aliased: this file already has a looser, exchanges-only SESSION_ID_RE (Exchanges section).
19
+ const { SESSION_ID_RE: RESTORABLE_SESSION_ID_RE } = require('./lib/epic/restorableSessions.cjs');
18
20
 
19
21
  // ──────────────────────────────────────────── PTY
20
22
  const ptySpawn = z.object({
@@ -235,8 +237,17 @@ const promptSessionsCreateEpic = z.object({
235
237
  // future scripted Epic) composes a full opening prompt.
236
238
  openingPrompt: z.string().max(200000).optional(),
237
239
  sections: z.array(EpicIntakeSectionSchema).max(200).optional(),
240
+ // Restore: adopt this project's existing Claude Code CLI session (a UUID —
241
+ // it becomes a transcript filename) instead of minting a fresh one. Absent =
242
+ // a normal mint; ensureEpic's restore gate decides whether the id may be adopted.
243
+ restoreSessionId: z.string().regex(RESTORABLE_SESSION_ID_RE).optional(),
238
244
  });
239
245
 
246
+ // Renderer entry point for the "Restore a session" picker: this project's CLI
247
+ // sessions no Epic owns yet (lib/epic/restorableSessions.cjs). The handler runs
248
+ // `cwd` through config.cjs's validatePath before any transcript dir is read.
249
+ const promptSessionsListRestorable = z.object({ cwd: z.string().min(1).max(4096) }).strict();
250
+
240
251
  // Renderer entry point for creating an Epic's isolated git worktree
241
252
  // (lib/epic/epicWorktreeMint.cjs) at the proposed->active transition — PRD 1033.
242
253
  const promptSessionsCreateWorktree = z.object({
@@ -682,6 +693,20 @@ const claudeConfigPatch = z.object({
682
693
  keyPath: z.array(z.string().min(1).max(256)).min(1).max(8),
683
694
  value: z.unknown().optional(),
684
695
  }).strict();
696
+ // mcp:check-server — names WHICH configured server to check, never its config:
697
+ // main reads that from disk (lib/mcpToolsProbe.cjs checkConfiguredMcpServer), so
698
+ // the renderer can't make main spawn a command of its choosing. A project server
699
+ // needs its project's absolute cwd, a plugin server its installed key; neither
700
+ // field moves a server of another source.
701
+ const PLUGIN_KEY_RE = /^[a-z0-9][a-z0-9._\-]*@[a-z0-9][a-z0-9._\-]*$/i; // name@marketplace, as in installed_plugins.json
702
+ const mcpCheckServer = z.object({
703
+ source: z.enum(['user', 'project', 'plugin']),
704
+ name: z.string().min(1).max(128),
705
+ cwd: z.string().min(1).max(4096).refine((s) => path.isAbsolute(s), 'cwd must be absolute').optional(),
706
+ pluginKey: z.string().regex(PLUGIN_KEY_RE).max(256).optional(),
707
+ }).strict()
708
+ .refine((p) => p.source !== 'project' || p.cwd !== undefined, 'a project server needs its cwd')
709
+ .refine((p) => p.source !== 'plugin' || p.pluginKey !== undefined, 'a plugin server needs its pluginKey');
685
710
  const macrosSave = MacroSaveSchema;
686
711
  const macrosDelete = MacroDeleteSchema;
687
712
  const macrosSetProject = MacroSetProjectSchema;
@@ -1280,7 +1305,7 @@ const pluginsAbort = z.object({
1280
1305
  }).passthrough();
1281
1306
  const pluginsList = z.object({}).strict();
1282
1307
  const pluginsSetEnabled = z.object({
1283
- key: z.string().regex(/^[a-z0-9][a-z0-9._\-]*@[a-z0-9][a-z0-9._\-]*$/i).max(256),
1308
+ key: z.string().regex(PLUGIN_KEY_RE).max(256),
1284
1309
  enabled: z.boolean(),
1285
1310
  }).strict();
1286
1311
  const pluginsUninstall = z.object({
@@ -1500,6 +1525,7 @@ module.exports = {
1500
1525
  promptSessionsMergeActiveIndex,
1501
1526
  promptSessionsWriteArchive,
1502
1527
  promptSessionsCreateEpic,
1528
+ promptSessionsListRestorable,
1503
1529
  promptSessionsCreateWorktree,
1504
1530
  promptSessionsReopen,
1505
1531
  promptSessionsCwd,
@@ -1532,6 +1558,7 @@ module.exports = {
1532
1558
  agentsDeletePersona,
1533
1559
  claudeConfigRead,
1534
1560
  claudeConfigPatch,
1561
+ mcpCheckServer,
1535
1562
  macrosSave,
1536
1563
  macrosDelete,
1537
1564
  macrosSetProject,
@@ -212,7 +212,32 @@ function withPathLock(lockPath, task) {
212
212
  }
213
213
 
214
214
  /**
215
- * ensureEpic(cwd, { epicId?, goalText, tag?, status?, openingPrompt?, source?, agentType?, model?, effort?, developLoop?, mintAuthority? }) → Promise<{ epicId, prdDir, created }>
215
+ * restoreRefusal(cwd, index, restoreSessionId, mintAuthority, deps) — why
216
+ * ensureEpic must NOT adopt `restoreSessionId` as a new Epic's
217
+ * claudeSessionId, or null when it may. Runs inside ensureEpic's withPathLock
218
+ * task against the index that task just read, so of two mints restoring the
219
+ * same id the second always sees the row the first wrote.
220
+ */
221
+ function restoreRefusal(cwd, index, restoreSessionId, mintAuthority, deps) {
222
+ if (mintAuthority !== MINT_AUTHORITY_NEW_EPIC_UI) {
223
+ return "restoring a Claude Code session as an Epic is the New Epic UI's alone (mintAuthority "
224
+ + `'${MINT_AUTHORITY_NEW_EPIC_UI}'), not '${mintAuthority}'`;
225
+ }
226
+ const owner = Object.entries(index.sessions)
227
+ .find(([, s]) => s && typeof s === 'object' && s.claudeSessionId === restoreSessionId);
228
+ if (owner) {
229
+ return `claude session ${restoreSessionId} already belongs to Epic ${owner[0]} in this project `
230
+ + '(EPIC : claude-session is 1:1)';
231
+ }
232
+ // Lazy: restorableSessions.cjs requires this module at load time, so a
233
+ // top-level require here would hand it a half-built exports object.
234
+ const { checkRestorableSessionSync } = require('./restorableSessions.cjs');
235
+ const check = checkRestorableSessionSync(cwd, restoreSessionId, deps);
236
+ return check.ok ? null : check.message;
237
+ }
238
+
239
+ /**
240
+ * ensureEpic(cwd, { epicId?, goalText, tag?, status?, openingPrompt?, source?, agentType?, model?, effort?, developLoop?, mintAuthority?, restoreSessionId? }, deps?) → Promise<{ epicId, prdDir, created }>
216
241
  *
217
242
  * Two behaviors, and only two:
218
243
  * - JOIN (the default, for every automated caller): `epicId` names an Epic
@@ -222,6 +247,15 @@ function withPathLock(lockPath, task) {
222
247
  * creates a brand-new Epic. No similarity/keyword matching runs first — the
223
248
  * human asked for a new Epic, so they get a new Epic.
224
249
  *
250
+ * RESTORE is a MINT whose `restoreSessionId` (default null) names an existing
251
+ * Claude Code CLI session: the new Epic adopts it as its claudeSessionId and is
252
+ * marked `restoredSession: true`, so a human can carry a plain-CLI conversation
253
+ * on as an Epic. Any non-null value is a restore request; it is refused unless
254
+ * mintAuthority is MINT_AUTHORITY_NEW_EPIC_UI, no Epic of this project already
255
+ * owns the id (EPIC : claude-session stays 1:1), and restorableSessions.cjs's
256
+ * checkRestorableSessionSync finds the transcript under this project's own
257
+ * `~/.claude/projects/<encodeCwd(cwd)>/` dir (`deps.homeDir` moves HOME for tests).
258
+ *
225
259
  * Every Epic is BORN 'proposed'; `status` defaults to it and the mint branch
226
260
  * rejects any other value outright (fail-closed, mirroring opsOwnership.cjs's
227
261
  * assertOpsWrite). Activation ('proposed' → 'active') happens exactly once, in
@@ -231,7 +265,7 @@ function withPathLock(lockPath, task) {
231
265
  * The Epic's id doubles as its directory name under scheduler/epics/, so the
232
266
  * PromptSession ↔ on-disk Epic mapping is 1:1 with no lookup table.
233
267
  */
234
- function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'proposed', openingPrompt = null, sections = null, source = null, agentType = null, model = null, effort = null, developLoop = null, mintAuthority = null } = {}, deps = {}) {
268
+ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'proposed', openingPrompt = null, sections = null, source = null, agentType = null, model = null, effort = null, developLoop = null, mintAuthority = null, restoreSessionId = null } = {}, deps = {}) {
235
269
  if (!cwd || typeof cwd !== 'string') throw new Error('ensureEpic: cwd is required');
236
270
  // A relative cwd (e.g. a caller passing '.') would otherwise get stored
237
271
  // verbatim on the minted Epic's `cwd` field — the renderer's EpicsWorkspace
@@ -309,15 +343,28 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
309
343
  }
310
344
  }
311
345
 
346
+ // RESTORE GATE (see restoreRefusal and the JSDoc above). An empty or
347
+ // malformed id is refused, never quietly swapped for a fresh session.
348
+ const restoring = restoreSessionId !== null;
349
+ if (restoring) {
350
+ const reason = restoreRefusal(cwd, index, restoreSessionId, mintAuthority, deps);
351
+ if (reason) {
352
+ appendAuditEvent('epic_mint_refused', { cwd, epicId: null, status, reason });
353
+ throw new Error(`ensureEpic: ${reason}`);
354
+ }
355
+ }
356
+
312
357
  const epicId = `${slugify(goalText)}-${crypto.randomUUID().slice(0, 8)}`;
313
358
  const now = new Date().toISOString();
314
359
  const session = {
315
360
  id: epicId,
316
361
  cwd,
317
362
  goalText: String(goalText || ''),
318
- // Independently minted, never shared with a SessionTab — same invariant
319
- // as renderer-created PromptSessions (state/promptSessions.ts).
320
- claudeSessionId: crypto.randomUUID(),
363
+ // A fresh UUID, never shared with a SessionTab. A restored Epic instead
364
+ // adopts an existing CLI session that no Epic or SessionTab owns (the
365
+ // RESTORE GATE above refuses an id any Epic of this project holds).
366
+ claudeSessionId: restoring ? restoreSessionId : crypto.randomUUID(),
367
+ ...(restoring ? { restoredSession: true } : {}),
321
368
  // 'proposed' files the Epic WITHOUT starting it — nothing runs until the
322
369
  // human presses Approve & start in the Epics workspace.
323
370
  status,
@@ -386,7 +433,15 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
386
433
 
387
434
  // Every mint is logged — the trace-back point for "who created this Epic"
388
435
  // (see auditLog.cjs).
389
- appendAuditEvent('epic_mint', { cwd, epicId, status, tag: tag ?? null, goalText: session.goalText, source: source ?? null });
436
+ appendAuditEvent('epic_mint', {
437
+ cwd,
438
+ epicId,
439
+ status,
440
+ tag: tag ?? null,
441
+ goalText: session.goalText,
442
+ source: source ?? null,
443
+ ...(restoring ? { restoredSession: true } : {}),
444
+ });
390
445
 
391
446
  const prdDir = resolveEpicPrdWriteDir(cwd, epicId);
392
447
  fs.mkdirSync(prdDir, { recursive: true });
@@ -19,13 +19,23 @@
19
19
  * isolation — its outstanding diff is carried into the fresh worktree
20
20
  * instead (gitWorktree.cjs's createWorktree).
21
21
  *
22
+ * A restored Epic (`restoredSession: true`, minted around an existing CLI
23
+ * session) is never isolated, at approve or reopen: its transcript lives under
24
+ * the project checkout's ~/.claude/projects encoding and its history (and any
25
+ * uncommitted work) refers to the main checkout, so planEpicSpawn resumes it
26
+ * from the project cwd — a worktree would sit unused while its queue row
27
+ * falsely showed isolation.
28
+ *
22
29
  * Mirrors promptSessionsCreateEpic.cjs's shape: `validatePath(cwd)` closes
23
30
  * the same "arbitrary renderer-supplied cwd" gap that handler documents,
24
31
  * since this is likewise reachable from the renderer over IPC.
25
32
  */
26
33
 
27
34
  const path = require('node:path');
28
- const { createEpicWorktree } = require('../git/gitWorktree.cjs');
35
+ // Called through the module object (not destructured) so tests can observe
36
+ // and substitute createEpicWorktree — gitWorktree.cjs does the same for
37
+ // captureAndCarryBaseDiff.
38
+ const gitWorktree = require('../git/gitWorktree.cjs');
29
39
  const { validatePath } = require('../../config.cjs');
30
40
 
31
41
  /**
@@ -33,8 +43,9 @@ const { validatePath } = require('../../config.cjs');
33
43
  *
34
44
  * Returns the `worktree` field shape (`{ dir, branch, baseCwd, status,
35
45
  * carriedPaths }`) ready to persist onto the Epic record on success, or
36
- * `null` on any failure — createEpicWorktree/createWorktree never throw, so
37
- * this never does either.
46
+ * `null` for a restored Epic or on any failure — createEpicWorktree/
47
+ * createWorktree never throw, and neither does isRestoredEpic, so this
48
+ * never does either.
38
49
  */
39
50
  /** In-flight mints, keyed by resolved cwd + epicId (turn 1 awaits these — awaitPendingEpicWorktree). */
40
51
  const pendingMints = new Map();
@@ -83,8 +94,38 @@ function __resetPendingForTests() {
83
94
  pendingMints.clear();
84
95
  }
85
96
 
97
+ const isFlaggedRestored = (record) => !!record && typeof record === 'object' && record.restoredSession === true;
98
+
99
+ /**
100
+ * isRestoredEpic(cwd, epicId) → boolean. Reads the Epic's row from
101
+ * active-index.json (approve: the proposed row is there). When the index has
102
+ * no row, reads the Epic's own prompt-sessions/<epicId>.json instead
103
+ * (reopen: completion tombstones the Epic out of the index, and epicReopen's
104
+ * provisionWorktree mints before writing the row back — the archive holds
105
+ * the record under `session`, a live mirror holds it flat). Never throws —
106
+ * an unreadable record proceeds as today (not restored).
107
+ */
108
+ function isRestoredEpic(cwd, epicId) {
109
+ try {
110
+ // Lazy: requiring epicMint.cjs at load would risk a require cycle.
111
+ const { readActiveIndex } = require('./epicMint.cjs');
112
+ const { sessions } = readActiveIndex(cwd);
113
+ if (Object.prototype.hasOwnProperty.call(sessions, epicId)) return isFlaggedRestored(sessions[epicId]);
114
+ const { epicMirrorPath } = require('./epicStatusMirror.cjs');
115
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
116
+ const mirror = readJsonOrSync(epicMirrorPath(cwd, epicId), null);
117
+ return isFlaggedRestored(mirror) || isFlaggedRestored(mirror && mirror.session);
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
122
+
86
123
  async function mintEpicWorktree(cwd, epicId) {
87
- const result = await createEpicWorktree({ cwd, epicId });
124
+ if (isRestoredEpic(cwd, epicId)) {
125
+ console.log(`[epicWorktreeMint] ${epicId}: not isolated (restored-session)`);
126
+ return null;
127
+ }
128
+ const result = await gitWorktree.createEpicWorktree({ cwd, epicId });
88
129
  if (!result.ok) {
89
130
  console.log(`[epicWorktreeMint] ${epicId}: not isolated (${result.reason})`);
90
131
  return null;
@@ -11,13 +11,18 @@
11
11
  * "own file, own register*Handlers export, wired from index.cjs" shape for
12
12
  * the neighboring active-index merge IPC) rather than growing epicMint.cjs
13
13
  * itself, since this is IPC-registration plumbing, not Epic-minting logic.
14
+ *
15
+ * Also home to 'promptSessions:list-restorable', the New Session card's
16
+ * "Restore a session" picker, whose pick comes back as create-epic's
17
+ * `restoreSessionId`.
14
18
  */
15
19
 
16
20
  const { ensureEpic, readActiveIndex, MINT_AUTHORITY_NEW_EPIC_UI } = require('./epicMint.cjs');
21
+ const { listRestorableSessions } = require('./restorableSessions.cjs');
17
22
  const { validatePath } = require('../../config.cjs');
18
23
 
19
24
  /**
20
- * createEpicViaIpc(cwd, { goalText, tag?, agentType?, source? }) → Promise<{ epicId, session }>
25
+ * createEpicViaIpc(cwd, { goalText, tag?, agentType?, source?, restoreSessionId? }) → Promise<{ epicId, session }>
21
26
  *
22
27
  * THE one Epic-creation path (epicMint.cjs's SINGLE-CREATOR LAW): this handler
23
28
  * holds `MINT_AUTHORITY_NEW_EPIC_UI`, the token that unlocks ensureEpic's mint
@@ -40,8 +45,12 @@ const { validatePath } = require('../../config.cjs');
40
45
  * filesystem location — the same boundary every other renderer-facing path
41
46
  * IPC (config:read-json/write-json, lib/epic/activeIndexMerge.cjs's own merge) is
42
47
  * already required to pass through.
48
+ *
49
+ * `restoreSessionId` (absent = a normal mint) asks ensureEpic to adopt that
50
+ * existing Claude Code CLI session as the new Epic's claudeSessionId. ensureEpic's
51
+ * restore gate decides; a refused id rejects the call, never mints a fresh session.
43
52
  */
44
- async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections } = {}) {
53
+ async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections, restoreSessionId } = {}) {
45
54
  validatePath(cwd);
46
55
  const { epicId } = await ensureEpic(cwd, {
47
56
  goalText,
@@ -53,6 +62,7 @@ async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort,
53
62
  source,
54
63
  openingPrompt,
55
64
  sections,
65
+ restoreSessionId,
56
66
  mintAuthority: MINT_AUTHORITY_NEW_EPIC_UI,
57
67
  status: 'proposed',
58
68
  });
@@ -60,14 +70,31 @@ async function createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort,
60
70
  return { epicId, session: index.sessions[epicId] };
61
71
  }
62
72
 
73
+ /**
74
+ * listRestorableViaIpc(cwd) → Promise<RestorableList>
75
+ *
76
+ * This project's Claude Code CLI sessions that no Epic owns yet, newest first
77
+ * (restorableSessions.cjs's listRestorableSessions). `cwd` is renderer-supplied,
78
+ * so it passes the same validatePath boundary as createEpicViaIpc before any
79
+ * transcript dir is read; an out-of-bounds cwd rejects.
80
+ */
81
+ async function listRestorableViaIpc(cwd) {
82
+ validatePath(cwd);
83
+ return listRestorableSessions({ cwd });
84
+ }
85
+
63
86
  function registerPromptSessionsCreateEpicHandlers() {
64
87
  const { ipcMain } = require('electron');
65
88
  const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
66
89
  ipcMain.handle(
67
90
  'promptSessions:create-epic',
68
- v(s.promptSessionsCreateEpic, ({ cwd, goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections }) =>
69
- createEpicViaIpc(cwd, { goalText, tag, agentType, model, effort, developLoop, source, openingPrompt, sections })),
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 })),
93
+ );
94
+ ipcMain.handle(
95
+ 'promptSessions:list-restorable',
96
+ v(s.promptSessionsListRestorable, ({ cwd }) => listRestorableViaIpc(cwd)),
70
97
  );
71
98
  }
72
99
 
73
- module.exports = { createEpicViaIpc, registerPromptSessionsCreateEpicHandlers };
100
+ module.exports = { createEpicViaIpc, listRestorableViaIpc, registerPromptSessionsCreateEpicHandlers };