claude-code-session-manager 0.138.0 → 0.139.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 (91) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-CgDhqrsU.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-CkhTvG7C.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/{index-CgCxpunJ.js → index-C-d0DCre.js} +523 -515
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +469 -450
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +2 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +22 -2
  33. package/src/main/ipcSchemas.cjs +122 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  37. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  38. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  39. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  40. package/src/main/lib/epic/epicSettle.cjs +1 -1
  41. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  42. package/src/main/lib/epic/externalRef.cjs +37 -0
  43. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  44. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  45. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  46. package/src/main/lib/externalContract.cjs +111 -0
  47. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  48. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  49. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  50. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  51. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  52. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  53. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  54. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +120 -2
  56. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  57. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  58. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  59. package/src/main/lib/historyRollup.cjs +32 -5
  60. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  61. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  62. package/src/main/lib/promptSessionSchema.cjs +4 -0
  63. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  64. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  65. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  66. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  67. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  68. package/src/main/scheduler.cjs +29 -0
  69. package/src/main/templates/PRD_AUTHORING.md +1 -0
  70. package/src/main/transcripts.cjs +62 -7
  71. package/src/main/webRemote.cjs +122 -18
  72. package/src/preload/api.d.ts +71 -8
  73. package/src/preload/apiSurface.cjs +7 -0
  74. package/src/preload/apiSurface.json +408 -83
  75. package/src/preload/index.cjs +15 -3
  76. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  77. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  78. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  79. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  80. package/dist/assets/History-BwO3coo4.js +0 -2
  81. package/dist/assets/Library-BDV69fSe.js +0 -32
  82. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  83. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  84. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  85. package/dist/assets/Settings-COT34hBF.js +0 -2
  86. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  87. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  88. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  89. package/dist/assets/Toggle-CENi19iK.js +0 -1
  90. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  91. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
@@ -15,9 +15,11 @@
15
15
  * toolCallCount, toolBreakdown, errorCount, sessionCount are populated;
16
16
  * token fields are 0. One per (date, projectDir).
17
17
  * - per-model line (modelId === a real model id): inputTokens,
18
- * outputTokens, cacheReadTokens, cacheCreationTokens are populated; the
19
- * rest are 0/empty. Cost is NOT stored — it's computed at read time from
20
- * MODEL_PRICING so a pricing fix retroactively corrects displayed cost.
18
+ * outputTokens, cacheReadTokens, cacheCreationTokens and (since v4)
19
+ * cacheCreation1hTokens — the 1-hour part of cacheCreationTokens — are
20
+ * populated; the rest are 0/empty. Cost is NOT stored — it's computed at
21
+ * read time from lib/claude/modelPricing.cjs so a pricing fix
22
+ * retroactively corrects displayed cost.
21
23
  * - finalized marker (projectDir === '', modelId === FINALIZED_MODEL_ID):
22
24
  * one per date, carries only `finalizedAt`. A date only counts as closed
23
25
  * (safe to trust the rollup with no live re-scan) once this exists.
@@ -35,11 +37,18 @@ const TOTALS_MODEL_ID = '';
35
37
  const FINALIZED_MODEL_ID = '__finalized__';
36
38
  const FINALIZED_PROJECT_ID = '';
37
39
  // Bumped when a bucket/finalized-marker line's shape changes in a way that
38
- // requires re-deriving it from transcripts (v1 → v2 added `activeMinutes`).
40
+ // requires re-deriving it from transcripts (v1 → v2 added `activeMinutes`;
41
+ // v2 → v3 counts each model call once — earlier versions over-counted calls,
42
+ // so a day still finalized at v<3 reads high; v3 → v4 records 1-hour cache
43
+ // writes as cacheCreation1hTokens on per-model lines).
39
44
  // isDateFinalized() gates on this so old-shape finalized days get re-scanned
40
45
  // by the existing finalizeClosedDays() budget/resume loop instead of a new
41
46
  // migration path.
42
- const ROLLUP_VERSION = 2;
47
+ const ROLLUP_VERSION = 4;
48
+ // The version that fixed the call over-count. A day finalized below it reads
49
+ // high and is reported as legacy; a day finalized at/above it but below
50
+ // ROLLUP_VERSION has correct counts and only lacks a newer field.
51
+ const OVERCOUNT_FIX_VERSION = 3;
43
52
 
44
53
  function rollupKey(date, projectDir, modelId) {
45
54
  return `${date}|${projectDir}|${modelId}`;
@@ -97,6 +106,22 @@ function isDateFinalized(mergedMap, date) {
97
106
  return (bucket.v ?? 1) >= ROLLUP_VERSION;
98
107
  }
99
108
 
109
+ /**
110
+ * Sorted dates whose finalized marker was written below OVERCOUNT_FIX_VERSION
111
+ * (no `v` counts as v1). These are days the finalize pass could not recount —
112
+ * typically because their transcripts are gone — so their stored numbers come
113
+ * from the over-counting scheme. A date with no marker is not legacy.
114
+ */
115
+ function legacyFinalizedDates(mergedMap) {
116
+ const dates = [];
117
+ for (const bucket of mergedMap.values()) {
118
+ if (bucket.projectDir !== FINALIZED_PROJECT_ID || bucket.modelId !== FINALIZED_MODEL_ID) continue;
119
+ if (!bucket.finalizedAt) continue;
120
+ if ((bucket.v ?? 1) < OVERCOUNT_FIX_VERSION) dates.push(bucket.date);
121
+ }
122
+ return dates.sort();
123
+ }
124
+
100
125
  /**
101
126
  * Append bucket entries (append-only) to the rollup file, then compact
102
127
  * (dedupe + rewrite) if the file has grown past COMPACT_THRESHOLD_BYTES.
@@ -138,10 +163,12 @@ module.exports = {
138
163
  FINALIZED_MODEL_ID,
139
164
  FINALIZED_PROJECT_ID,
140
165
  ROLLUP_VERSION,
166
+ OVERCOUNT_FIX_VERSION,
141
167
  rollupKey,
142
168
  mergeRollupLines,
143
169
  readRollup,
144
170
  isDateFinalized,
171
+ legacyFinalizedDates,
145
172
  appendRollupDays,
146
173
  compact,
147
174
  };
@@ -23,12 +23,17 @@ const { z } = require('zod');
23
23
 
24
24
  const CatalogEntrySchema = z.object({
25
25
  name: z.string().min(1),
26
- group: z.enum(['scheduler', 'chat', 'feedback', 'help', 'project-home', 'macros', 'customer-feedback']),
26
+ group: z.enum(['scheduler', 'chat', 'feedback', 'help', 'project-home', 'macros', 'customer-feedback', 'epics', 'agents']),
27
27
  purpose: z.string().min(1),
28
+ summary: z.string().min(10).max(90).regex(/^[^|`\n]+$/),
28
29
  whenToUse: z.string().min(1),
29
30
  whenNotToUse: z.string().min(1),
30
31
  exampleArgs: z.record(z.string(), z.unknown()),
31
32
  notes: z.string().nullable(),
33
+ // Arg groups the handler refuses a call without ('exactly one of'). README
34
+ // table only — never enters composeDescription, and never becomes a
35
+ // oneOf/anyOf in inputSchema (the Claude API refuses those at top level).
36
+ requiredOneOf: z.array(z.array(z.string()).min(2)).optional(),
32
37
  });
33
38
 
34
39
  const RecipeSchema = z.object({
@@ -42,6 +47,7 @@ const MCP_TOOL_CATALOG = [
42
47
  name: 'scheduler_reset_job',
43
48
  group: 'scheduler',
44
49
  purpose: "Reset a stuck scheduler job by slug via the session-manager app's admin API.",
50
+ summary: 'Reset a stuck job so the scheduler runs it again.',
45
51
  whenToUse: 'Use after diagnosing why a job is stuck (e.g. via scheduler_get_prd/scheduler_list_jobs) and deciding it should re-run from pending.',
46
52
  whenNotToUse: 'Do not use as a first move on a "needs_review" job without reading it first — reset just clears status, it does not answer the question the job raised.',
47
53
  exampleArgs: { slug: 'add-mcp-tool-catalog', force: false },
@@ -51,6 +57,7 @@ const MCP_TOOL_CATALOG = [
51
57
  name: 'scheduler_pause',
52
58
  group: 'scheduler',
53
59
  purpose: "Pause NEW job dispatch for every project on this machine (machine-wide, not per-repo) via the session-manager app's admin API.",
60
+ summary: 'Pause new job starts for every project on this machine.',
54
61
  whenToUse: 'Use only when the human asks you to stop dispatch everywhere, or for a machine-wide emergency. Pass a `reason`. Running jobs are never killed.',
55
62
  whenNotToUse: "NEVER use it to protect one repo's git/branch state or a single Epic's work — it freezes every project's scheduler. Do not use it to cancel a running job (use scheduler_cancel_job) or as a workaround for a stuck queue.",
56
63
  exampleArgs: { reason: 'machine-wide emergency: disk full' },
@@ -60,6 +67,7 @@ const MCP_TOOL_CATALOG = [
60
67
  name: 'scheduler_resume',
61
68
  group: 'scheduler',
62
69
  purpose: "Clear any scheduler pause (manual or automatic) via the session-manager app's admin API.",
70
+ summary: 'Lift a scheduler pause so jobs start again.',
63
71
  whenToUse: 'Use to restart dispatch after scheduler_pause, or to lift an auto-pause you have judged stale.',
64
72
  whenNotToUse: 'Do not use to retry a parked needs_review job — that is scheduler_reset_job.',
65
73
  exampleArgs: {},
@@ -69,6 +77,7 @@ const MCP_TOOL_CATALOG = [
69
77
  name: 'scheduler_list_jobs',
70
78
  group: 'scheduler',
71
79
  purpose: "List scheduler jobs via the session-manager app's admin API.",
80
+ summary: 'List queued, running and finished jobs on this machine.',
72
81
  whenToUse: 'Use for a quick overview of live queue-row status (pending/running/completed/failed/needs_review) across the machine.',
73
82
  whenNotToUse: 'For PRD content (frontmatter/body) rather than just job status, or for filtering by cwd/Epic, use scheduler_list_prds instead.',
74
83
  exampleArgs: {},
@@ -110,6 +119,7 @@ const MCP_TOOL_CATALOG = [
110
119
  + 'or folders this PRD may change; The scheduler never runs two PRDs with overlapping files at once '
111
120
  + '(dispatch holds the later one), so `dependsOn` is for real output or order dependencies, not for '
112
121
  + 'avoiding file clashes.',
122
+ summary: 'Queue one PRD (a written work order) in an Epic a human approved.',
113
123
  whenToUse: 'Use whenever new work should be queued into an already-approved Epic — this is the /develop path.',
114
124
  whenNotToUse: 'TWO DISTINCT FAILURE MODES if this tool is not usable — do not conflate them: '
115
125
  + '(a) this tool call is PRESENT in your tool list but ERRORS — NEVER hand-write a PRD file. '
@@ -145,6 +155,7 @@ const MCP_TOOL_CATALOG = [
145
155
  + 'any advisory warnings. Like scheduler_create_prd it only writes files; the queue rows are derived by the '
146
156
  + 'next reconcile pass. All entries must resolve to the same project and Epic; top-level cwd, sourcePromptId '
147
157
  + 'and origin fields are forwarded the same way as scheduler_create_prd.',
158
+ summary: 'Queue a whole plan of PRDs in one all-or-nothing call.',
148
159
  whenToUse: 'Use to queue a whole plan at once, validate PRD included: dependsOn may name other entries of the same call by bare slug (earlier or later), so a chain needs no ordering of calls.',
149
160
  whenNotToUse: 'Do not use for a single PRD — use scheduler_create_prd. Not callable from inside a headless scheduled job (same refusal as scheduler_create_prd). If the app is not running, stop and ask the human to start it; never hand-write PRD files.',
150
161
  exampleArgs: {
@@ -172,6 +183,7 @@ const MCP_TOOL_CATALOG = [
172
183
  + 'limit 100, max 500) sorted by slug ascending — check `hasMore`/`total` in the response before assuming you '
173
184
  + "received every PRD; page further with `offset`. Default fields are compact (no parallelGroup/estimateMinutes/"
174
185
  + 'sourcePromptId/epicId/archivedStatus) — pass fields:"full" to restore them.',
186
+ summary: 'List PRDs and their job status, by project, Epic or status.',
175
187
  whenToUse: 'Use to survey PRDs by project/Epic/status before deciding which one to read, update, reset, or archive.',
176
188
  whenNotToUse: 'Do not assume a page without `hasMore` is the full result set without checking `total` — page further with `offset` first.',
177
189
  exampleArgs: { cwd: '/home/bilko/Projects/session-manager', status: 'needs_review' },
@@ -182,6 +194,7 @@ const MCP_TOOL_CATALOG = [
182
194
  group: 'scheduler',
183
195
  purpose: "THE ONLY SUPPORTED WAY to read one PRD's full body + parsed frontmatter (live or archived) via the "
184
196
  + "session-manager app's admin API.",
197
+ summary: 'Read one PRD in full, with its frontmatter.',
185
198
  whenToUse: 'Use before editing/resetting a PRD, or to answer what a needs_review job actually asked.',
186
199
  whenNotToUse: 'For a fleet-wide overview instead of one PRD, use scheduler_list_prds.',
187
200
  exampleArgs: { slug: 'add-mcp-tool-catalog' },
@@ -198,6 +211,7 @@ const MCP_TOOL_CATALOG = [
198
211
  + 'Patching dependsOn to a non-empty array replaces it wholesale (validated against existing PRD slugs, '
199
212
  + 'same resolver scheduler_create_prd uses); patching it to an explicit empty array CLEARS the dependency — '
200
213
  + 'the safe way to fix a wrong dependsOn without archiving (which marks the PRD completed and wrongly frees its dependents).',
214
+ summary: 'Edit a PRD that has not run yet or has stopped.',
201
215
  whenToUse: 'Use to fix a PRD\'s spec before it runs, or to fix a parked (needs_review or failed) or skipped PRD before you reset it with scheduler_reset_job.',
202
216
  whenNotToUse: 'Do not use on a running or completed job. Do not reset first and edit second: the reset job can start before the edit lands.',
203
217
  exampleArgs: { slug: 'add-mcp-tool-catalog', frontmatter: { estimateMinutes: 8 } },
@@ -208,6 +222,7 @@ const MCP_TOOL_CATALOG = [
208
222
  group: 'scheduler',
209
223
  purpose: "THE ONLY SUPPORTED WAY to archive one or more PRDs (move to prds-archived/) via the session-manager "
210
224
  + "app's admin API.",
225
+ summary: 'Archive PRDs that are done or no longer needed.',
211
226
  whenToUse: 'Use once a batch of PRDs is done and should stop showing up in default (live) listings.',
212
227
  whenNotToUse: 'Do not archive a PRD you still expect to reset/re-run — archived PRDs are not part of the live scheduling loop.',
213
228
  exampleArgs: { slugs: ['add-mcp-tool-catalog'] },
@@ -222,6 +237,7 @@ const MCP_TOOL_CATALOG = [
222
237
  + '(completed/failed/needs_review) — nothing to cancel. A cancelled running job\'s commits are never landed on '
223
238
  + 'the base branch; they stay on the job branch, reported in the result as landed:false plus '
224
239
  + 'jobBranch/jobBranchSha.',
240
+ summary: 'Cancel a job that has not finished.',
225
241
  whenToUse: 'Use to stop a running or pending job that should not continue (e.g. it was queued in error, or scope changed underneath it).',
226
242
  whenNotToUse: 'Do not use on an already-terminal job (completed/failed/needs_review) — use scheduler_reset_job if it should run again.',
227
243
  exampleArgs: { slug: 'add-mcp-tool-catalog' },
@@ -232,6 +248,7 @@ const MCP_TOOL_CATALOG = [
232
248
  group: 'scheduler',
233
249
  purpose: "THE ONLY SUPPORTED WAY to rewrite a PRD's parallelGroup and/or estimateMinutes frontmatter (and, if "
234
250
  + "parallelGroup changes, its NN- filename prefix) via the session-manager app's admin API.",
251
+ summary: "Change a PRD's group number or time estimate.",
235
252
  whenToUse: 'Use to correct an estimate or renumber a PRD file after it was created.',
236
253
  whenNotToUse: 'Do not use parallelGroup as an ordering/dependency barrier — it is only a unique-per-PRD display hint; use dependsOn on scheduler_create_prd/scheduler_update_prd for real ordering.',
237
254
  exampleArgs: { items: [{ slug: 'add-mcp-tool-catalog', estimateMinutes: 10 }] },
@@ -243,6 +260,7 @@ const MCP_TOOL_CATALOG = [
243
260
  purpose: "Push a prompt into an already-open tab's chat queue via the session-manager app's admin "
244
261
  + 'API. The renderer resolves the tab (must currently be open) and runs the prompt through '
245
262
  + 'the same queued-vs-immediate path as a manual send.',
263
+ summary: 'Send a prompt to a session tab that is already open.',
246
264
  whenToUse: 'Use to programmatically continue a conversation in a tab that is already open in the running app.',
247
265
  whenNotToUse: 'Do not use to start new work in a project you are not already chatting in — that is /develop (scheduler_create_prd) or feedback_open_session.',
248
266
  exampleArgs: { tabId: 'a1b2c3d4-tab-id', prompt: 'Please continue with the next step.' },
@@ -254,6 +272,7 @@ const MCP_TOOL_CATALOG = [
254
272
  group: 'feedback',
255
273
  purpose: 'List the OTHER projects on this machine that can receive feedback (i.e. that Session Manager '
256
274
  + 'already manages — they have a session-manager-operations/ directory).',
275
+ summary: 'List the other projects on this machine that can take feedback.',
257
276
  whenToUse: "Call this FIRST when you need the exact `toCwd` for feedback_open_session and are not certain of it — never guess a path.",
258
277
  whenNotToUse: 'A project missing from this list has simply never been opened in Session Manager; ask the human to open it once rather than inventing a path.',
259
278
  exampleArgs: {},
@@ -266,6 +285,7 @@ const MCP_TOOL_CATALOG = [
266
285
  + "PROPOSED session in the receiving project's own Sessions queue, carrying your report as its "
267
286
  + 'opening prompt and stamped with where it came from. Session Manager performs the cross-folder '
268
287
  + 'write; you never write another project\'s files yourself.',
288
+ summary: 'Hand a finding to another project as a proposed session there.',
269
289
  whenToUse: 'Use when work in this project surfaces something that is genuinely another project\'s to fix. '
270
290
  + 'Write for a human who must approve it and has never seen your project. Lead with WHY: `motivation` '
271
291
  + 'in the originating human\'s terms. Then give the full `plan` (required for tag "feature") and '
@@ -311,6 +331,7 @@ const MCP_TOOL_CATALOG = [
311
331
  purpose: 'Answer the project that asked. Only for a session that was opened by ANOTHER project\'s '
312
332
  + 'feedback_open_session: the reply lands in the Epic that asked — as an event on its chain plus its '
313
333
  + 'next chat prompt — not as a new proposed session.',
334
+ summary: 'Answer the project that sent this session its feedback.',
314
335
  whenToUse: 'Use once the work the other project asked for is verified (outcome "done"), or when you are '
315
336
  + 'blocked or need an answer from it (outcome "blocked" / "question"). Send "done" only after the work '
316
337
  + 'is verified — name the commit or version in the message.',
@@ -333,6 +354,7 @@ const MCP_TOOL_CATALOG = [
333
354
  purpose: "ALIAS of project_page_write for the Overview page: write this project's Project Home Overview page — ONE self-contained HTML document — to "
334
355
  + "session-manager-operations/project-pages/knowledge/overview/ via the session-manager app's admin API. "
335
356
  + 'Prefer project_page_write for any new knowledge page.',
357
+ summary: 'Write the Overview page of Project Home (same as project_page_write).',
336
358
  whenToUse: 'Use when asked to generate or refresh the project home Overview page. Compose the whole page yourself '
337
359
  + '(inline <style> only — scripts never run in a page; data: URIs for assets) from what is really true about the project, then '
338
360
  + 'pass the full document as `html`.',
@@ -344,9 +366,11 @@ const MCP_TOOL_CATALOG = [
344
366
  },
345
367
  {
346
368
  name: 'project_page_write',
369
+ requiredOneOf: [['html', 'htmlPath']],
347
370
  group: 'project-home',
348
371
  purpose: "Write one knowledge page for this project's Project Home — ONE self-contained HTML document identified by `pageId` — "
349
372
  + "via the session-manager app's admin API. Writing an existing pageId replaces that page.",
373
+ summary: 'Write one HTML knowledge page for Project Home.',
350
374
  whenToUse: 'Use when asked to document a topic of the project as a page (architecture, how-to, status). Compose the whole page yourself '
351
375
  + 'with inline <style> only — scripts never run in a page — from what is really true about the project, then pass it as `html` '
352
376
  + 'or, for a large document, write it to a local .html file and pass its absolute path as `htmlPath`.',
@@ -367,6 +391,7 @@ const MCP_TOOL_CATALOG = [
367
391
  group: 'project-home',
368
392
  purpose: "Load this project's saved competitive feature matrix (session-manager-operations/project-pages/matrix/matrix.json) "
369
393
  + "together with its JSON Schema, via the session-manager app's admin API — the warm start for a competitive-analysis run.",
394
+ summary: 'Read the saved competitor feature matrix and its schema.',
370
395
  whenToUse: 'Call FIRST in a competitive-analysis run, before any research: start from the saved products, groups and features '
371
396
  + 'instead of a cold start, and shape every edit to the returned `schema`. `matrix` is null when none has been saved yet.',
372
397
  whenNotToUse: 'Do not use to save — use project_matrix_write. Do not read matrix.json from disk yourself: '
@@ -377,9 +402,11 @@ const MCP_TOOL_CATALOG = [
377
402
  },
378
403
  {
379
404
  name: 'project_matrix_write',
405
+ requiredOneOf: [['matrix', 'matrixPath']],
380
406
  group: 'project-home',
381
407
  purpose: "Save this project's competitive feature matrix — ONE JSON object matching the schema project_matrix_read returns — "
382
408
  + "via the session-manager app's admin API. Each call replaces the whole stored matrix.",
409
+ summary: 'Save the competitor feature matrix as one JSON object.',
383
410
  whenToUse: 'Use once, at the end of a competitive-analysis run, to save the finished matrix. Build the whole object from '
384
411
  + 'project_matrix_read\'s result plus what your research really found, then pass it as `matrix` or — preferred for a large '
385
412
  + 'matrix — write it to a local .json file and pass its absolute path as `matrixPath`. Pass `model` to record which model wrote it.',
@@ -392,9 +419,11 @@ const MCP_TOOL_CATALOG = [
392
419
  },
393
420
  {
394
421
  name: 'project_video_write',
422
+ requiredOneOf: [['html', 'htmlPath']],
395
423
  group: 'project-home',
396
424
  purpose: "Write one video for this project's Project Home — ONE self-contained HTML/JS document identified by `videoId` — "
397
425
  + "via the session-manager app's admin API. Writing an existing videoId replaces that video.",
426
+ summary: 'Save one self-contained HTML video for Project Home.',
398
427
  whenToUse: 'Use when asked to make a project video (demo, marketing). Compose the whole document yourself (inline <style>/<script>, '
399
428
  + 'data: URIs for assets, CSS/JS-driven animation) from what is really true about the project, declare `kind` and `lengthS`, '
400
429
  + 'then pass the document as `html` or — preferred when it embeds a base64 audio/image data URI — as an absolute `htmlPath`.',
@@ -414,10 +443,12 @@ const MCP_TOOL_CATALOG = [
414
443
  },
415
444
  {
416
445
  name: 'project_demo_video_write',
446
+ requiredOneOf: [['html', 'htmlPath']],
417
447
  group: 'project-home',
418
448
  purpose: "ALIAS of project_video_write that adds a project-demo video: write this project's demo video (30 seconds or 1 minute) — ONE self-contained HTML/JS document — as a new "
419
449
  + "project-demo entry under session-manager-operations/project-pages/videos/<id>/ via the session-manager app's admin API. "
420
450
  + 'project_video_write is the primary video tool; use this alias only for a quick project-demo.',
451
+ summary: 'Save a 30-second or 1-minute demo video (same as project_video_write).',
421
452
  whenToUse: 'Use when asked to generate or refresh the demo video. Compose the whole document yourself '
422
453
  + '(inline <style>/<script>, data: URIs for assets, CSS/JS-driven animation) from what is really true about '
423
454
  + 'the project, declare its length with <meta name="sm-demo-duration" content="N"> (5-60 seconds), then '
@@ -439,9 +470,11 @@ const MCP_TOOL_CATALOG = [
439
470
  },
440
471
  {
441
472
  name: 'project_character_write',
473
+ requiredOneOf: [['js', 'jsPath']],
442
474
  group: 'project-home',
443
475
  purpose: "Write this project's reusable video character — a `character.json` descriptor plus a `character.js` drawing module — to "
444
476
  + "the project's videos/_character/ folder via the session-manager app's admin API, so every later video can reuse the same mascot.",
477
+ summary: "Save the reusable character used in this project's videos.",
445
478
  whenToUse: 'Use once per project, before building character videos, to save the mascot you designed. Pass `json` (the descriptor object or its JSON text) '
446
479
  + 'and the module as `js` or — preferred for large modules — an absolute `jsPath` to a local .js file. Pass `replace: true` only to deliberately overwrite an existing character.',
447
480
  whenNotToUse: 'Never fabricate content. Do not use to write a video — use project_video_write. The call is rejected (409) when a character already exists and `replace` is not set, '
@@ -459,11 +492,12 @@ const MCP_TOOL_CATALOG = [
459
492
  name: 'customer_feedback_list',
460
493
  group: 'customer-feedback',
461
494
  purpose: "List the customers' feedback in the owner's local inbox (bug / feature / discussion items submitted "
462
- + 'from the {F} feedback panel), optionally pulling new items from the feedback service first.',
495
+ + 'from the Feedback panel), optionally pulling new items from the feedback service first.',
496
+ summary: "List feedback that users sent to the owner's inbox.",
463
497
  whenToUse: 'Use to inspect what customers have submitted and each item\'s status. `pull` defaults to true '
464
498
  + '(fetch new items first); pass `includeHidden: true` to include moderated-away items.',
465
499
  whenNotToUse: 'WHEN NOT TO USE IT: this only works on the owner\'s machine (it needs the owner token) and is read-only. '
466
- + 'Turning an item into an Epic is done by the human via Open as Epic in the {F} feedback panel — there is no tool '
500
+ + 'Turning an item into an Epic is done by the human via Open as Epic in the Feedback panel — there is no tool '
467
501
  + 'for it. A finding that belongs to another local project uses feedback_open_session instead.',
468
502
  exampleArgs: { pull: true, includeHidden: false },
469
503
  notes: 'Returns { ok, items, pulled? }. Not-configured machines get { ok:false, error } as an error result. '
@@ -476,9 +510,10 @@ const MCP_TOOL_CATALOG = [
476
510
  group: 'customer-feedback',
477
511
  purpose: 'Set the status of one customer feedback item (open | in_progress | resolved | wontfix) with an optional '
478
512
  + 'note the customer sees, via the session-manager app\'s admin API.',
513
+ summary: 'Set the status of one feedback item, with an optional note.',
479
514
  whenToUse: 'Use after inspecting an item with customer_feedback_list, to mark it in progress, resolved, or wontfix.',
480
515
  whenNotToUse: 'WHEN NOT TO USE IT: this changes status only. Turning an item into an Epic is done by the human via '
481
- + 'Open as Epic in the {F} feedback panel — there is no tool for it. Cross-project findings use '
516
+ + 'Open as Epic in the Feedback panel — there is no tool for it. Cross-project findings use '
482
517
  + 'feedback_open_session. Never mark an item resolved unless the work has actually landed.',
483
518
  exampleArgs: { id: 'fb_123', status: 'resolved', note: 'Fixed in 0.97.0' },
484
519
  notes: 'The note is shown to the customer; keep it short (the inbox enforces a maximum length).',
@@ -486,17 +521,28 @@ const MCP_TOOL_CATALOG = [
486
521
  {
487
522
  name: 'customer_feedback_submit',
488
523
  group: 'customer-feedback',
489
- purpose: 'Send one piece of feedback about Session Manager itself (bug | feature | discussion) to its maintainers, '
490
- + 'the same submission the {F} feedback panel makes, via the session-manager app\'s admin API.',
491
- whenToUse: 'Use only when the human asks to send feedback about Session Manager itself. Draft a title (max 120 chars) '
492
- + 'and body (max 4000 chars) from the conversation, show the human the exact title, body and tag, and call only '
493
- + 'after they agree.',
524
+ purpose: 'Send one piece of feedback about Session Manager itself (bug | feature | discussion) to its maintainers — '
525
+ + 'a one-line goal, a description, and up to 5 PNG/JPEG/WebP/GIF images given by absolute path — the same '
526
+ + 'submission the Feedback panel makes, via the session-manager app\'s admin API.',
527
+ summary: 'Send feedback about Session Manager to its maintainers.',
528
+ whenToUse: 'Use only when the human asks to send feedback about Session Manager itself. Draft a goal (one line, max '
529
+ + '120 chars) and a description (max 4000 chars) from the conversation. For images, use the `Attached: <path>` '
530
+ + 'lines of images the human pasted into this chat, or files the human named — absolute paths only, at most 5. '
531
+ + 'Show the human the exact goal, description, tag and image list, and call only after they agree.',
494
532
  whenNotToUse: 'WHEN NOT TO USE IT: a bug in the project being worked on is /develop; a finding for another local '
495
- + 'project is feedback_open_session. Never call it on your own initiative. Never include secrets, tokens, '
496
- + 'customer data or private file contents in the title or body.',
497
- exampleArgs: { title: 'Feedback panel: prefill from the current session', body: 'What happened, what I expected, steps.', tag: 'feature' },
498
- notes: 'Runs only in a Session Manager chat or terminal session (refused in headless jobs). Returns { ok, item }; '
499
- + '{ ok:false, error } comes back as an error result. The home directory is redacted to ~ before sending.',
533
+ + 'project is feedback_open_session. Never call it on your own initiative. Never attach an image the human did '
534
+ + 'not ask to send. Never include secrets, tokens, customer data or private file contents in the goal, '
535
+ + 'description or images.',
536
+ exampleArgs: {
537
+ goal: 'Feedback panel: prefill from the current session',
538
+ description: 'What happened, what I expected, steps.',
539
+ tag: 'feature',
540
+ imagePaths: ['/home/me/Pictures/feedback-panel.png'],
541
+ },
542
+ notes: 'Runs only in a Session Manager chat or terminal session (refused in headless jobs). Returns { ok, item, '
543
+ + 'warning? }; a warning means the text was sent but the feedback service did not accept every image — tell the '
544
+ + 'human which images did not go. { ok:false, error } comes back as an error result. The home directory is '
545
+ + 'redacted to ~ before sending.',
500
546
  },
501
547
  {
502
548
  name: 'macro_list',
@@ -505,6 +551,7 @@ const MCP_TOOL_CATALOG = [
505
551
  + "in the Sessions tab's HOT KEYS strip or as tools in Project Home ▸ Tools, via the session-manager app's admin API. "
506
552
  + "Each macro's `surface` tells where it shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = a tool in "
507
553
  + 'Project Home ▸ Tools, shown in every project (only what it generates is per project).',
554
+ summary: "List this project's saved one-click macros.",
508
555
  whenToUse: 'Use to see what macros already exist for this project (including machine-wide `*` macros and '
509
556
  + 'built-ins) before deciding whether to add, update or delete one.',
510
557
  whenNotToUse: 'WHEN NOT TO USE IT: macros are scoped to the caller\'s own project — this only ever returns '
@@ -518,6 +565,7 @@ const MCP_TOOL_CATALOG = [
518
565
  purpose: "Create or update one of this project's HOT KEYS macros — a saved (agentName, tag, prompt) "
519
566
  + 'one-click button — via the session-manager app\'s admin API, through the same macroLibrary.cjs store '
520
567
  + 'the Sessions HOT KEYS strip reads from.',
568
+ summary: 'Create or change a saved one-click macro (agent, mission, prompt).',
521
569
  whenToUse: 'Pass `id` to update an existing macro already visible to this project; omit `id` to create a new '
522
570
  + 'one scoped to this project. Use for things like a "Publish git + npm" macro a human will press '
523
571
  + 'repeatedly, when they have asked for that macro to exist. A surface \'project-home\' macro is a Project Home '
@@ -558,6 +606,7 @@ const MCP_TOOL_CATALOG = [
558
606
  group: 'macros',
559
607
  purpose: "Remove one of this project's HOT KEYS macros via the session-manager app's admin API, through the same "
560
608
  + 'macroLibrary.cjs store the Sessions HOT KEYS strip reads from, so an open strip updates at once.',
609
+ summary: 'Delete one saved macro.',
561
610
  whenToUse: 'Use when the human has asked for that macro to go, for example after its work moved to another project. '
562
611
  + 'Get the `id` from macro_list first.',
563
612
  whenNotToUse: "WHEN NOT TO USE IT: a macro is a HUMAN's one-click button and this cannot be undone — never delete one "
@@ -570,6 +619,53 @@ const MCP_TOOL_CATALOG = [
570
619
  notes: 'Returns { ok, deleted, macro }. `deleted: true` means the macro is gone and `macro` is its last copy. '
571
620
  + '`deleted: false` means other projects still list it, so only this project was dropped. A refusal comes back as an error result.',
572
621
  },
622
+ {
623
+ name: 'epic_list',
624
+ group: 'epics',
625
+ purpose: "Read-only list of one project's open Epics (sessions) via the session-manager app's admin API "
626
+ + '(GET /admin/epics) — the same outside-facing records a script gets: each Epic\'s epicId, title, '
627
+ + 'outside-facing state and PRD progress. Optionally filter by `state`. Results are paginated (default limit 50, '
628
+ + 'max 200) — check `hasMore`/`total` before assuming you received every Epic; page further with `offset`.',
629
+ summary: 'List the open sessions of one project and what state each is in.',
630
+ whenToUse: 'Use to survey which Epics a project has open and which need input, review or approval, before '
631
+ + 'reading one in full with epic_get.',
632
+ whenNotToUse: 'Do not use this to create, approve or change an Epic — it is read-only, and an Epic is only '
633
+ + 'ever created by a human pressing New Epic. Do not use it for PRD status; use scheduler_list_prds.',
634
+ exampleArgs: { cwd: '/home/bilko/Projects/session-manager', state: 'needs_input' },
635
+ notes: 'A partial page carries a `note` naming how many Epics were returned out of `total`.',
636
+ },
637
+ {
638
+ name: 'epic_get',
639
+ group: 'epics',
640
+ purpose: "Read-only fetch of one Epic's outside-facing record via the session-manager app's admin API "
641
+ + '(GET /admin/epic), looked up in project `cwd` by exactly one of `id` (the Epic id) or `externalRef` '
642
+ + '(the reference it was opened with). Returns `{ ok: true, epic }`, or `{ ok: false, error: "not found" }`.',
643
+ summary: 'Read one session by its id or by the outside reference it was opened with.',
644
+ whenToUse: 'Use after epic_list, or when you already hold an Epic id or external reference, to read that '
645
+ + "one Epic's state and progress.",
646
+ whenNotToUse: 'Do not pass both `id` and `externalRef`, or neither — the call is refused without reaching '
647
+ + 'the app. Do not use it to change an Epic; it is read-only.',
648
+ exampleArgs: { cwd: '/home/bilko/Projects/session-manager', id: 'epic-id-from-epic-list' },
649
+ notes: null,
650
+ requiredOneOf: [['id', 'externalRef']],
651
+ },
652
+ {
653
+ name: 'agent_list',
654
+ group: 'agents',
655
+ purpose: "Read-only list of this machine's agent library (personas) via the session-manager app's admin API "
656
+ + '(GET /admin/agents) — the same roster a script gets, sorted by name: each agent\'s name, title, description, '
657
+ + 'model, effort, tags, tools, executorOnly, agentCli and path, never the persona body. With `cwd`, each agent '
658
+ + 'also carries `resolved` { modelId, modelSource, effort, effortSource } for that project, or null when it '
659
+ + 'cannot be resolved.',
660
+ summary: 'List the agents you can launch and the model each one runs on.',
661
+ whenToUse: 'Use to see which agent personas exist and which model and effort each one pins, before naming an '
662
+ + 'agentType in a PRD or a macro. Pass `cwd` to see what each agent resolves to in that project.',
663
+ whenNotToUse: 'Do not use this to create, edit or delete an agent — it is read-only. Do not use it to list '
664
+ + 'saved macros; use macro_list. A `cwd` that is not an absolute path to a project with a '
665
+ + 'session-manager-operations folder is refused.',
666
+ exampleArgs: { cwd: '/home/bilko/Projects/session-manager' },
667
+ notes: 'Returns { ok: true, agents }.',
668
+ },
573
669
  {
574
670
  name: 'session_manager_help',
575
671
  group: 'help',
@@ -578,6 +674,7 @@ const MCP_TOOL_CATALOG = [
578
674
  + "tool's description is composed from, this project's multi-tool recipes, and this machine's "
579
675
  + 'delegation-readiness state (tells apart "not registered", "registered but dead" — the process '
580
676
  + 'won\'t even answer tools/list — and "registered and answering").',
677
+ summary: 'Start here: list every tool, or explain one tool or recipe.',
581
678
  whenToUse: 'Call with no arguments for the full grouped tool list plus recipe titles. Pass `tool` (a tool '
582
679
  + 'name) for that one tool\'s full entry, including its exampleArgs. Pass `topic` (a recipe id) for that '
583
680
  + 'recipe\'s step-by-step instructions. Pass both to get both sections in one call.',
@@ -0,0 +1,121 @@
1
+ /**
2
+ * agentAdminRoutes.cjs — read-only admin HTTP route over the persona library
3
+ * (agentLibrary.cjs's listPersonas), so an outside app on this machine can
4
+ * launch from the same roster with a pinned model instead of copying persona
5
+ * text into its own prompts.
6
+ *
7
+ * GET /admin/agents[?cwd=<abs>]
8
+ * → 200 { ok: true, agents } sorted by name. Each agent carries
9
+ * name, title, description, model, effort, tags, tools, executorOnly,
10
+ * agentCli, agentCliModel, seedVersion, path — never the persona body or
11
+ * the per-project override details.
12
+ * With cwd, each agent also has resolved: { modelId, modelAlias,
13
+ * modelSource, effort, effortSource } (effectiveModelInfo.cjs), or
14
+ * resolved: null when that persona's resolution throws. modelAlias is
15
+ * the effective alias: the persona's own, or the Settings default when
16
+ * the persona inherits.
17
+ *
18
+ * A query the schema rejects → 400 { ok: false, error: 'invalid query', details }.
19
+ * A cwd that is not absolute or has no session-manager-operations folder →
20
+ * 400 { ok: false, error: <reason> }.
21
+ *
22
+ * Writes no file and no audit row. Auth/loopback binding are the injected
23
+ * localAdminHttp.cjs transport's job (see index.cjs).
24
+ */
25
+ 'use strict';
26
+
27
+ const fs = require('node:fs');
28
+ const path = require('node:path');
29
+ const { schemas } = require('../../ipcSchemas.cjs');
30
+ const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
31
+ const { opsPath } = require('../opsOwnership.cjs');
32
+
33
+ /** @param {unknown} cwd @returns {string | null} the reason this cwd is not a project, or null. */
34
+ function projectProblem(cwd) {
35
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return 'cwd must be an absolute path';
36
+ let dir;
37
+ try {
38
+ dir = opsPath(cwd);
39
+ } catch (e) {
40
+ return e instanceof Error ? e.message : String(e);
41
+ }
42
+ try {
43
+ if (!fs.statSync(dir).isDirectory()) return 'cwd has no session-manager-operations folder';
44
+ } catch {
45
+ return 'cwd has no session-manager-operations folder';
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /** @param {any} p the listPersonas row → the outside-facing fields only. */
51
+ function publicAgent(p) {
52
+ return {
53
+ name: p.name,
54
+ title: p.title ?? null,
55
+ description: p.description ?? null,
56
+ model: p.model ?? null,
57
+ effort: p.effort ?? null,
58
+ tags: Array.isArray(p.tags) ? p.tags : [],
59
+ tools: Array.isArray(p.tools) ? p.tools : [],
60
+ executorOnly: p.executorOnly === true,
61
+ agentCli: p.agentCli ?? null,
62
+ agentCliModel: p.agentCliModel ?? null,
63
+ seedVersion: p.seedVersion ?? null,
64
+ path: p.path ?? null,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * @param {{ registerRoute: Function }} adminHttp
70
+ * @param {{ listPersonas?: () => Promise<any[]>, resolveEffectiveModelInfo?: (args: { cwd: string, agentType: string }) => Promise<any> }} [deps]
71
+ */
72
+ function registerAdminRoute(adminHttp, deps = {}) {
73
+ // Lazy defaults: agentLibrary pulls in the sessions store + config manager.
74
+ const listPersonas = deps.listPersonas || (() => require('../../agentLibrary.cjs').listPersonas());
75
+ const resolveInfo = deps.resolveEffectiveModelInfo
76
+ || ((/** @type {{ cwd: string, agentType: string }} */ args) => require('../claude/effectiveModelInfo.cjs').resolveEffectiveModelInfo(args));
77
+
78
+ adminHttp.registerRoute('GET', '/admin/agents', async (/** @type {any} */ req, /** @type {any} */ res, /** @type {any} */ query) => {
79
+ let input;
80
+ try {
81
+ input = schemas.adminListAgentsQuery.parse(Object.fromEntries(query ?? []));
82
+ } catch (e) {
83
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
84
+ return;
85
+ }
86
+ if (input.cwd !== undefined) {
87
+ const problem = projectProblem(input.cwd);
88
+ if (problem) {
89
+ sendJson(res, 400, { ok: false, error: problem });
90
+ return;
91
+ }
92
+ }
93
+
94
+ const personas = await listPersonas();
95
+ const agents = personas
96
+ .map(publicAgent)
97
+ .sort((a, b) => String(a.name).localeCompare(String(b.name)));
98
+
99
+ if (input.cwd !== undefined) {
100
+ const cwd = input.cwd;
101
+ await Promise.all(agents.map(async (/** @type {any} */ agent) => {
102
+ try {
103
+ const info = await resolveInfo({ cwd, agentType: agent.name });
104
+ agent.resolved = {
105
+ modelId: info?.resolvedModelId ?? null,
106
+ modelAlias: info?.modelAlias ?? null,
107
+ modelSource: info?.modelSource ?? null,
108
+ effort: info?.personaEffort ?? null,
109
+ effortSource: info?.personaEffortSource ?? null,
110
+ };
111
+ } catch {
112
+ agent.resolved = null;
113
+ }
114
+ }));
115
+ }
116
+
117
+ sendJson(res, 200, { ok: true, agents });
118
+ });
119
+ }
120
+
121
+ module.exports = { registerAdminRoute };
@@ -45,6 +45,10 @@ const EpicSourceSchema = z.object({
45
45
  fromEpicId: z.string().optional(),
46
46
  // The macro that launched this Epic (new-epic-ui Epics only).
47
47
  macroId: z.string().optional(),
48
+ // An outside app's own id for this Epic. Any string here: the strict rule
49
+ // lives in epic/externalRef.cjs at entry points, since a stricter stored
50
+ // shape would make dropInvalidSessions drop a whole row.
51
+ externalRef: z.string().optional(),
48
52
  // Zod strips undeclared keys on the merge path; a stricter shape could make dropInvalidSessions (ipcSchemas.cjs) drop a whole row holding an older or malformed value.
49
53
  proposal: z.unknown().optional(),
50
54
  autoApprove: z.unknown().optional(),
@@ -28,10 +28,41 @@ function textOf(content) {
28
28
  .join('\n');
29
29
  }
30
30
 
31
- function cap(text, max) {
31
+ const ATTACHED_LINE = /^Attached: .+$/;
32
+
33
+ function capHead(text, max) {
32
34
  return text.length > max ? text.slice(0, max - 1) + '…' : text;
33
35
  }
34
36
 
37
+ /**
38
+ * Cap text at `max` chars. A trailing block of `Attached: <path>` lines (image
39
+ * sends append it) survives: only the body before it is cut, so the phone can
40
+ * still render attachment chips. Without such a block this is a plain head cap.
41
+ */
42
+ function cap(text, max) {
43
+ if (text.length <= max) return text;
44
+ const lines = text.split('\n');
45
+ let i = lines.length;
46
+ while (i > 0 && ATTACHED_LINE.test(lines[i - 1])) i--;
47
+ if (i === lines.length) return capHead(text, max);
48
+ const block = lines.slice(i);
49
+ const blockText = block.join('\n');
50
+ if (blockText.length <= max - 2) {
51
+ const body = lines.slice(0, i).join('\n').trimEnd();
52
+ const budget = max - 2 - blockText.length;
53
+ if (!body || budget < 1) return blockText;
54
+ return capHead(body, budget) + '\n\n' + blockText;
55
+ }
56
+ // Block alone overflows: whole lines from its start, no body.
57
+ let out = '';
58
+ for (const line of block) {
59
+ const next = out ? out + '\n' + line : line;
60
+ if (next.length > max) break;
61
+ out = next;
62
+ }
63
+ return out || capHead(block[0], max);
64
+ }
65
+
35
66
  function truncate(text) {
36
67
  return cap(text, MAX_TEXT_CHARS);
37
68
  }