claude-code-session-manager 0.125.1 → 0.127.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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +71 -9
  3. package/bin/supervise.cjs +84 -0
  4. package/dist/assets/{AgentLibrary-DjEH5SoY.js → AgentLibrary-DKQznr7o.js} +1 -1
  5. package/dist/assets/{Button-B8NLivk-.js → Button-CZXqmIiM.js} +1 -1
  6. package/dist/assets/{DataModel-CHiBk8m_.js → DataModel-piyV33To.js} +1 -1
  7. package/dist/assets/{History-DttgrJO0.js → History-BxwtrKF2.js} +1 -1
  8. package/dist/assets/{Hooks-Bvy0BH1u.js → Hooks-DogeSPII.js} +1 -1
  9. package/dist/assets/{Library-UbBOgkkP.js → Library-BDt6EeQQ.js} +1 -1
  10. package/dist/assets/{ListDetail-xOyOpVZX.js → ListDetail-CwS-LKar.js} +1 -1
  11. package/dist/assets/{McpServers-CoGL0ddv.js → McpServers-D2HVljgS.js} +1 -1
  12. package/dist/assets/{Memory-Cise856d.js → Memory-hNzuOGn8.js} +1 -1
  13. package/dist/assets/{Panel-Cj72VO5s.js → Panel-BLDrsUeq.js} +1 -1
  14. package/dist/assets/{Permissions-BoJ9AB-G.js → Permissions-DzZ5vaJW.js} +1 -1
  15. package/dist/assets/{Plugins-DfT24sAZ.js → Plugins-Cz9yaxzG.js} +2 -2
  16. package/dist/assets/{ProvenanceBadge-ChkIslT4.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  17. package/dist/assets/{SaveBar-RCXr0jey.js → SaveBar-Shmn699J.js} +1 -1
  18. package/dist/assets/{Scheduler-B70tknnx.js → Scheduler-Bqr0WHNd.js} +1 -1
  19. package/dist/assets/{ScopeSwitcher-p_tgO5Sa.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  20. package/dist/assets/{Settings-wHiAxTfI.js → Settings-Ci8in-yF.js} +1 -1
  21. package/dist/assets/{SkillReferenceGraph-D_Pt35vb.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  22. package/dist/assets/{Skills-DUvOrgw9.js → Skills-BON6o-c4.js} +1 -1
  23. package/dist/assets/{SystemPrompt-BrNIdy68.js → SystemPrompt-D5epIYYs.js} +1 -1
  24. package/dist/assets/{TagLibrary-CDRatxXG.js → TagLibrary-C2qDZROJ.js} +1 -1
  25. package/dist/assets/{TiptapBody-BF8PxUDj.js → TiptapBody-SZhI3-bW.js} +1 -1
  26. package/dist/assets/{Toggle-CQH8NGXW.js → Toggle-C_qFDG0g.js} +1 -1
  27. package/dist/assets/{ViewTabs-DwnxqCVs.js → ViewTabs-C9q5WCEd.js} +1 -1
  28. package/dist/assets/{historyTotals-KINLTHQ4.js → historyTotals-BCl7IOhY.js} +1 -1
  29. package/dist/assets/{index-CfR3NU2t.js → index-CMIYLbPb.js} +581 -581
  30. package/dist/assets/{settingsSchema-BUcHqLnt.js → settingsSchema-BBrRBrBr.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BwwkyuMD.js → skillFrontmatter-B01qJk6N.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Coem9Wg-.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/dist-web/{assets/app.js → app.js} +351 -351
  35. package/dist-web/index.html +2 -2
  36. package/package.json +2 -2
  37. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  38. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  39. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  40. package/scripts/scheduler-mcp-server.cjs +56 -5
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +73 -6
  43. package/src/main/crashDiagnostics.cjs +83 -8
  44. package/src/main/health.cjs +16 -5
  45. package/src/main/index.cjs +32 -0
  46. package/src/main/lib/chatBootRecovery.cjs +136 -0
  47. package/src/main/lib/chatInflight.cjs +88 -0
  48. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  49. package/src/main/lib/epic/epicMint.cjs +6 -0
  50. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  51. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  52. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  53. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  54. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  56. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  57. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  58. package/src/main/lib/git/gitExec.cjs +11 -1
  59. package/src/main/lib/git/gitWorktree.cjs +255 -9
  60. package/src/main/lib/git/jobWorktree.cjs +5 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +27 -5
  62. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  63. package/src/main/lib/persona-macro/macroLibrary.cjs +78 -3
  64. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  65. package/src/main/lib/prd/prdCreate.cjs +5 -1
  66. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  67. package/src/main/lib/process/childWithLog.cjs +38 -95
  68. package/src/main/lib/process/memoryScope.cjs +140 -0
  69. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  70. package/src/main/lib/process/procIdentity.cjs +10 -3
  71. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  72. package/src/main/lib/promptSessionSchema.cjs +6 -1
  73. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  74. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  75. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  76. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  78. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  79. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  80. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  81. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  82. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  83. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  84. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  85. package/src/main/runVerify.cjs +59 -110
  86. package/src/main/scheduler/budget.cjs +31 -0
  87. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  88. package/src/main/scheduler/prdPaths.cjs +54 -0
  89. package/src/main/scheduler/reviewLadder.cjs +28 -5
  90. package/src/main/scheduler/starvation.cjs +22 -0
  91. package/src/main/scheduler.cjs +662 -90
  92. package/src/main/templates/PRD_AUTHORING.md +10 -3
  93. package/src/main/usage.cjs +4 -2
  94. package/src/main/webRemote.cjs +3 -0
  95. package/src/preload/api.d.ts +19 -3
  96. package/src/seed/agents/demo-video-builder.md +62 -14
  97. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -7,8 +7,8 @@
7
7
  <link rel="preconnect" href="https://fonts.googleapis.com">
8
8
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
9
  <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;0,6..72,700;1,6..72,400&family=Geist:wght@300;400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
10
- <script type="module" crossorigin src="./assets/app.js"></script>
11
- <link rel="stylesheet" crossorigin href="./assets/app.css">
10
+ <script type="module" crossorigin src="./app.js"></script>
11
+ <link rel="stylesheet" crossorigin href="./app.css">
12
12
  </head>
13
13
  <body class="bg-bg text-fg font-sans antialiased">
14
14
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.125.1",
3
+ "version": "0.127.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",
@@ -37,7 +37,7 @@
37
37
  "dev": "concurrently -k -n vite,electron -c magenta,cyan \"npm:dev:renderer\" \"npm:dev:electron\"",
38
38
  "dev:renderer": "vite",
39
39
  "dev:electron": "wait-on http://localhost:5173 && SM_DEV=1 electron .",
40
- "build": "vite build && vite build --config vite.web.config.ts",
40
+ "build": "vite build && vite build --config vite.web.config.ts && node scripts/check-dist-web.cjs",
41
41
  "build:web": "vite build --config vite.web.config.ts",
42
42
  "dist:stage": "npm run build && node scripts/package/stage.cjs",
43
43
  "dist:mac": "npm run dist:stage && electron-builder --config electron-builder.yml --mac --publish never",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "session-manager-dev",
3
3
  "description": "The default end-to-end development skillset for the Claude Code Session Manager: decompose work into scheduler PRDs and track them to a validated finish (/develop), publish releases to npm (/builder), and hand a finding to another project on this machine (/send-feedback). Together with the session-manager scheduler these form a develop → queue → validate → release loop.",
4
- "version": "0.2.2",
4
+ "version": "0.2.3",
5
5
  "author": {
6
6
  "name": "Bilko Bibitkov",
7
7
  "email": "BilkoBibitkov2000@gmail.com",
@@ -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
@@ -148,6 +148,14 @@ stays a plain proposal. If the quote cannot be verified, the call silently falls
148
148
  back to a normal `proposed` session (the result note gives the reason), so
149
149
  report it as a proposal in that case.
150
150
 
151
+ **Auto-start from a macro.** If the human started THIS session by pressing a
152
+ macro whose auto-start setting allows the target project, bug and feature
153
+ proposals there start without any quote: pass no `autoStart` flag and no
154
+ `humanRequestQuote`, and do not try to set the setting yourself (it is edited
155
+ only in the macro editor). It reaches only that one hop, at most 5 times per
156
+ session, and `discussion` or other tags stay plain proposals. The result status
157
+ tells you which happened.
158
+
151
159
  `fromEpicId` is filled in automatically from your running session; pass it
152
160
  explicitly only if you know it and the auto-fill failed. When it resolves, a
153
161
  receipt is chained onto your own session's event log so your transcript records
@@ -161,8 +169,8 @@ human sees the motivation, plan and acceptance criteria on the proposal before
161
169
  approving.
162
170
 
163
171
  If the result status is `auto-approved`, say instead that the session was
164
- auto-approved on the human's request and is starting in `<toCwd>` — not that it
165
- is done.
172
+ auto-approved (on the human's request, or by the macro they pressed) and is
173
+ starting in `<toCwd>` — not that it is done.
166
174
 
167
175
  Do **not** say the other project has been notified-and-is-working-on-it, that
168
176
  the bug is filed/fixed/assigned, or that you'll follow up when they respond.
@@ -16,6 +16,7 @@
16
16
  *
17
17
  * macro_list({ cwd? }) -> GET /admin/macros?cwd=<encoded>
18
18
  * macro_save({ cwd?, id?, label, agentName, tag, prompt }) -> POST /admin/macros/save
19
+ * macro_delete({ id }) -> POST /admin/macros/delete
19
20
  * customer_feedback_list({ pull?, includeHidden? }) -> GET /admin/customer-feedback/inbox
20
21
  * customer_feedback_set_status({ id, status, note? }) -> POST /admin/customer-feedback/status
21
22
  *
@@ -200,6 +201,15 @@ const CREATE_PRD_ITEM_SCHEMA = {
200
201
  type: 'string',
201
202
  description: 'Optional: WHO executes this PRD — the persona name (a file at ~/.claude/agents/<name>.md, e.g. "dev-lead") the executor should adopt. Distinct from `tag` (what kind of work); this is who does it. Defaults to "dev-lead" when omitted. Rejected at write time if the name does not resolve to a readable persona file.',
202
203
  },
204
+ deliverable: {
205
+ type: 'string',
206
+ enum: ['artifact'],
207
+ description: 'Optional: set to "artifact" ONLY when this PRD truthfully lands no commit (publish, live migration, probe) and instead writes git-excluded output files during the run. Requires artifactPaths. A no-commit PRD with no declaration parks in needs_review.',
208
+ },
209
+ artifactPaths: {
210
+ type: 'array', items: { type: 'string' },
211
+ description: 'Required with deliverable: "artifact" (and refused without it): every git-excluded file this PRD writes during the run, e.g. a built file in a gitignored folder. Relative paths, never containing "..", no commas or brackets. Each must be non-empty and freshly written.',
212
+ },
203
213
  quietMachine: {
204
214
  type: 'boolean',
205
215
  description: 'Optional: set true only when this PRD\'s acceptance criteria are wall-clock/timing measurements (frame time, performance fences) that CPU contention from concurrent jobs would invalidate. The scheduler dispatches it only once zero other jobs are running machine-wide, and holds every other job off the whole slot pool for its run — a whole-machine exclusive lease, not a per-project one. If the machine never goes quiet within the configured wait window (default 30 minutes), it dispatches anyway and is marked degraded. Opt-in only; omit for ordinary PRDs.',
@@ -377,7 +387,7 @@ const TOOLS = [
377
387
  inputSchema: {
378
388
  type: 'object',
379
389
  properties: {
380
- tabId: { type: 'string', description: 'Target tab id (claudeSessionId) that must already be open in the app' },
390
+ 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." },
381
391
  prompt: { type: 'string', description: 'Prompt text to enqueue' },
382
392
  },
383
393
  required: ['tabId', 'prompt'],
@@ -454,7 +464,7 @@ const TOOLS = [
454
464
  },
455
465
  humanRequestQuote: {
456
466
  type: 'string',
457
- description: "Required with autoStart. Copy VERBATIM from the human's own message in this conversation; that message must name the target project. Do not paraphrase or write it yourself.",
467
+ description: "Required with autoStart. Copy VERBATIM from the human's own message in this conversation; the quoted words themselves must name the target project. Do not paraphrase or write it yourself.",
458
468
  },
459
469
  },
460
470
  required: ['toCwd', 'fromCwd', 'title', 'motivation', 'acceptanceCriteria', 'body'],
@@ -535,6 +545,17 @@ const TOOLS = [
535
545
  required: ['label', 'agentName', 'tag', 'prompt'],
536
546
  },
537
547
  },
548
+ {
549
+ name: 'macro_delete',
550
+ description: descriptionFor('macro_delete'),
551
+ inputSchema: {
552
+ type: 'object',
553
+ properties: {
554
+ id: { type: 'string', description: 'Id of the macro to remove, from macro_list.' },
555
+ },
556
+ required: ['id'],
557
+ },
558
+ },
538
559
  {
539
560
  name: 'customer_feedback_list',
540
561
  description: descriptionFor('customer_feedback_list'),
@@ -572,6 +593,19 @@ const TOOLS = [
572
593
  },
573
594
  ];
574
595
 
596
+ // A macro is a human's button and its delete cannot be undone, so this runs
597
+ // only in a session a human is attached to. headlessQueueRefusal does not fit:
598
+ // it lets an architect job through.
599
+ function macroDeleteRefusal() {
600
+ if (process.env.SM_SCHEDULER_JOB_SLUG || !process.env.SM_CHAT_SESSION_ID) {
601
+ return errorResult(
602
+ 'refused: macro_delete runs only in a Session Manager chat or terminal session, because a macro goes only when a human asks. '
603
+ + 'Say in your final result which macro should go; the human can remove it from the HOT KEYS panel.',
604
+ );
605
+ }
606
+ return null;
607
+ }
608
+
575
609
  // Named + exported (see module.exports below) so mcpToolCatalog.test.cjs's
576
610
  // sibling can exercise session_manager_help's argument handling directly —
577
611
  // mocking node:fs/promises + global.fetch to drive adminRequest — without
@@ -777,7 +811,11 @@ async function handleCallTool(request) {
777
811
  // Epic and chain a receipt onto it. Never invents an Epic — an
778
812
  // unresolvable id just means no receipt.
779
813
  const payload = { ...args };
780
- if (!payload.fromEpicId && process.env.SM_CHAT_SESSION_ID) {
814
+ // payload starts as a copy of args: drop any caller-supplied identity so
815
+ // only this process's own env can vouch for the session (a scheduled PRD
816
+ // job has no SM_CHAT_SESSION_ID and so cannot claim one).
817
+ delete payload.originClaudeSessionId;
818
+ if (process.env.SM_CHAT_SESSION_ID) {
781
819
  payload.originClaudeSessionId = process.env.SM_CHAT_SESSION_ID;
782
820
  }
783
821
  // See scheduler_create_prd's own SM_PROJECT_ROOT forwarding above.
@@ -792,10 +830,10 @@ async function handleCallTool(request) {
792
830
  let note = '';
793
831
  if (result?.ok !== false) {
794
832
  if (result?.status === 'auto-approved') {
795
- note = ' — auto-approved on the human\'s explicit request; the session is starting in the receiving project. No reply channel; the work is not done yet.';
833
+ note = ' — the session was auto-approved and is starting in the receiving project. No reply channel; the work is not done yet.';
796
834
  } else {
797
835
  note = ' — delivered as a PROPOSED session in the receiving project; it runs only if a human there presses Approve & start. No reply channel.';
798
- if (args.autoStart && result?.autoStart && result.autoStart.granted !== true && result.autoStart.reason) {
836
+ if (result?.autoStart && result.autoStart.granted === false && result.autoStart.reason) {
799
837
  note += ` Auto-start was requested but not granted: ${result.autoStart.reason}`;
800
838
  }
801
839
  }
@@ -857,6 +895,19 @@ async function handleCallTool(request) {
857
895
  const result = await adminRequest('POST', '/admin/macros/save', payload);
858
896
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
859
897
  }
898
+ if (name === 'macro_delete') {
899
+ const refusal = macroDeleteRefusal();
900
+ if (refusal) return refusal;
901
+ if (!args || typeof args.id !== 'string' || !args.id) return errorResult('missing or invalid required argument: id');
902
+ // No args: this tool never takes a project from the caller. mcpStdioServer enforces no input schema.
903
+ const result = await adminRequest('POST', '/admin/macros/delete', {
904
+ cwd: resolveCwdArg(),
905
+ id: args.id,
906
+ originClaudeSessionId: process.env.SM_CHAT_SESSION_ID,
907
+ });
908
+ if (result?.ok === false) return errorResult(result.error ?? 'macro_delete failed');
909
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
910
+ }
860
911
  if (name === 'customer_feedback_list') {
861
912
  const qs = new URLSearchParams();
862
913
  if (!args || args.pull !== false) qs.set('pull', '1');
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.125.1",
3
- "gitSha": "043d76f7e5838adb777089e411f4b729c2645357",
4
- "gitShortSha": "043d76f7",
2
+ "version": "0.127.0",
3
+ "gitSha": "40558ffe7293dc3e982e98ea4eb282c9c72824c9",
4
+ "gitShortSha": "40558ffe",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-10-31T03:51:27.358Z",
6
+ "builtAt": "2026-11-03T03:08:26.011Z",
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).
@@ -269,6 +271,29 @@ const SCHEDULER_TURN_INSTRUCTION =
269
271
  `Make the safest reasonable choice for anything left open, and end with a short report ` +
270
272
  `of what you did.\n\n`;
271
273
 
274
+ /**
275
+ * Picks the instruction block that opens a turn: scheduler turns and
276
+ * auto-started inbound Epics have no human watching, so they never ask.
277
+ */
278
+ /** Only the first (inbound-proposal) turn earns a follow-up; scheduler turns never chain. */
279
+ function shouldFollowUp(origin) {
280
+ return origin === 'inbound-proposal';
281
+ }
282
+
283
+ function turnInstructionFor(origin, cwd, sessionId) {
284
+ if (origin === 'scheduler') {
285
+ // An auto-started Epic with no PRDs needs /develop Phase 1 (plan), not Phase 2.
286
+ const auto = require('./lib/feedback-remote/autoStartedSession.cjs');
287
+ if (auto.autoStartNeedsPlan(cwd, sessionId)) return auto.autoStartTurnInstruction(STOP_SENTINEL);
288
+ return SCHEDULER_TURN_INSTRUCTION;
289
+ }
290
+ if (origin === 'inbound-proposal') {
291
+ const auto = require('./lib/feedback-remote/autoStartedSession.cjs');
292
+ if (auto.isAutoStartedEpic(cwd, sessionId)) return auto.autoStartTurnInstruction(STOP_SENTINEL);
293
+ }
294
+ return STOP_SIGNAL_INSTRUCTION;
295
+ }
296
+
272
297
  // tab+prompt keys of scheduler-originated prompts awaiting their run() (consumed once).
273
298
  const schedulerPrompts = new Map();
274
299
  const SCHEDULER_PROMPT_TTL_MS = 6 * 60 * 60 * 1000;
@@ -341,6 +366,11 @@ const dispatching = new Set();
341
366
  // "Session ID … is already in use", so pump() refuses to start a second run
342
367
  // for a held sessionId (it waits in `waiting` like any other blocked run).
343
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(); }
344
374
  // Submissions parked while a New Epic's fire-and-forget worktree mint is still in
345
375
  // flight (tabId → opts). Counted by run()'s tabBusy; cancel() can drop them.
346
376
  const pendingStart = new Map();
@@ -359,6 +389,7 @@ function __resetQueueForTests() {
359
389
  inFlight.clear();
360
390
  dispatching.clear();
361
391
  liveSessions.clear();
392
+ orphanSessions.clear();
362
393
  waiting.length = 0;
363
394
  pendingStart.clear();
364
395
  sessionSlots.__resetForTests();
@@ -407,6 +438,7 @@ function run(opts) {
407
438
  const tabBusy = inFlight.has(opts.tabId)
408
439
  || dispatching.has(opts.tabId)
409
440
  || liveSessions.has(opts.sessionId)
441
+ || orphanSessions.has(opts.sessionId)
410
442
  || pendingStart.has(opts.tabId)
411
443
  || waiting.some((w) => w.tabId === opts.tabId);
412
444
  if (tabBusy && opts.silent) {
@@ -446,7 +478,7 @@ function pump() {
446
478
  // synchronous sweep of this loop could start two runs for the same tab and
447
479
  // race two --resume processes against a single sessionId.
448
480
  const idx = waiting.findIndex((w) => !inFlight.has(w.tabId) && !dispatching.has(w.tabId)
449
- && !liveSessions.has(w.sessionId));
481
+ && !liveSessions.has(w.sessionId) && !orphanSessions.has(w.sessionId));
450
482
  // Everything queued is blocked behind its own tab's live run; the settle()
451
483
  // of that run re-pumps.
452
484
  if (idx === -1) break;
@@ -509,6 +541,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
509
541
  const settle = () => {
510
542
  if (settled) return;
511
543
  settled = true;
544
+ chatInflight.end(sessionId).catch(() => {});
512
545
  inFlight.delete(tabId);
513
546
  resolve();
514
547
  };
@@ -581,7 +614,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
581
614
 
582
615
  // Prepend the stop-signal protocol instruction and the chat-mode truth
583
616
  // instruction to every prompt
584
- const fullPrompt = (origin === 'scheduler' ? SCHEDULER_TURN_INSTRUCTION : STOP_SIGNAL_INSTRUCTION)
617
+ const fullPrompt = turnInstructionFor(origin, cwd, sessionId)
585
618
  + CHAT_MODE_TRUTH_INSTRUCTION + prompt;
586
619
 
587
620
  // sessionId is the Epic's claudeSessionId for an Epic-backed tab (see
@@ -719,9 +752,24 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
719
752
  // stdout is piped for real-time NDJSON streaming; stderr piped for
720
753
  // error-message capture.
721
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.
722
758
  try {
723
759
  const chatArgs = buildArgs(resumeFlag);
724
- 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
+ }
725
773
  thisChild = spawn(target.command, target.args || chatArgs, {
726
774
  ...(target.argv0 ? { argv0: target.argv0 } : {}),
727
775
  ...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
@@ -742,6 +790,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
742
790
  return;
743
791
  }
744
792
  child = thisChild;
793
+ chatInflight.begin(sessionId, { tabId, cwd, pid: thisChild.pid, startedAt, resume, silent, promptId, origin, worktreeDirHint }).catch(() => {});
745
794
  feedChildStdin(thisChild, fullPrompt, {
746
795
  log: (m) => logs.writeLine({ scope: 'chatRunner', level: 'warn', message: m }),
747
796
  });
@@ -830,6 +879,15 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
830
879
  console.error('[chatRunner] recordExchange failed:', err?.message ?? err);
831
880
  });
832
881
  }
882
+ if (shouldFollowUp(origin)) {
883
+ try {
884
+ require('./lib/feedback-remote/autoStartedSession.cjs').autoStartFollowUp({
885
+ cwd, tabId, sessionId, send: enqueueExternalPrompt,
886
+ });
887
+ } catch (err) {
888
+ console.error('[chatRunner] auto-start follow-up failed:', err?.message ?? err);
889
+ }
890
+ }
833
891
  }
834
892
  } else {
835
893
  emitTerminal('chat:run:error', {
@@ -1082,8 +1140,12 @@ function registerAdminRoute(adminHttp) {
1082
1140
  sendJson(res, 400, { ok: false, error: e?.message ?? 'invalid body' });
1083
1141
  return;
1084
1142
  }
1085
- void enqueueExternalPrompt(body.tabId, body.prompt);
1086
- 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
+ });
1087
1149
  });
1088
1150
  }
1089
1151
 
@@ -1113,7 +1175,7 @@ function registerChatHandlers() {
1113
1175
  // A user send is always accepted now (queued behind the tab's live run if
1114
1176
  // one holds it), but the renderer gets the truth either way rather than a
1115
1177
  // success it can't verify.
1116
- const outcome = run({ tabId, sessionId, prompt, cwd, resume: !!resume, promptId });
1178
+ const outcome = run({ tabId, sessionId, prompt, cwd, resume: !!resume, promptId, origin });
1117
1179
  return { ok: outcome.accepted !== false, queued: !!outcome.queued, reason: outcome.reason };
1118
1180
  }));
1119
1181
 
@@ -1140,10 +1202,14 @@ module.exports = {
1140
1202
  run,
1141
1203
  cancel,
1142
1204
  __resetQueueForTests,
1205
+ holdOrphanSession,
1206
+ releaseOrphanSession,
1143
1207
  __liveSessionCount: () => liveSessions.size,
1144
1208
  attachWindow,
1145
1209
  registerChatHandlers,
1146
1210
  noteChatRunOrigin,
1211
+ turnInstructionFor,
1212
+ shouldFollowUp,
1147
1213
  parseStopSignal,
1148
1214
  splitStopSignal,
1149
1215
  parseContextUsageMarkdown,
@@ -1159,6 +1225,7 @@ module.exports = {
1159
1225
  WARN_CEILING_MS,
1160
1226
  __setExecutor,
1161
1227
  enqueueExternalPrompt,
1228
+ settleExternalSend,
1162
1229
  EXTERNAL_SEND_ACK_TIMEOUT_MS,
1163
1230
  requestExternalNewSession,
1164
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 };
@@ -88,6 +88,13 @@ function readFreshHeartbeat(heartbeatPath) {
88
88
  return entry;
89
89
  }
90
90
 
91
+ // Last tick's reason + detail from a heartbeat's dispatch block; both null
92
+ // when the heartbeat or its dispatch is missing.
93
+ function lastTickFromHeartbeat(heartbeat) {
94
+ const d = heartbeat?.dispatch;
95
+ return { lastTickReason: d?.lastTickReason ?? null, lastTickDetail: d?.lastTickDetail ?? null };
96
+ }
97
+
91
98
  // Evaluates whether the scheduler tick looks stalled: pending work exists,
92
99
  // there's free capacity to run it, and nothing about the queue's own state
93
100
  // explains why it hasn't. Kept as a pure function of (queueState, heartbeat,
@@ -762,8 +769,8 @@ function evaluateCredentialHealth({ credState, now = Date.now() } = {}) {
762
769
  * latestStarveEscalationReasons); a cwd with no recorded reason yet reports
763
770
  * 'unknown' rather than failing.
764
771
  */
765
- function evaluateStarveEscalationHealth(jobs, now, thresholdMs, escalationReasons = {}) {
766
- const starved = findStarvedProjects(jobs, now, thresholdMs);
772
+ function evaluateStarveEscalationHealth(jobs, now, thresholdMs, escalationReasons = {}, lastDispatchAtByCwd = {}) {
773
+ const starved = findStarvedProjects(jobs, now, thresholdMs, lastDispatchAtByCwd);
767
774
  if (starved.length === 0) return { ok: true };
768
775
  const projects = starved.map((sp) => ({
769
776
  cwd: sp.cwd,
@@ -988,9 +995,11 @@ async function check(opts = {}) {
988
995
  machineStateRecovered: queueState.machineStateRecovered ?? false,
989
996
  quarantinedCwds: (queueState.unreadableCwds ?? []).map((u) => u.cwd),
990
997
  machineStateRecoveryMode: queueState.machineStateRecoveryMode ?? null,
991
- // Informational only (PRD 1085): current 1-min loadavg per core vs the
992
- // launch-gate threshold, so a "nothing is launching" report can be
993
- // read next to the reason without opening the app.
998
+ ...lastTickFromHeartbeat(heartbeat),
999
+ // Informational only (PRD 1085): the RAW 1-min loadavg per core vs the
1000
+ // launch-gate threshold, with no CPU sample behind it (the gate also
1001
+ // checks a CPU sample, so a ratio over threshold is not a hold). Read it
1002
+ // beside lastTickReason / lastTickDetail above.
994
1003
  loadRatio: (() => {
995
1004
  const cores = (os.cpus() || []).length;
996
1005
  const l1 = os.loadavg()[0];
@@ -1066,6 +1075,7 @@ async function check(opts = {}) {
1066
1075
  // the exact condition the 2026-09-12 19h Bilko starve went unreported by.
1067
1076
  status.components.project_starve_escalation = evaluateStarveEscalationHealth(
1068
1077
  queueState.jobs, now, STARVE_ESCALATION_MS, latestStarveEscalationReasons(auditLogPath()),
1078
+ queueState.lastDispatchAtByCwd,
1069
1079
  );
1070
1080
  if (!status.components.project_starve_escalation.ok) {
1071
1081
  status.issues.push(status.components.project_starve_escalation.message);
@@ -1414,6 +1424,7 @@ module.exports = {
1414
1424
  check,
1415
1425
  evaluateTickLiveness,
1416
1426
  readFreshHeartbeat,
1427
+ lastTickFromHeartbeat,
1417
1428
  evaluatePrdMigrationHealth,
1418
1429
  evaluateDelegationChainHealth,
1419
1430
  evaluateCredentialHealth,