claude-code-session-manager 0.126.0 → 0.128.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 (107) hide show
  1. package/bin/cli.cjs +71 -9
  2. package/bin/supervise.cjs +84 -0
  3. package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
  4. package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
  5. package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
  6. package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
  7. package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
  8. package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
  9. package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
  10. package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
  11. package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
  12. package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
  13. package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
  14. package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
  15. package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
  16. package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
  17. package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
  18. package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
  19. package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
  20. package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
  21. package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
  22. package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
  23. package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
  24. package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
  25. package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
  26. package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
  27. package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
  28. package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
  29. package/dist/assets/index-DzY_GXYY.js +3081 -0
  30. package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
  33. package/dist/index.html +2 -2
  34. package/dist-web/app.css +1 -1
  35. package/dist-web/app.js +343 -341
  36. package/package.json +1 -1
  37. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  38. package/scripts/scheduler-mcp-server.cjs +209 -7
  39. package/src/main/build-info.json +4 -4
  40. package/src/main/chatRunner.cjs +37 -4
  41. package/src/main/crashDiagnostics.cjs +83 -8
  42. package/src/main/health.cjs +16 -5
  43. package/src/main/index.cjs +46 -0
  44. package/src/main/ipcSchemas.cjs +107 -0
  45. package/src/main/lib/chatBootRecovery.cjs +136 -0
  46. package/src/main/lib/chatInflight.cjs +88 -0
  47. package/src/main/lib/claude/agentModelResolve.cjs +26 -7
  48. package/src/main/lib/claude/personaToolScope.cjs +40 -2
  49. package/src/main/lib/demo-video-kit/capture.cjs +113 -0
  50. package/src/main/lib/demo-video-kit/character.cjs +97 -0
  51. package/src/main/lib/demo-video-kit/checks.cjs +150 -0
  52. package/src/main/lib/demo-video-kit/frames.cjs +200 -0
  53. package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
  54. package/src/main/lib/demo-video-kit/sound.cjs +312 -0
  55. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  56. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  57. package/src/main/lib/epic/epicValidationHook.cjs +31 -3
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  59. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
  60. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +93 -14
  62. package/src/main/lib/opsOwnership.cjs +9 -5
  63. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
  64. package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
  65. package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
  66. package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
  67. package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
  68. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
  69. package/src/main/lib/prd/prdCreate.cjs +17 -2
  70. package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
  71. package/src/main/lib/process/childWithLog.cjs +38 -95
  72. package/src/main/lib/process/memoryScope.cjs +140 -0
  73. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  74. package/src/main/lib/process/procIdentity.cjs +10 -3
  75. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  76. package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
  77. package/src/main/lib/project-pages/playerBridge.cjs +129 -0
  78. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  79. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  80. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  81. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  82. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  83. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  84. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  85. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  86. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  87. package/src/main/lib/smfileHeaders.cjs +11 -3
  88. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  89. package/src/main/projectPages.cjs +107 -30
  90. package/src/main/promptSessionsIpc.cjs +131 -0
  91. package/src/main/scheduler/budget.cjs +31 -0
  92. package/src/main/scheduler/prdParser.cjs +2 -0
  93. package/src/main/scheduler/prdPaths.cjs +54 -0
  94. package/src/main/scheduler/reviewLadder.cjs +17 -0
  95. package/src/main/scheduler/starvation.cjs +22 -0
  96. package/src/main/scheduler.cjs +548 -77
  97. package/src/main/seedSchedulerMcp.cjs +10 -1
  98. package/src/main/templates/PRD_AUTHORING.md +5 -2
  99. package/src/main/transcripts.cjs +8 -0
  100. package/src/main/usage.cjs +4 -2
  101. package/src/main/webRemote.cjs +3 -1
  102. package/src/preload/api.d.ts +113 -7
  103. package/src/preload/apiSurface.json +70 -0
  104. package/src/preload/index.cjs +13 -0
  105. package/src/seed/agents/demo-video-builder.md +141 -43
  106. package/src/seed/agents/project-home-builder.md +26 -13
  107. package/dist/assets/index-DgPUERhe.js +0 -3079
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.126.0",
3
+ "version": "0.128.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",
@@ -109,7 +109,8 @@ failure modes have different fixes:
109
109
  exempt: it has one criterion per PRD, plus the record. A new helper and its first caller are
110
110
  two PRDs. Most PRDs take 5–10 executor minutes; split anything expected
111
111
  to take over 15. Do not write an estimate. Why: the kill budget floors at 45 minutes, so a
112
- run without one is never starved.
112
+ run without one is never starved. A validator's budget is sized from the gates it must
113
+ re-run, so the validate PRD omits it too.
113
114
  8. **Make each PRD self-contained.** The executor sees only the PRD and the project. Notes are
114
115
  a recipe: `Read first:` (at most 4 files, with line ranges), `Steps:` (numbered, each naming
115
116
  file and function), `Do not touch:` (files a sibling owns). Quote signatures. Say when a PRD
@@ -233,7 +234,7 @@ The validator prints `VALIDATION: <slug> VERIFIED` or `VALIDATION: <slug> REFUTE
233
234
  per PRD. Queue the validate PRD in the same `scheduler_create_prds` call as the plan (its `dependsOn` may name that call's entries); with single creates it goes last: in a single `scheduler_create_prd`, `dependsOn` accepts only slugs that already exist. The
234
235
  scheduler sends no per-PRD validation prompt. When the Epic has no pending or running PRD for
235
236
  `SM_EPIC_SETTLE_SECONDS` (default 120), it queues one `validate-sweep-*` validator for completed
236
- PRDs no validator checked, then sends one PLAN SETTLED digest. Several validators in one Epic
237
+ PRDs no validator checked (a large sweep becomes several sweeps in turn), then sends one PLAN SETTLED digest. Several validators in one Epic
237
238
  are fine: each runs headless.
238
239
 
239
240
  If the API rejects `agentType: "validator"`, the persona is not installed: keep the plan
@@ -13,16 +13,23 @@
13
13
  *
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
+ * project_page_write({ cwd?, pageId, title, topic?, html? | htmlPath? }) -> POST /admin/project-home/pages/write
17
+ * project_character_write({ cwd?, json, js? | jsPath?, replace? }) -> POST /admin/project-home/character/write
18
+ * project_video_write({ cwd?, videoId, title, kind, lengthS, html? | htmlPath?, meta? }) -> POST /admin/project-home/videos/write
16
19
  *
17
20
  * macro_list({ cwd? }) -> GET /admin/macros?cwd=<encoded>
18
21
  * macro_save({ cwd?, id?, label, agentName, tag, prompt }) -> POST /admin/macros/save
22
+ * macro_delete({ id }) -> POST /admin/macros/delete
19
23
  * customer_feedback_list({ pull?, includeHidden? }) -> GET /admin/customer-feedback/inbox
20
24
  * customer_feedback_set_status({ id, status, note? }) -> POST /admin/customer-feedback/status
21
25
  *
22
26
  * This is a separate process from the Electron app — it only ever reaches
23
27
  * it over the token-authed loopback HTTP API in admin-api.json, never by
24
- * requiring scheduler.cjs/localAdminHttp.cjs directly. The admin server IS the
25
- * security boundary; this file stays on the client side of it.
28
+ * requiring scheduler.cjs/localAdminHttp.cjs directly. The admin API (loopback +
29
+ * bearer token) is the boundary against other users and remote callers, not
30
+ * against a job running as the same user (it can read admin-api.json). The env
31
+ * refusals in this file (job tool scope, headless queue, macro delete) are
32
+ * guardrails for agents acting in good faith, not containment.
26
33
  */
27
34
 
28
35
  'use strict';
@@ -56,6 +63,23 @@ function withPointer(text) {
56
63
  }
57
64
 
58
65
  const MAX_DEMO_VIDEO_BYTES = 2 * 1024 * 1024;
66
+ const MAX_CHARACTER_JS_BYTES = 300 * 1024;
67
+
68
+ /** Reads a local .js file for project_character_write; errors carry only the reason, never file contents. */
69
+ async function readCharacterJsFile(p) {
70
+ if (typeof p !== 'string' || !path.isAbsolute(p)) return { error: 'jsPath must be an absolute path' };
71
+ if (!/\.(c|m)?js$/i.test(p)) return { error: 'jsPath must end in .js' };
72
+ try {
73
+ const st = await fsp.stat(p);
74
+ if (!st.isFile()) return { error: 'jsPath is not a regular file' };
75
+ if (st.size > MAX_CHARACTER_JS_BYTES) return { error: `jsPath file exceeds ${MAX_CHARACTER_JS_BYTES} bytes` };
76
+ const js = await fsp.readFile(p, 'utf8');
77
+ if (js.length === 0) return { error: 'jsPath file is empty' };
78
+ return { js };
79
+ } catch (err) {
80
+ return { error: `cannot read jsPath: ${err && err.code ? err.code : 'read failed'}` };
81
+ }
82
+ }
59
83
 
60
84
  /** Reads a local .html/.htm file for project_demo_video_write; errors carry only the reason, never file contents. */
61
85
  async function readDemoVideoHtmlFile(p) {
@@ -73,6 +97,16 @@ async function readDemoVideoHtmlFile(p) {
73
97
  }
74
98
  }
75
99
 
100
+ /** Resolves exactly one of html / htmlPath into { html } or { error }. */
101
+ async function resolveHtmlArg(args) {
102
+ const hasHtml = !!args && args.html !== undefined && args.html !== null && args.html !== '';
103
+ const hasPath = !!args && args.htmlPath !== undefined && args.htmlPath !== null && args.htmlPath !== '';
104
+ if (hasHtml === hasPath) return { error: 'provide exactly one of html or htmlPath' };
105
+ if (hasPath) return readDemoVideoHtmlFile(args.htmlPath);
106
+ if (typeof args.html !== 'string') return { error: 'missing required argument: html' };
107
+ return { html: args.html };
108
+ }
109
+
76
110
  function errorResult(text) {
77
111
  return { content: [{ type: 'text', text: withPointer(text) }], isError: true };
78
112
  }
@@ -386,7 +420,7 @@ const TOOLS = [
386
420
  inputSchema: {
387
421
  type: 'object',
388
422
  properties: {
389
- tabId: { type: 'string', description: 'Target tab id (claudeSessionId) that must already be open in the app' },
423
+ tabId: { type: 'string', description: "Target id: an open tab's id or an Epic id (Epic chats are keyed by Epic id). Never a Claude session id." },
390
424
  prompt: { type: 'string', description: 'Prompt text to enqueue' },
391
425
  },
392
426
  required: ['tabId', 'prompt'],
@@ -476,11 +510,26 @@ const TOOLS = [
476
510
  type: 'object',
477
511
  properties: {
478
512
  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." },
479
- html: { type: 'string', description: 'The complete self-contained HTML document (<= 1MB; no <script src>, <link href=http*>, @import, or url(http*)).' },
513
+ html: { type: 'string', description: 'The complete self-contained HTML document (<= 1MB; inline <style> only — scripts never run in a page; no <script src>, <link href=http*>, @import, or url(http*)).' },
480
514
  },
481
515
  required: ['html'],
482
516
  },
483
517
  },
518
+ {
519
+ name: 'project_character_write',
520
+ description: descriptionFor('project_character_write'),
521
+ inputSchema: {
522
+ type: 'object',
523
+ properties: {
524
+ 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." },
525
+ json: { description: 'The character descriptor: a JSON object (or its JSON text).' },
526
+ js: { type: 'string', description: 'The character drawing module source (<= 300KB; no remote references or network-capable APIs). Give exactly one of js / jsPath.' },
527
+ jsPath: { type: 'string', description: 'Absolute path to a local .js file holding the module (same rules as js; <= 300KB). Give exactly one of js / jsPath.' },
528
+ replace: { type: 'boolean', description: 'Overwrite an existing character. Without it an existing character is refused with 409.' },
529
+ },
530
+ required: ['json'],
531
+ },
532
+ },
484
533
  {
485
534
  name: 'project_demo_video_write',
486
535
  description: descriptionFor('project_demo_video_write'),
@@ -490,11 +539,11 @@ const TOOLS = [
490
539
  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." },
491
540
  html: {
492
541
  type: 'string',
493
- description: 'The complete self-contained HTML/JS document for a 30-second-or-less demo video (<= 2MB). '
542
+ description: 'The complete self-contained HTML/JS document for a demo video of 60 seconds or less (<= 2MB). '
494
543
  + 'It is rejected for: being empty; <script src>, <link href=http*>, @import, or url(http*) (no remote references); '
495
544
  + 'fetch/XMLHttpRequest/WebSocket/EventSource/sendBeacon/dynamic import/importScripts/<iframe>/<object>/<embed>/window.open/'
496
545
  + 'any http(s)/// src or href (no network-capable APIs — the document is CSP-fenced after it is written); '
497
- + 'or missing a <meta name="sm-demo-duration" content="N"> tag with 5 <= N <= 30.',
546
+ + 'or missing a <meta name="sm-demo-duration" content="N"> tag with 5 <= N <= 60.',
498
547
  },
499
548
  htmlPath: {
500
549
  type: 'string',
@@ -504,6 +553,40 @@ const TOOLS = [
504
553
  },
505
554
  },
506
555
  },
556
+ {
557
+ name: 'project_page_write',
558
+ description: descriptionFor('project_page_write'),
559
+ inputSchema: {
560
+ type: 'object',
561
+ properties: {
562
+ 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." },
563
+ pageId: { type: 'string', description: 'Stable id (kebab-case) of the knowledge page; writing the same id replaces that page.' },
564
+ title: { type: 'string', description: 'Human title shown in the page list.' },
565
+ topic: { type: 'string', description: 'Optional: one-line topic/summary of the page.' },
566
+ html: { type: 'string', description: 'The complete self-contained HTML document (<= 1MB). Inline <style> only; scripts never run in a page. No <script src>, <link href=http*>, @import, or url(http*).' },
567
+ htmlPath: { type: 'string', description: 'Absolute path to a local .html/.htm file holding the document (same rules as html). Give exactly one of html / htmlPath.' },
568
+ },
569
+ required: ['pageId', 'title'],
570
+ },
571
+ },
572
+ {
573
+ name: 'project_video_write',
574
+ description: descriptionFor('project_video_write'),
575
+ inputSchema: {
576
+ type: 'object',
577
+ properties: {
578
+ 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." },
579
+ videoId: { type: 'string', description: 'Stable id (kebab-case) of the video; writing the same id replaces that video.' },
580
+ title: { type: 'string', description: 'Human title shown in the video list.' },
581
+ kind: { type: 'string', description: 'What the video is, e.g. project-demo or marketing.' },
582
+ lengthS: { type: 'number', description: 'Length of the video in seconds.' },
583
+ html: { type: 'string', description: 'The complete self-contained HTML/JS video document (<= 2MB; no remote references or network-capable APIs).' },
584
+ htmlPath: { type: 'string', description: 'Absolute path to a local .html/.htm file holding the document (<= 2MB). Prefer this for base64 data URIs. Give exactly one of html / htmlPath.' },
585
+ meta: { type: 'object', description: 'Optional: free-form metadata object stored with the video.' },
586
+ },
587
+ required: ['videoId', 'title', 'kind', 'lengthS'],
588
+ },
589
+ },
507
590
  {
508
591
  name: 'macro_list',
509
592
  description: descriptionFor('macro_list'),
@@ -544,6 +627,17 @@ const TOOLS = [
544
627
  required: ['label', 'agentName', 'tag', 'prompt'],
545
628
  },
546
629
  },
630
+ {
631
+ name: 'macro_delete',
632
+ description: descriptionFor('macro_delete'),
633
+ inputSchema: {
634
+ type: 'object',
635
+ properties: {
636
+ id: { type: 'string', description: 'Id of the macro to remove, from macro_list.' },
637
+ },
638
+ required: ['id'],
639
+ },
640
+ },
547
641
  {
548
642
  name: 'customer_feedback_list',
549
643
  description: descriptionFor('customer_feedback_list'),
@@ -581,6 +675,49 @@ const TOOLS = [
581
675
  },
582
676
  ];
583
677
 
678
+ // SM_SCHEDULER_JOB_MCP_TOOLS: JSON array of full mcp__<server>__<tool> names a
679
+ // scoped job may use. Unset = no filter. Malformed = fail closed. Guardrail only.
680
+ function jobToolScope() {
681
+ const raw = process.env.SM_SCHEDULER_JOB_MCP_TOOLS;
682
+ if (raw === undefined) return null;
683
+ let parsed;
684
+ try { parsed = JSON.parse(raw); } catch { return { names: new Set(), malformed: true }; }
685
+ if (!Array.isArray(parsed) || !parsed.every((e) => typeof e === 'string')) {
686
+ return { names: new Set(), malformed: true };
687
+ }
688
+ const names = new Set();
689
+ for (const entry of parsed) {
690
+ if (!entry.startsWith('mcp__')) continue;
691
+ const i = entry.indexOf('__', 5);
692
+ if (i > 0) names.add(entry.slice(i + 2));
693
+ }
694
+ return { names, malformed: false };
695
+ }
696
+
697
+ function jobToolScopeRefusal(toolName) {
698
+ const scope = jobToolScope();
699
+ if (!scope || (!scope.malformed && scope.names.has(toolName))) return null;
700
+ const text = scope.malformed
701
+ ? `refused: ${toolName} was not run because SM_SCHEDULER_JOB_MCP_TOOLS is malformed (expected a JSON array of tool-name strings). `
702
+ + 'Say in your final result that the tool scope is malformed and stop.'
703
+ : `refused: ${toolName} is outside the tool scope of headless scheduled job '${process.env.SM_SCHEDULER_JOB_SLUG || '(unknown)'}' — its persona does not list it. `
704
+ + "Starting this server yourself does not widen a job's scope. Say in your final result which tool was missing and stop.";
705
+ return { content: [{ type: 'text', text }], isError: true };
706
+ }
707
+
708
+ // A macro is a human's button and its delete cannot be undone, so this runs
709
+ // only in a session a human is attached to. headlessQueueRefusal does not fit:
710
+ // it lets an architect job through.
711
+ function macroDeleteRefusal() {
712
+ if (process.env.SM_SCHEDULER_JOB_SLUG || !process.env.SM_CHAT_SESSION_ID) {
713
+ return errorResult(
714
+ 'refused: macro_delete runs only in a Session Manager chat or terminal session, because a macro goes only when a human asks. '
715
+ + 'Say in your final result which macro should go; the human can remove it from the HOT KEYS panel.',
716
+ );
717
+ }
718
+ return null;
719
+ }
720
+
584
721
  // Named + exported (see module.exports below) so mcpToolCatalog.test.cjs's
585
722
  // sibling can exercise session_manager_help's argument handling directly —
586
723
  // mocking node:fs/promises + global.fetch to drive adminRequest — without
@@ -617,6 +754,8 @@ function withCreateOrigin(payload) {
617
754
 
618
755
  async function handleCallTool(request) {
619
756
  const { name, arguments: args } = request.params;
757
+ const scopeRefusal = jobToolScopeRefusal(name);
758
+ if (scopeRefusal) return scopeRefusal;
620
759
  try {
621
760
  if (name === 'scheduler_reset_job') {
622
761
  const slug = args && typeof args.slug === 'string' ? args.slug : null;
@@ -832,6 +971,28 @@ async function handleCallTool(request) {
832
971
  const result = await adminRequest('POST', '/admin/project-home/write', { cwd, html: args.html });
833
972
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
834
973
  }
974
+ if (name === 'project_character_write') {
975
+ if (!args || args.json === undefined || args.json === null || args.json === '') {
976
+ return errorResult('missing required argument: json');
977
+ }
978
+ const hasJs = args.js !== undefined && args.js !== null && args.js !== '';
979
+ const hasJsPath = args.jsPath !== undefined && args.jsPath !== null && args.jsPath !== '';
980
+ if (hasJs === hasJsPath) return errorResult('provide exactly one of js or jsPath');
981
+ let js;
982
+ if (hasJsPath) {
983
+ const loaded = await readCharacterJsFile(args.jsPath);
984
+ if (loaded.error) return errorResult(loaded.error);
985
+ js = loaded.js;
986
+ } else {
987
+ if (typeof args.js !== 'string') return errorResult('missing required argument: js');
988
+ js = args.js;
989
+ }
990
+ const cwd = resolveCwdArg(args);
991
+ const body = { cwd, json: args.json, js };
992
+ if (args.replace === true) body.replace = true;
993
+ const result = await adminRequest('POST', '/admin/project-home/character/write', body);
994
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
995
+ }
835
996
  if (name === 'project_demo_video_write') {
836
997
  const hasHtml = !!args && args.html !== undefined && args.html !== null && args.html !== '';
837
998
  const hasPath = !!args && args.htmlPath !== undefined && args.htmlPath !== null && args.htmlPath !== '';
@@ -851,6 +1012,31 @@ async function handleCallTool(request) {
851
1012
  const result = await adminRequest('POST', '/admin/project-home/demo-video/write', { cwd, html });
852
1013
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
853
1014
  }
1015
+ if (name === 'project_page_write') {
1016
+ if (!args || typeof args.pageId !== 'string' || !args.pageId || typeof args.title !== 'string' || !args.title) {
1017
+ return errorResult('missing required arguments: pageId, title');
1018
+ }
1019
+ const loaded = await resolveHtmlArg(args);
1020
+ if (loaded.error) return errorResult(loaded.error);
1021
+ const cwd = resolveCwdArg(args);
1022
+ const body = { cwd, pageId: args.pageId, title: args.title, html: loaded.html };
1023
+ if (typeof args.topic === 'string' && args.topic) body.topic = args.topic;
1024
+ const result = await adminRequest('POST', '/admin/project-home/pages/write', body);
1025
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1026
+ }
1027
+ if (name === 'project_video_write') {
1028
+ if (!args || typeof args.videoId !== 'string' || !args.videoId || typeof args.title !== 'string' || !args.title
1029
+ || typeof args.kind !== 'string' || !args.kind || typeof args.lengthS !== 'number' || !Number.isFinite(args.lengthS)) {
1030
+ return errorResult('missing required arguments: videoId, title, kind, lengthS');
1031
+ }
1032
+ const loaded = await resolveHtmlArg(args);
1033
+ if (loaded.error) return errorResult(loaded.error);
1034
+ const cwd = resolveCwdArg(args);
1035
+ const body = { cwd, videoId: args.videoId, title: args.title, kind: args.kind, lengthS: args.lengthS, html: loaded.html };
1036
+ if (args.meta && typeof args.meta === 'object') body.meta = args.meta;
1037
+ const result = await adminRequest('POST', '/admin/project-home/videos/write', body);
1038
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1039
+ }
854
1040
  if (name === 'macro_list') {
855
1041
  const cwd = resolveCwdArg(args);
856
1042
  const result = await adminRequest('GET', `/admin/macros?cwd=${encodeURIComponent(cwd)}`);
@@ -870,6 +1056,19 @@ async function handleCallTool(request) {
870
1056
  const result = await adminRequest('POST', '/admin/macros/save', payload);
871
1057
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
872
1058
  }
1059
+ if (name === 'macro_delete') {
1060
+ const refusal = macroDeleteRefusal();
1061
+ if (refusal) return refusal;
1062
+ if (!args || typeof args.id !== 'string' || !args.id) return errorResult('missing or invalid required argument: id');
1063
+ // No args: this tool never takes a project from the caller. mcpStdioServer enforces no input schema.
1064
+ const result = await adminRequest('POST', '/admin/macros/delete', {
1065
+ cwd: resolveCwdArg(),
1066
+ id: args.id,
1067
+ originClaudeSessionId: process.env.SM_CHAT_SESSION_ID,
1068
+ });
1069
+ if (result?.ok === false) return errorResult(result.error ?? 'macro_delete failed');
1070
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1071
+ }
873
1072
  if (name === 'customer_feedback_list') {
874
1073
  const qs = new URLSearchParams();
875
1074
  if (!args || args.pull !== false) qs.set('pull', '1');
@@ -931,7 +1130,10 @@ async function main() {
931
1130
  createStdioServer({
932
1131
  name: 'session-manager-scheduler',
933
1132
  version: '1.0.0',
934
- listTools: () => TOOLS,
1133
+ listTools: () => {
1134
+ const scope = jobToolScope();
1135
+ return scope ? TOOLS.filter((t) => scope.names.has(t.name)) : TOOLS;
1136
+ },
935
1137
  callTool: (params) => handleCallTool({ params }),
936
1138
  }).start();
937
1139
  }
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.126.0",
3
- "gitSha": "52a58ff337bbb86c0de1841f70b2220fce04877a",
4
- "gitShortSha": "52a58ff3",
2
+ "version": "0.128.0",
3
+ "gitSha": "649aeb30ca19187ef19b347f5482b984304b4943",
4
+ "gitShortSha": "649aeb30",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-10-31T16:13:41.329Z",
6
+ "builtAt": "2026-11-06T07:00:20.246Z",
7
7
  "dirty": false
8
8
  }
@@ -52,7 +52,9 @@ const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResol
52
52
  const { planEpicSpawn } = require('./lib/epic/epicSpawnPlan.cjs');
53
53
  const epicWorktreeMint = require('./lib/epic/epicWorktreeMint.cjs');
54
54
  const logs = require('./logs.cjs');
55
+ const chatInflight = require('./lib/chatInflight.cjs');
55
56
  const { feedChildStdin } = require('./lib/process/childStdin.cjs');
57
+ const memoryScope = require('./lib/process/memoryScope.cjs');
56
58
  const { createHeadTailBuffer } = require('./lib/util/headTailBuffer.cjs');
57
59
 
58
60
  // Caps on per-run stream buffers (a run can last hours).
@@ -364,6 +366,11 @@ const dispatching = new Set();
364
366
  // "Session ID … is already in use", so pump() refuses to start a second run
365
367
  // for a held sessionId (it waits in `waiting` like any other blocked run).
366
368
  const liveSessions = new Set();
369
+ // sessionIds whose previous-boot CLI child is still alive (chatBootRecovery): run() for
370
+ // them waits in `waiting` until released, so a second writer is never spawned.
371
+ const orphanSessions = new Set();
372
+ function holdOrphanSession(sessionId) { if (sessionId) orphanSessions.add(sessionId); }
373
+ function releaseOrphanSession(sessionId) { orphanSessions.delete(sessionId); pump(); }
367
374
  // Submissions parked while a New Epic's fire-and-forget worktree mint is still in
368
375
  // flight (tabId → opts). Counted by run()'s tabBusy; cancel() can drop them.
369
376
  const pendingStart = new Map();
@@ -382,6 +389,7 @@ function __resetQueueForTests() {
382
389
  inFlight.clear();
383
390
  dispatching.clear();
384
391
  liveSessions.clear();
392
+ orphanSessions.clear();
385
393
  waiting.length = 0;
386
394
  pendingStart.clear();
387
395
  sessionSlots.__resetForTests();
@@ -430,6 +438,7 @@ function run(opts) {
430
438
  const tabBusy = inFlight.has(opts.tabId)
431
439
  || dispatching.has(opts.tabId)
432
440
  || liveSessions.has(opts.sessionId)
441
+ || orphanSessions.has(opts.sessionId)
433
442
  || pendingStart.has(opts.tabId)
434
443
  || waiting.some((w) => w.tabId === opts.tabId);
435
444
  if (tabBusy && opts.silent) {
@@ -469,7 +478,7 @@ function pump() {
469
478
  // synchronous sweep of this loop could start two runs for the same tab and
470
479
  // race two --resume processes against a single sessionId.
471
480
  const idx = waiting.findIndex((w) => !inFlight.has(w.tabId) && !dispatching.has(w.tabId)
472
- && !liveSessions.has(w.sessionId));
481
+ && !liveSessions.has(w.sessionId) && !orphanSessions.has(w.sessionId));
473
482
  // Everything queued is blocked behind its own tab's live run; the settle()
474
483
  // of that run re-pumps.
475
484
  if (idx === -1) break;
@@ -532,6 +541,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
532
541
  const settle = () => {
533
542
  if (settled) return;
534
543
  settled = true;
544
+ chatInflight.end(sessionId).catch(() => {});
535
545
  inFlight.delete(tabId);
536
546
  resolve();
537
547
  };
@@ -742,9 +752,24 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
742
752
  // stdout is piped for real-time NDJSON streaming; stderr piped for
743
753
  // error-message capture.
744
754
  let thisChild;
755
+ // Memory-capped systemd scope for this attempt (unwrapped when unsupported).
756
+ // A turn's background processes (dev server, local service) outlive it on
757
+ // purpose: the scope is never stopped; created --collect, systemd collects it once empty.
745
758
  try {
746
759
  const chatArgs = buildArgs(resumeFlag);
747
- const target = claudeSpawnTarget('chat', sessionId, claudeBin, chatArgs);
760
+ let target = claudeSpawnTarget('chat', sessionId, claudeBin, chatArgs);
761
+ // Limits first: with the cap off, never probe systemd.
762
+ const limits = memoryScope.memoryLimitsFor({ totalRamMb: Math.floor(require('node:os').totalmem() / 1048576) });
763
+ {
764
+ if (limits && memoryScope.scopeSupported()) {
765
+ const unit = `sm-chat-${memoryScope.sanitizeUnit(sessionId)}-${attemptNo}-${Date.now()}`;
766
+ const wrapped = memoryScope.wrapInMemoryScope({
767
+ command: target.command, args: target.args || chatArgs, unit, limits,
768
+ });
769
+ // argv0 cannot pass through systemd-run — dropped on the wrapped path only.
770
+ target = { ...target, command: wrapped.command, args: wrapped.args, argv0: undefined };
771
+ }
772
+ }
748
773
  thisChild = spawn(target.command, target.args || chatArgs, {
749
774
  ...(target.argv0 ? { argv0: target.argv0 } : {}),
750
775
  ...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
@@ -765,6 +790,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
765
790
  return;
766
791
  }
767
792
  child = thisChild;
793
+ chatInflight.begin(sessionId, { tabId, cwd, pid: thisChild.pid, startedAt, resume, silent, promptId, origin, worktreeDirHint }).catch(() => {});
768
794
  feedChildStdin(thisChild, fullPrompt, {
769
795
  log: (m) => logs.writeLine({ scope: 'chatRunner', level: 'warn', message: m }),
770
796
  });
@@ -1114,8 +1140,12 @@ function registerAdminRoute(adminHttp) {
1114
1140
  sendJson(res, 400, { ok: false, error: e?.message ?? 'invalid body' });
1115
1141
  return;
1116
1142
  }
1117
- void enqueueExternalPrompt(body.tabId, body.prompt);
1118
- sendJson(res, 200, { ok: true });
1143
+ const outcome = await enqueueExternalPrompt(body.tabId, body.prompt);
1144
+ sendJson(res, 200, {
1145
+ ok: outcome.disposition !== 'refused',
1146
+ disposition: outcome.disposition,
1147
+ ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),
1148
+ });
1119
1149
  });
1120
1150
  }
1121
1151
 
@@ -1172,6 +1202,8 @@ module.exports = {
1172
1202
  run,
1173
1203
  cancel,
1174
1204
  __resetQueueForTests,
1205
+ holdOrphanSession,
1206
+ releaseOrphanSession,
1175
1207
  __liveSessionCount: () => liveSessions.size,
1176
1208
  attachWindow,
1177
1209
  registerChatHandlers,
@@ -1193,6 +1225,7 @@ module.exports = {
1193
1225
  WARN_CEILING_MS,
1194
1226
  __setExecutor,
1195
1227
  enqueueExternalPrompt,
1228
+ settleExternalSend,
1196
1229
  EXTERNAL_SEND_ACK_TIMEOUT_MS,
1197
1230
  requestExternalNewSession,
1198
1231
  registerAdminRoute,
@@ -200,21 +200,93 @@ function heartbeat() {
200
200
  if (stall) logs?.writeLine({ scope: 'crash-diag', ...stall, meta: { ...loop } });
201
201
  }
202
202
 
203
+ const STDERR_TAIL_BYTES = 16 * 1024;
204
+
205
+ // Last 16 KB of the launcher's saved stderr. Best-effort: '' when missing.
206
+ function readStderrTail(dir) {
207
+ let fd = null;
208
+ try {
209
+ fd = fs.openSync(path.join(dir, 'electron-stderr.log'), 'r');
210
+ const size = fs.fstatSync(fd).size;
211
+ const len = Math.min(size, STDERR_TAIL_BYTES);
212
+ const buf = Buffer.alloc(len);
213
+ fs.readSync(fd, buf, 0, len, size - len);
214
+ return buf.toString('utf8');
215
+ } catch { return ''; } finally {
216
+ if (fd !== null) { try { fs.closeSync(fd); } catch { /* ignore */ } }
217
+ }
218
+ }
219
+
220
+ // Newest main-exit.jsonl line for `pid` (format owned by bin/supervise.cjs).
221
+ // Only enum-ish fields are kept: no paths, no message text.
222
+ function readExitRecord(dir, pid) {
223
+ if (!Number.isInteger(pid)) return null;
224
+ try {
225
+ const lines = fs.readFileSync(path.join(dir, 'main-exit.jsonl'), 'utf8').split('\n');
226
+ for (let i = lines.length - 1; i >= 0; i--) {
227
+ if (!lines[i]) continue;
228
+ let rec = null;
229
+ try { rec = JSON.parse(lines[i]); } catch { continue; }
230
+ if (rec && rec.pid === pid) {
231
+ return {
232
+ code: typeof rec.code === 'number' ? rec.code : null,
233
+ signal: typeof rec.signal === 'string' ? rec.signal : null,
234
+ uptimeMs: typeof rec.uptimeMs === 'number' ? rec.uptimeMs : undefined,
235
+ };
236
+ }
237
+ }
238
+ } catch { /* missing or unreadable */ }
239
+ return null;
240
+ }
241
+
242
+ // systemd's verdict on the previous run's scope. Linux only; any failure = no data.
243
+ function readScopeResult(pid, deps) {
244
+ if ((deps.platform || process.platform) !== 'linux' || !Number.isInteger(pid)) return null;
245
+ try {
246
+ const spawnSync = deps.spawnSync || require('node:child_process').spawnSync;
247
+ const r = spawnSync('systemctl', ['--user', 'show', `app-claude-code-session-manager-${pid}.scope`, '-p', 'Result', '--value'],
248
+ { encoding: 'utf8', timeout: 2000 });
249
+ if (!r || r.error || r.status !== 0) return null;
250
+ const out = String(r.stdout || '').trim();
251
+ return out || null;
252
+ } catch { return null; }
253
+ }
254
+
203
255
  // Read the previous run's sentinel. If it was still `open`, the app died
204
256
  // without a clean quit — almost certainly the OOM-kill we're hunting. Log it
205
257
  // as the postmortem the dying process couldn't write, including its last
206
- // memory sample so we can see the footprint at time of death.
207
- function checkPreviousRun() {
258
+ // memory sample so we can see the footprint at time of death. `deps` is
259
+ // injectable for tests.
260
+ function checkPreviousRun(deps = {}) {
261
+ const sPath = deps.sentinelPath || sentinelPath;
262
+ const log = deps.logs !== undefined ? deps.logs : logs;
263
+ const report = deps.reportCrash || reportCrash;
208
264
  let prev = null;
209
- try { prev = JSON.parse(fs.readFileSync(sentinelPath, 'utf8')); } catch { return; }
210
- if (!prev || prev.open !== true) return;
265
+ try { prev = JSON.parse(fs.readFileSync(sPath, 'utf8')); } catch { return; }
266
+ if (!prev) return;
267
+ const dir = path.dirname(sPath);
268
+ // A systemd SIGTERM runs will-quit and marks the sentinel clean, so the scope
269
+ // result is the only witness to an oom-kill in that case.
270
+ const scopeResult = readScopeResult(prev.pid, deps);
271
+ if (scopeResult === 'oom-kill') {
272
+ log?.writeLine({
273
+ scope: 'crash-diag',
274
+ level: 'error',
275
+ message: 'previous session was killed by systemd (oom-scope-stop; scope Result=oom-kill)',
276
+ meta: { prevPid: prev.pid, sentinelOpen: prev.open === true, likelyCause: 'oom-scope-stop' },
277
+ });
278
+ report({ reason: 'oom-scope-stop', meta: { likelyCause: 'oom-scope-stop', sentinelOpen: prev.open === true } });
279
+ }
280
+ if (prev.open !== true) return;
211
281
  const s = prev.lastSample;
212
282
  const lastTop = s && Array.isArray(s.procs) ? [...s.procs].sort((a, b) => b.mb - a.mb).slice(0, 4).map((p) => `${p.type}:${p.mb}MB`) : undefined;
213
283
  const lastLoopDelayMaxMs = prev.loop?.loopDelayMaxMs;
214
284
  const sampleMs = s?.ts ? Date.parse(s.ts) : NaN;
215
285
  const silentGapSec = Number.isFinite(sampleMs) ? Math.round((Date.now() - sampleMs) / 1000) : undefined;
216
- const likelyCause = classifyUncleanShutdown({ lastLoopDelayMaxMs, lastTotalMb: s?.totalMb, silentGapSec });
217
- logs?.writeLine({
286
+ const exitRecord = readExitRecord(dir, prev.pid);
287
+ const stderrTail = readStderrTail(dir);
288
+ const likelyCause = classifyUncleanShutdown({ lastLoopDelayMaxMs, lastTotalMb: s?.totalMb, silentGapSec, exitRecord, stderrTail });
289
+ log?.writeLine({
218
290
  scope: 'crash-diag',
219
291
  level: 'error',
220
292
  message: `previous session ended UNCLEANLY (likelyCause=${likelyCause}; no graceful quit)`,
@@ -229,13 +301,15 @@ function checkPreviousRun() {
229
301
  lastLoopDelayMaxMs,
230
302
  silentGapSec,
231
303
  likelyCause,
304
+ exitRecord,
305
+ scopeResult,
232
306
  hint: 'Check `journalctl -k | grep -i oom` around lastSampleTs to confirm the kernel OOM-killer, and the "main-loop stall" heartbeats before lastSampleTs to confirm a wedged main thread.',
233
307
  },
234
308
  });
235
309
  // The unclean-shutdown postmortem is the report most likely to be the ONLY
236
310
  // thing ever received from a machine that just OOM-killed the app — the
237
311
  // dying process couldn't write it itself. See crashTelemetry.cjs header.
238
- reportCrash({
312
+ report({
239
313
  reason: 'unclean-shutdown',
240
314
  meta: {
241
315
  lastSampleTs: s?.ts,
@@ -246,6 +320,7 @@ function checkPreviousRun() {
246
320
  lastLoopDelayMaxMs,
247
321
  silentGapSec,
248
322
  likelyCause,
323
+ exitRecord,
249
324
  },
250
325
  });
251
326
  }
@@ -327,4 +402,4 @@ function markCleanShutdown() {
327
402
  persistSentinel(true);
328
403
  }
329
404
 
330
- module.exports = { startCrashReporter, init, markCleanShutdown };
405
+ module.exports = { startCrashReporter, init, markCleanShutdown, checkPreviousRun };