claude-code-session-manager 0.126.0 → 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 (75) hide show
  1. package/bin/cli.cjs +71 -9
  2. package/bin/supervise.cjs +84 -0
  3. package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-DKQznr7o.js} +1 -1
  4. package/dist/assets/{Button-8dWfDDuQ.js → Button-CZXqmIiM.js} +1 -1
  5. package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-piyV33To.js} +1 -1
  6. package/dist/assets/{History-hsztE6yh.js → History-BxwtrKF2.js} +1 -1
  7. package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-DogeSPII.js} +1 -1
  8. package/dist/assets/{Library-Czt3Bojd.js → Library-BDt6EeQQ.js} +1 -1
  9. package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-CwS-LKar.js} +1 -1
  10. package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-D2HVljgS.js} +1 -1
  11. package/dist/assets/{Memory-caujO8O3.js → Memory-hNzuOGn8.js} +1 -1
  12. package/dist/assets/{Panel-D64i9tGz.js → Panel-BLDrsUeq.js} +1 -1
  13. package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-DzZ5vaJW.js} +1 -1
  14. package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-Cz9yaxzG.js} +2 -2
  15. package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  16. package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-Shmn699J.js} +1 -1
  17. package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-Bqr0WHNd.js} +1 -1
  18. package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  19. package/dist/assets/{Settings-Bcf65bpL.js → Settings-Ci8in-yF.js} +1 -1
  20. package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  21. package/dist/assets/{Skills-DwnQKJVc.js → Skills-BON6o-c4.js} +1 -1
  22. package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-D5epIYYs.js} +1 -1
  23. package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-C2qDZROJ.js} +1 -1
  24. package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-SZhI3-bW.js} +1 -1
  25. package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C_qFDG0g.js} +1 -1
  26. package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-C9q5WCEd.js} +1 -1
  27. package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-BCl7IOhY.js} +1 -1
  28. package/dist/assets/{index-DgPUERhe.js → index-CMIYLbPb.js} +73 -73
  29. package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-BBrRBrBr.js} +1 -1
  30. package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-B01qJk6N.js} +1 -1
  31. package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  32. package/dist/index.html +1 -1
  33. package/dist-web/app.js +307 -307
  34. package/package.json +1 -1
  35. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  36. package/scripts/scheduler-mcp-server.cjs +39 -1
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/chatRunner.cjs +37 -4
  39. package/src/main/crashDiagnostics.cjs +83 -8
  40. package/src/main/health.cjs +16 -5
  41. package/src/main/index.cjs +32 -0
  42. package/src/main/lib/chatBootRecovery.cjs +136 -0
  43. package/src/main/lib/chatInflight.cjs +88 -0
  44. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  45. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  46. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  47. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  48. package/src/main/lib/mcpToolCatalog.cjs +22 -3
  49. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  50. package/src/main/lib/persona-macro/macroLibrary.cjs +57 -3
  51. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  52. package/src/main/lib/prd/prdCreate.cjs +5 -1
  53. package/src/main/lib/process/childWithLog.cjs +38 -95
  54. package/src/main/lib/process/memoryScope.cjs +140 -0
  55. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  56. package/src/main/lib/process/procIdentity.cjs +10 -3
  57. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  58. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  59. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  60. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  61. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  62. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  63. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  64. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  65. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  66. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  67. package/src/main/scheduler/budget.cjs +31 -0
  68. package/src/main/scheduler/prdPaths.cjs +54 -0
  69. package/src/main/scheduler/reviewLadder.cjs +17 -0
  70. package/src/main/scheduler/starvation.cjs +22 -0
  71. package/src/main/scheduler.cjs +522 -68
  72. package/src/main/templates/PRD_AUTHORING.md +5 -2
  73. package/src/main/usage.cjs +4 -2
  74. package/src/preload/api.d.ts +12 -2
  75. package/src/seed/agents/demo-video-builder.md +62 -14
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.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",
@@ -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
@@ -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
  *
@@ -386,7 +387,7 @@ const TOOLS = [
386
387
  inputSchema: {
387
388
  type: 'object',
388
389
  properties: {
389
- 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." },
390
391
  prompt: { type: 'string', description: 'Prompt text to enqueue' },
391
392
  },
392
393
  required: ['tabId', 'prompt'],
@@ -544,6 +545,17 @@ const TOOLS = [
544
545
  required: ['label', 'agentName', 'tag', 'prompt'],
545
546
  },
546
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
+ },
547
559
  {
548
560
  name: 'customer_feedback_list',
549
561
  description: descriptionFor('customer_feedback_list'),
@@ -581,6 +593,19 @@ const TOOLS = [
581
593
  },
582
594
  ];
583
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
+
584
609
  // Named + exported (see module.exports below) so mcpToolCatalog.test.cjs's
585
610
  // sibling can exercise session_manager_help's argument handling directly —
586
611
  // mocking node:fs/promises + global.fetch to drive adminRequest — without
@@ -870,6 +895,19 @@ async function handleCallTool(request) {
870
895
  const result = await adminRequest('POST', '/admin/macros/save', payload);
871
896
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
872
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
+ }
873
911
  if (name === 'customer_feedback_list') {
874
912
  const qs = new URLSearchParams();
875
913
  if (!args || args.pull !== false) qs.set('pull', '1');
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.126.0",
3
- "gitSha": "52a58ff337bbb86c0de1841f70b2220fce04877a",
4
- "gitShortSha": "52a58ff3",
2
+ "version": "0.127.0",
3
+ "gitSha": "40558ffe7293dc3e982e98ea4eb282c9c72824c9",
4
+ "gitShortSha": "40558ffe",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-10-31T16:13:41.329Z",
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).
@@ -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 };
@@ -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,
@@ -29,6 +29,7 @@ const { createProjectFolder } = require('./lib/projectFolder.cjs');
29
29
  const { cleanChildEnv } = require('./lib/process/cleanEnv.cjs');
30
30
  const { applyLoginShellPath } = require('./lib/process/loginShellPath.cjs');
31
31
  const { terminateLosingInstance } = require('./lib/process/singleInstanceGuard.cjs');
32
+ const { ensureScopeOomPolicy } = require('./lib/process/scopeOomPolicy.cjs');
32
33
  const { acquireSchedulerOwnership, releaseSchedulerOwnership } = require('./lib/process/instanceLock.cjs');
33
34
  const { manager: ptyManager, registerPtyHandlers } = require('./pty.cjs');
34
35
  const configMgr = require('./config.cjs');
@@ -1086,6 +1087,29 @@ try {
1086
1087
  logs.writeLine({ scope: 'main', level: 'error', message: 'ops retention IPC registration failed', meta: { error: e?.message } });
1087
1088
  }
1088
1089
  chatRunner.registerChatHandlers();
1090
+ // Boot recovery of chat turns that were in flight when the app last died (once, after handlers).
1091
+ try {
1092
+ const chatInflight = require('./lib/chatInflight.cjs');
1093
+ const { identity } = require('./lib/process/procIdentity.cjs');
1094
+ require('./lib/chatBootRecovery.cjs').recoverInflightTurns({
1095
+ ledger: chatInflight,
1096
+ run: (o) => chatRunner.run(o),
1097
+ holdOrphan: chatRunner.holdOrphanSession,
1098
+ releaseOrphan: chatRunner.releaseOrphanSession,
1099
+ identityOf: identity,
1100
+ sessionTurnState: async (entry) => {
1101
+ try {
1102
+ const { resolveEpicTranscriptPath } = require('./lib/epic/epicTranscriptPath.cjs');
1103
+ const { readTranscriptTail } = require('./lib/epic/epicDelegationStats.cjs');
1104
+ const filePath = resolveEpicTranscriptPath({ cwd: entry.cwd, claudeSessionId: entry.sessionId }).path;
1105
+ if (!filePath) return 'missing';
1106
+ return require('./lib/chatBootRecovery.cjs').classifyTurnTail(readTranscriptTail(filePath));
1107
+ } catch { return 'missing'; }
1108
+ },
1109
+ }).catch((e) => logs.writeLine({ scope: 'main', level: 'error', message: 'chat boot recovery failed', meta: { error: e?.message } }));
1110
+ } catch (e) {
1111
+ logs.writeLine({ scope: 'main', level: 'error', message: 'chat boot recovery wiring failed', meta: { error: e?.message } });
1112
+ }
1089
1113
 
1090
1114
  // Direct in-process PRD authoring for a queued PromptTicket classified
1091
1115
  // 'develop' (PRD 749 follow-up) — calls the same createPrd() the admin HTTP
@@ -1223,6 +1247,7 @@ app.on('web-contents-created', (_e, wc) => {
1223
1247
  app.whenReady().then(async () => {
1224
1248
  logs.pruneOld();
1225
1249
  logs.writeLine({ scope: 'main', level: 'info', message: 'app start', meta: { version: app.getVersion(), platform: process.platform } });
1250
+ logs.writeLine({ scope: 'main', level: 'info', message: 'ozone platform', meta: { ozonePlatform: app.commandLine.getSwitchValue('ozone-platform') || 'default', override: process.env.SM_OZONE_PLATFORM || null } });
1226
1251
 
1227
1252
  // Crash/OOM diagnostics: logs a postmortem if the PREVIOUS run died
1228
1253
  // uncleanly (the silent OOM-kill we've been chasing), then starts the memory
@@ -1456,6 +1481,13 @@ app.whenReady().then(async () => {
1456
1481
  // owner's running job and overwrote admin-api.json. Losing instances run
1457
1482
  // scheduler-PASSIVE: read IPC still works (handlers registered above),
1458
1483
  // nothing mutates.
1484
+ // Child OOM-kill must not stop the whole app scope (OOMPolicy=continue drop-in).
1485
+ try {
1486
+ const oom = ensureScopeOomPolicy({ log: (m) => logs.writeLine({ scope: 'main', level: 'warn', message: m }) });
1487
+ logs.writeLine({ scope: 'main', level: 'info', message: 'scope OOM policy', meta: oom });
1488
+ } catch (e) {
1489
+ logs.writeLine({ scope: 'main', level: 'warn', message: 'scope OOM policy failed', meta: { error: e?.message } });
1490
+ }
1459
1491
  const ownership = acquireSchedulerOwnership();
1460
1492
  if (ownership.owner) {
1461
1493
  scheduler.init().catch((e) => {
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Boot recovery for chat turns that were in flight when the app died
5
+ * (ledger: lib/chatInflight.cjs). Per ledger entry:
6
+ * - pid alive AND it is an sm-claude-chat process for that sessionId → orphan: hold the
7
+ * session in chatRunner so run() queues instead of spawning a second writer, poll until
8
+ * it exits, then treat it as dead;
9
+ * - dead (or recycled pid) → Claude's own session JSONL decides (classifyTurnTail): finished or
10
+ * missing, or a silent entry → just clear the entry; unfinished → re-run ONCE through
11
+ * chatRunner.run() with the same sessionId and a fixed continue prompt, at most once per
12
+ * session per 24 h.
13
+ * Touches only the session's own turn: never mints an Epic or edits its title/objective/status.
14
+ */
15
+
16
+ const DAY_MS = 24 * 60 * 60 * 1000;
17
+ const ORPHAN_POLL_MS = 5000;
18
+
19
+ const CONTINUE_PROMPT = 'The Session Manager app restarted while your previous turn was running. '
20
+ + 'Check what already landed (files, git status, commits, tool results) before repeating any step, '
21
+ + 'then continue the interrupted work from where it stopped.';
22
+
23
+ function defaultPidAlive(pid) {
24
+ if (!Number.isInteger(pid) || pid <= 0) return false;
25
+ try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
26
+ }
27
+
28
+ function isChatProcessFor(identity, sessionId) {
29
+ const cmd = identity && typeof identity.cmdline === 'string' ? identity.cmdline : '';
30
+ return cmd.includes('sm-claude-chat') && cmd.includes(sessionId);
31
+ }
32
+
33
+ /**
34
+ * Classify the tail of a Claude session JSONL.
35
+ * @param {string} text
36
+ * @returns {'finished'|'unfinished'|'missing'}
37
+ */
38
+ function classifyTurnTail(text) {
39
+ if (typeof text !== 'string' || !text) return 'missing';
40
+ const lines = text.split('\n');
41
+ for (let i = lines.length - 1; i >= 0; i--) {
42
+ const t = lines[i].trim();
43
+ if (!t) continue;
44
+ let obj;
45
+ try { obj = JSON.parse(t); } catch { continue; }
46
+ if (!obj || typeof obj !== 'object') continue;
47
+ if (obj.type === 'user') return 'unfinished';
48
+ if (obj.type === 'assistant') {
49
+ const sr = obj.message && obj.message.stop_reason;
50
+ return sr != null && sr !== 'tool_use' ? 'finished' : 'unfinished';
51
+ }
52
+ }
53
+ return 'missing';
54
+ }
55
+
56
+ /**
57
+ * @param {object} deps
58
+ * ledger {list,end,markRecovered,recoveredMap}, run(opts), holdOrphan(sid), releaseOrphan(sid),
59
+ * pidAlive(pid), identityOf(pid), sessionTurnState(entry) → 'finished'|'unfinished'|'missing',
60
+ * now(), pollMs, setTimer/clearTimer (tests)
61
+ * @returns {Promise<{ pending: Promise<void>, results: object[] }>} resolves after the first pass;
62
+ * `pending` settles once every orphan has exited and been handled.
63
+ */
64
+ async function recoverInflightTurns(deps) {
65
+ const {
66
+ ledger, run, holdOrphan = () => {}, releaseOrphan = () => {},
67
+ pidAlive = defaultPidAlive, identityOf = () => null,
68
+ sessionTurnState = async () => 'missing',
69
+ now = Date.now, pollMs = ORPHAN_POLL_MS,
70
+ setTimer = setTimeout,
71
+ } = deps;
72
+ const results = [];
73
+ const waits = [];
74
+ let entries = [];
75
+ try { entries = await ledger.list(); } catch { entries = []; }
76
+
77
+ async function settleDead(entry) {
78
+ const { sessionId, tabId, cwd } = entry;
79
+ let state = 'missing';
80
+ if (!entry.silent) {
81
+ try { state = await sessionTurnState(entry); } catch { state = 'missing'; }
82
+ }
83
+ if (entry.silent || state !== 'unfinished') {
84
+ await ledger.end(sessionId);
85
+ return { sessionId, outcome: 'finished' };
86
+ }
87
+ let recovered = {};
88
+ try { recovered = await ledger.recoveredMap(); } catch { recovered = {}; }
89
+ const prev = Number(recovered[sessionId]);
90
+ if (Number.isFinite(prev) && now() - prev < DAY_MS) {
91
+ await ledger.end(sessionId);
92
+ return { sessionId, outcome: 'guarded' };
93
+ }
94
+ await ledger.markRecovered(sessionId, now());
95
+ await ledger.end(sessionId);
96
+ run({
97
+ tabId, sessionId, cwd, prompt: CONTINUE_PROMPT, resume: true,
98
+ ...(entry.promptId ? { promptId: entry.promptId } : {}),
99
+ ...(entry.origin ? { origin: entry.origin } : {}),
100
+ ...(entry.worktreeDirHint ? { worktreeDirHint: entry.worktreeDirHint } : {}),
101
+ });
102
+ return { sessionId, outcome: 'rerun' };
103
+ }
104
+
105
+ function isOrphan(entry) {
106
+ if (!pidAlive(entry.pid)) return false;
107
+ try { return isChatProcessFor(identityOf(entry.pid), entry.sessionId); } catch { return false; }
108
+ }
109
+
110
+ for (const entry of entries) {
111
+ if (!entry || !entry.sessionId) continue;
112
+ if (isOrphan(entry)) {
113
+ holdOrphan(entry.sessionId);
114
+ waits.push(new Promise((resolve) => {
115
+ const tick = () => {
116
+ if (isOrphan(entry)) {
117
+ const t = setTimer(tick, pollMs);
118
+ if (t && typeof t.unref === 'function') t.unref();
119
+ return;
120
+ }
121
+ settleDead(entry)
122
+ .catch(() => ({ sessionId: entry.sessionId, outcome: 'error' }))
123
+ .then((r) => { results.push(r); releaseOrphan(entry.sessionId); resolve(); });
124
+ };
125
+ const t = setTimer(tick, pollMs);
126
+ if (t && typeof t.unref === 'function') t.unref();
127
+ }));
128
+ results.push({ sessionId: entry.sessionId, outcome: 'orphan' });
129
+ continue;
130
+ }
131
+ try { results.push(await settleDead(entry)); } catch { results.push({ sessionId: entry.sessionId, outcome: 'error' }); }
132
+ }
133
+ return { results, pending: Promise.all(waits).then(() => undefined) };
134
+ }
135
+
136
+ module.exports = { recoverInflightTurns, classifyTurnTail, CONTINUE_PROMPT, DAY_MS };