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
@@ -37,6 +37,7 @@ const { sizingWarnings } = require('./prdSizing.cjs');
37
37
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
38
38
  const { execGit } = require('../git/gitExec.cjs');
39
39
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
40
+ const { isSweepValidatorSlug } = require('../epic/epicSweepValidator.cjs');
40
41
  const { validateGate, validateFiles, renderFilesSection, renderGateSection } = require('./prdGateFiles.cjs');
41
42
  const { resolveGate, parseChain, isNoneGate } = require('../scheduler/definitionOfDone.cjs');
42
43
 
@@ -84,7 +85,7 @@ function buildPrdBody(input) {
84
85
  const {
85
86
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
86
87
  implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId,
87
- gate, files,
88
+ gate, files, budgetExempt,
88
89
  } = input;
89
90
 
90
91
  // No `parallelGroup` frontmatter key (PRD_AUTHORING.md §5) — the NN-
@@ -137,6 +138,9 @@ function buildPrdBody(input) {
137
138
  // sibling jobs would otherwise invalidate. Only emitted when true — see
138
139
  // prdFrontmatter.cjs's applyKey for the matching "only true opts in" parse.
139
140
  if (quietMachine === true) fmLines.push('quietMachine: true');
141
+ // Budget exemption is for a sweep validator that cannot be split further;
142
+ // every other caller's budgetExempt is ignored.
143
+ if (budgetExempt === true && agentType === 'validator' && isSweepValidatorSlug(input.slug)) fmLines.push('budgetExempt: true');
140
144
  fmLines.push('---', '');
141
145
 
142
146
  const acLines = acceptanceCriteria.map((line) => `- [ ] ${line}`).join('\n');
@@ -4,6 +4,9 @@
4
4
  * prdDeclaredPaths.cjs — derive the file paths a PRD declares it touches, for
5
5
  * the reverify self-heal pass's widened evidence window (PRD 1102).
6
6
  *
7
+ * The PRD's `# Files` list is the declared change set and wins when present;
8
+ * the backtick scan of notes/criteria is only for PRDs with no Files section.
9
+ *
7
10
  * Reuses definitionOfDone.cjs's existing `extractSection` (already the PRD
8
11
  * markdown section parser used by flagRiskySurfaces) rather than
9
12
  * re-implementing one — see standards.md's API-reuse rule.
@@ -12,6 +15,7 @@
12
15
  const fs = require('node:fs');
13
16
  const { splitFrontmatter } = require('./prdFrontmatter.cjs');
14
17
  const { extractSection } = require('../scheduler/definitionOfDone.cjs');
18
+ const { parseFilesSection } = require('./prdGateFiles.cjs');
15
19
 
16
20
  // Backtick-quoted, extension-bearing relative paths, e.g. `src/main/scheduler.cjs`
17
21
  // or `src/main/scheduler.cjs:490` (trailing :line dropped). Requires at least
@@ -20,7 +24,9 @@ const PATH_RE = /`([a-zA-Z0-9_][\w.-]*(?:\/[\w.-]+)+\.[a-zA-Z0-9]+)(?::\d+)?`/g;
20
24
 
21
25
  /**
22
26
  * Extract declared file paths from a PRD body (frontmatter already
23
- * stripped). Scans the `# Implementation notes` and `# Acceptance criteria`
27
+ * stripped). When a `# Files` section exists, returns its file entries
28
+ * (folder entries ending in `/` dropped; a folders-only section yields []).
29
+ * Otherwise (legacy PRDs) scans the `# Implementation notes` and `# Acceptance criteria`
24
30
  * sections only — the same sections flagRiskySurfaces and the PRD-authoring
25
31
  * convention already treat as where files-touched are named. Returns `[]`
26
32
  * (never fabricates a path) when neither section names one.
@@ -30,6 +36,9 @@ const PATH_RE = /`([a-zA-Z0-9_][\w.-]*(?:\/[\w.-]+)+\.[a-zA-Z0-9]+)(?::\d+)?`/g;
30
36
  */
31
37
  function extractDeclaredPaths(prdBody) {
32
38
  if (!prdBody || typeof prdBody !== 'string') return [];
39
+ if (/^#\s+Files\s*$/m.test(prdBody)) {
40
+ return parseFilesSection(prdBody).filter((f) => !f.endsWith('/'));
41
+ }
33
42
  const text = [
34
43
  extractSection(prdBody, 'Implementation notes'),
35
44
  extractSection(prdBody, 'Acceptance criteria'),
@@ -67,4 +76,22 @@ function declaredPathsForPrd(prdPath) {
67
76
  return extractDeclaredPaths(body);
68
77
  }
69
78
 
70
- module.exports = { extractDeclaredPaths, declaredPathsForPrd };
79
+ /**
80
+ * The PRD's frontmatter `issuedAt` string, or null. Never throws — a missing
81
+ * or unreadable PRD, or one without the field, resolves to null.
82
+ *
83
+ * @param {string|null} prdPath
84
+ * @returns {string|null}
85
+ */
86
+ function issuedAtForPrd(prdPath) {
87
+ if (!prdPath) return null;
88
+ try {
89
+ const { fm } = splitFrontmatter(fs.readFileSync(prdPath, 'utf8'));
90
+ const v = fm && fm.issuedAt;
91
+ return typeof v === 'string' && v ? v : (v instanceof Date && !Number.isNaN(v.getTime()) ? v.toISOString() : null);
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ module.exports = { extractDeclaredPaths, declaredPathsForPrd, issuedAtForPrd };
@@ -21,7 +21,7 @@
21
21
  * shouldFire(ctx) returns true, then calls action(ctx).
22
22
  * - action() may call ctx.addTimer(t) to register secondary timers
23
23
  * (e.g. SIGTERM → SIGKILL cascades) so they are also cleared on exit.
24
- * Calls onExit() inside the child 'exit'/'error' handler,
24
+ * Calls onExit() synchronously inside the child 'exit'/'error' handler,
25
25
  * before calling closeFd(). Caller may call ctx.safeLog() inside onExit.
26
26
  *
27
27
  * WatchdogContext:
@@ -40,10 +40,7 @@
40
40
  * killedByWatchdog — string | null
41
41
  * error — Error | undefined (child 'error' event or sync spawn throw)
42
42
  * spawnFailed — boolean, true when the error came from a synchronous spawn throw
43
- * leakedDescendants — { pid, pcpu, etimes, comm }[], the process-group survivors
44
- * sweepChildProcessGroup found still alive right before it
45
- * swept them. [] in the normal case (nothing leaked, or
46
- * non-Linux, or enumeration failed). See sweepChildProcessGroup.
43
+ * pid — number | null, the child pid (null when spawn threw)
47
44
  * safeLog — same safeLog (usable inside onExit for final log lines)
48
45
  *
49
46
  * Returns { child, cancel } where cancel() clears all timers + SIGKILLs.
@@ -51,13 +48,10 @@
51
48
  */
52
49
 
53
50
  const fs = require('node:fs');
54
- const { spawn, execFile } = require('node:child_process');
51
+ const { spawn } = require('node:child_process');
55
52
  const { killTree } = require('./killTree.cjs');
56
53
  const { feedChildStdin } = require('./childStdin.cjs');
57
54
 
58
- // Injectable for tests (enumeration-failure coverage).
59
- const deps = { execFile };
60
-
61
55
  // Grace period between the post-exit SIGTERM sweep and the follow-up SIGKILL
62
56
  // sweep of a detached child's process group. See sweepChildProcessGroup below.
63
57
  const POST_EXIT_GROUP_SWEEP_GRACE_MS = 5000;
@@ -145,65 +139,24 @@ function openLog(logPath) {
145
139
  // a job's descendants must not outlive the job. Killing the job's own process
146
140
  // group at the job's own exit is ownership-based and needs no /proc heuristics
147
141
  // to distinguish an abandoned descendant from a live one.
148
- // Enumerate the still-alive members of process group `pgid` (Linux only).
149
- // Read-only — never throws, never blocks the caller's exit path. Used to
150
- // report what sweepChildProcessGroup is about to kill, since the kill itself
151
- // is silent (ESRCH on the normal empty-group case).
152
- // Async: resolves to the survivors list, rejects on ps failure/timeout. O(P) in
153
- // the process table, off the main event loop.
154
- function enumerateProcessGroupSurvivors(pgid) {
155
- // ps -eo is Linux-only; on win32 (and macOS) report the empty/unknown result without spawning ps.
156
- if (process.platform !== 'linux') return Promise.resolve([]);
157
- if (!pgid || pgid <= 1) return Promise.resolve([]);
158
- return new Promise((resolve, reject) => {
159
- try {
160
- deps.execFile('ps', ['-eo', 'pid,pgrp,pcpu,etimes,comm'], { encoding: 'utf8', timeout: 2000 }, (err, out) => {
161
- if (err) { reject(err); return; }
162
- const survivors = [];
163
- for (const line of String(out).split('\n').slice(1)) {
164
- const m = line.trim().match(/^(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.+)$/);
165
- if (!m) continue;
166
- const [, pidStr, pgrpStr, pcpuStr, etimesStr, comm] = m;
167
- if (Number(pgrpStr) !== pgid) continue;
168
- survivors.push({ pid: Number(pidStr), pcpu: Number(pcpuStr), etimes: Number(etimesStr), comm });
169
- }
170
- resolve(survivors);
171
- });
172
- } catch (e) { reject(e); }
173
- });
174
- }
175
-
176
- // Returns null when there is nothing to enumerate/sweep (non-detached, missing or
177
- // invalid pid, our own group) so the caller can finish synchronously. Otherwise
178
- // returns a promise for the leaked descendants: enumeration runs FIRST so the
179
- // report reflects what the sweep is about to reap, and SIGTERM (+ the delayed
180
- // SIGKILL) is issued only once it has SETTLED — resolved or rejected. The 2 s ps
181
- // timeout bounds that wait. The promise never rejects: a failed enumeration
182
- // resolves [] after a safeLog line, and the group is still killed.
183
- function sweepChildProcessGroup(child, detached, safeLog) {
184
- if (!detached) return null;
185
- if (!child || !child.pid || child.pid <= 1) return null;
142
+ // Synchronous and fire-and-forget: SIGTERM now, SIGKILL after the grace period.
143
+ // What escaped the group is reported by the job-marker scan (jobLeftovers), not here.
144
+ // No-op when there is nothing to sweep (non-detached, missing or invalid pid, our
145
+ // own group, win32).
146
+ function sweepChildProcessGroup(child, detached) {
147
+ if (!detached) return;
148
+ if (!child || !child.pid || child.pid <= 1) return;
186
149
  // Defensive: never target the Session Manager process's own group.
187
- if (child.pid === process.pid) return null;
150
+ if (child.pid === process.pid) return;
188
151
  // win32 has no process groups; taskkill on an already-exited pid risks hitting a reused pid.
189
- if (process.platform === 'win32') return null;
152
+ if (process.platform === 'win32') return;
190
153
 
191
154
  const pid = child.pid;
192
- const kill = () => {
193
- killTree(pid, 'SIGTERM'); // ESRCH on an empty group is the normal case
194
- const t = setTimeout(() => {
195
- killTree(pid, 'SIGKILL');
196
- }, POST_EXIT_GROUP_SWEEP_GRACE_MS);
197
- if (t.unref) t.unref();
198
- };
199
-
200
- return enumerateProcessGroupSurvivors(pid)
201
- .then((all) => all.filter((p) => p.pid !== pid))
202
- .catch((e) => {
203
- safeLog(`[childWithLog] process-group enumeration failed; leak report omitted: ${e && e.message}\n`);
204
- return [];
205
- })
206
- .then((leaked) => { kill(); return leaked; });
155
+ killTree(pid, 'SIGTERM'); // ESRCH on an empty group is the normal case
156
+ const t = setTimeout(() => {
157
+ killTree(pid, 'SIGKILL');
158
+ }, POST_EXIT_GROUP_SWEEP_GRACE_MS);
159
+ if (t.unref) t.unref();
207
160
  }
208
161
 
209
162
  /**
@@ -272,37 +225,27 @@ function withChildAndLog({ fd, logPath, safeLog, closeFd, spawn: spawnSpec, watc
272
225
  // calls onExit (caller may still safeLog inside), then closes the fd.
273
226
  const handleDone = (exitCode, signal, error, spawnFailed) => {
274
227
  clearAllTimers();
275
- const finish = (leakedDescendants) => {
276
- try {
277
- if (onExit) {
278
- onExit({
279
- exitCode,
280
- signal: signal ?? null,
281
- killedByWatchdog: ctx.killedByWatchdog,
282
- error,
283
- spawnFailed: spawnFailed ?? false,
284
- leakedDescendants,
285
- safeLog,
286
- });
287
- }
288
- } catch (e) {
289
- // Log while the fd is still open (closeFd below makes safeLog a no-op),
290
- // then rethrow: sync callers see the throw as before PRD 1353; the
291
- // deferred path contains it below.
292
- const stack = e && e.stack ? String(e.stack).split('\n').slice(0, 3).join('\n') : '';
293
- safeLog(`[childWithLog] onExit threw: ${e && e.message}${stack ? `\n${stack}` : ''}\n`);
294
- throw e;
295
- } finally {
296
- closeFd();
228
+ sweepChildProcessGroup(ctx.child, !!spawnSpec.options?.detached);
229
+ try {
230
+ if (onExit) {
231
+ onExit({
232
+ exitCode,
233
+ signal: signal ?? null,
234
+ killedByWatchdog: ctx.killedByWatchdog,
235
+ error,
236
+ spawnFailed: spawnFailed ?? false,
237
+ pid: ctx.child && ctx.child.pid ? ctx.child.pid : null,
238
+ safeLog,
239
+ });
297
240
  }
298
- };
299
- const pending = sweepChildProcessGroup(ctx.child, !!spawnSpec.options?.detached, safeLog);
300
- // Nothing to enumerate: stay synchronous. Otherwise onExit + closeFd wait
301
- // (bounded by the 2 s ps timeout) for the leak report; a throwing onExit
302
- // must not become an unhandled rejection.
303
- if (!pending) { finish([]); return; }
304
- // finish() already logged the throw and closed the fd; just contain it.
305
- pending.then(finish).catch(() => {});
241
+ } catch (e) {
242
+ // Log while the fd is still open (closeFd below makes safeLog a no-op), then rethrow.
243
+ const stack = e && e.stack ? String(e.stack).split('\n').slice(0, 3).join('\n') : '';
244
+ safeLog(`[childWithLog] onExit threw: ${e && e.message}${stack ? `\n${stack}` : ''}\n`);
245
+ throw e;
246
+ } finally {
247
+ closeFd();
248
+ }
306
249
  };
307
250
 
308
251
  // Attempt synchronous spawn. On failure, call handleDone immediately so the
@@ -337,4 +280,4 @@ function withChildAndLog({ fd, logPath, safeLog, closeFd, spawn: spawnSpec, watc
337
280
  return { child, cancel };
338
281
  }
339
282
 
340
- module.exports = { openLog, withChildAndLog, POST_EXIT_GROUP_SWEEP_GRACE_MS, _deps: deps };
283
+ module.exports = { openLog, withChildAndLog, POST_EXIT_GROUP_SWEEP_GRACE_MS };
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * memoryScope.cjs — wrap a command in a transient systemd user scope with
5
+ * memory limits so a runaway process hits its own cgroup limit instead of the
6
+ * machine's global OOM. Degrades to a plain spawn wherever scopes are
7
+ * unavailable (callers use scopeSupported()).
8
+ *
9
+ * `systemd-run --scope` execs the command in place, so the spawned pid stays
10
+ * the job's own pid and detached process groups keep working.
11
+ */
12
+
13
+ const childProcess = require('node:child_process');
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+
17
+ const DEFAULT_MAX_CAP_MB = 10240;
18
+ const DEFAULT_MAX_FRACTION = 0.45;
19
+ const HIGH_FRACTION = 0.85;
20
+ const DEFAULT_SWAP_MAX_MB = 4096;
21
+
22
+ /**
23
+ * @param {{ totalRamMb?: number, env?: Record<string, string | undefined> }} [opts]
24
+ * @returns {{ memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number } | null} null = disabled
25
+ */
26
+ function memoryLimitsFor(opts = {}) {
27
+ const env = opts.env || process.env;
28
+ const raw = env.SM_JOB_MEMORY_MAX_MB;
29
+ let max;
30
+ if (raw !== undefined && raw !== '' && Number.isFinite(Number(raw)) && Number(raw) >= 0) {
31
+ max = Math.floor(Number(raw));
32
+ } else {
33
+ const total = Number(opts.totalRamMb);
34
+ if (!Number.isFinite(total) || total <= 0) return null;
35
+ max = Math.min(DEFAULT_MAX_CAP_MB, Math.floor(total * DEFAULT_MAX_FRACTION));
36
+ }
37
+ if (max <= 0) return null;
38
+ return {
39
+ memoryMaxMb: max,
40
+ memoryHighMb: Math.floor(HIGH_FRACTION * max),
41
+ swapMaxMb: DEFAULT_SWAP_MAX_MB,
42
+ };
43
+ }
44
+
45
+ /** @type {boolean | null} */
46
+ let cachedSupport = null;
47
+
48
+ /** Test hook: forget the cached probe result. */
49
+ function _resetScopeSupportCache() {
50
+ cachedSupport = null;
51
+ }
52
+
53
+ /**
54
+ * @param {{ platform?: string, spawnSync?: typeof childProcess.spawnSync, fs?: { existsSync: (p: string) => boolean }, env?: Record<string, string | undefined> }} [deps]
55
+ * @returns {boolean}
56
+ */
57
+ function scopeSupported(deps = {}) {
58
+ if (cachedSupport !== null) return cachedSupport;
59
+ const platform = deps.platform || process.platform;
60
+ const spawnSync = deps.spawnSync || childProcess.spawnSync;
61
+ const fsImpl = deps.fs || fs;
62
+ const env = deps.env || process.env;
63
+ let ok = false;
64
+ try {
65
+ if (platform === 'linux') {
66
+ const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
67
+ const found = dirs.some((d) => fsImpl.existsSync(path.join(d, 'systemd-run')));
68
+ if (found) {
69
+ const r = spawnSync('systemd-run', ['--user', '--scope', '--quiet', '--collect', 'true'], {
70
+ stdio: 'ignore',
71
+ timeout: 5000,
72
+ });
73
+ ok = !!r && !r.error && r.status === 0;
74
+ }
75
+ }
76
+ } catch {
77
+ ok = false;
78
+ }
79
+ cachedSupport = ok;
80
+ return ok;
81
+ }
82
+
83
+ /** @param {string} unit */
84
+ function sanitizeUnit(unit) {
85
+ const s = String(unit == null ? '' : unit).replace(/[^A-Za-z0-9:_.\\-]/g, '-').replace(/\.scope$/, '');
86
+ return s || 'sm-job';
87
+ }
88
+
89
+ /**
90
+ * @param {{ command: string, args?: string[], unit: string, limits: { memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number }, systemdRunPath?: string }} o
91
+ * @returns {{ command: string, args: string[] }}
92
+ */
93
+ function wrapInMemoryScope(o) {
94
+ const { command, args = [], unit, limits, systemdRunPath } = o;
95
+ return {
96
+ command: systemdRunPath || 'systemd-run',
97
+ args: [
98
+ '--user',
99
+ '--scope',
100
+ '--quiet',
101
+ '--collect',
102
+ `--unit=${sanitizeUnit(unit)}.scope`,
103
+ '-p', `MemoryHigh=${limits.memoryHighMb}M`,
104
+ '-p', `MemoryMax=${limits.memoryMaxMb}M`,
105
+ '-p', `MemorySwapMax=${limits.swapMaxMb}M`,
106
+ '-p', 'OOMPolicy=continue',
107
+ '--',
108
+ command,
109
+ ...args,
110
+ ],
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Stop a scope by unit name, fire-and-forget. `--no-block` returns at once so a
116
+ * SIGTERM-ignoring straggler cannot stall the main thread. Never throws.
117
+ * @param {string} unit
118
+ * @param {{ spawn?: typeof childProcess.spawn }} [deps]
119
+ * @returns {void}
120
+ */
121
+ function stopScope(unit, deps = {}) {
122
+ try {
123
+ const spawn = deps.spawn || childProcess.spawn;
124
+ const child = spawn('systemctl', ['--user', 'stop', '--no-block', `${sanitizeUnit(unit)}.scope`], {
125
+ stdio: 'ignore',
126
+ detached: true,
127
+ });
128
+ if (child && typeof child.on === 'function') child.on('error', () => { /* systemctl missing */ });
129
+ if (child && typeof child.unref === 'function') child.unref();
130
+ } catch { /* never throw */ }
131
+ }
132
+
133
+ module.exports = {
134
+ memoryLimitsFor,
135
+ scopeSupported,
136
+ wrapInMemoryScope,
137
+ stopScope,
138
+ sanitizeUnit,
139
+ _resetScopeSupportCache,
140
+ };
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+ // Pick Electron's --ozone-platform. A stalled Wayland client is dropped by the compositor
3
+ // ("Fatal Wayland communication error: Broken pipe", exit 0, no dump); X11/XWayland isn't.
4
+ // SM_OZONE_PLATFORM=x11|wayland wins; auto/unset -> x11 on a Wayland session with DISPLAY.
5
+ // null = leave Electron's default alone.
6
+ function chooseOzonePlatform(env = {}) {
7
+ const override = String(env.SM_OZONE_PLATFORM || '').trim().toLowerCase();
8
+ if (override === 'x11' || override === 'wayland') return override;
9
+ const session = String(env.XDG_SESSION_TYPE || '').trim().toLowerCase();
10
+ const display = String(env.DISPLAY || '').trim();
11
+ if (session === 'wayland' && display) return 'x11';
12
+ return null;
13
+ }
14
+
15
+ module.exports = { chooseOzonePlatform };
@@ -16,6 +16,13 @@
16
16
  * all all read as "not different" — i.e. today's pid-only behaviour, never a
17
17
  * false positive that could wrongly break a live lock or veto a real kill.
18
18
  *
19
+ * Identity is pid + startTicks ONLY; cmdline is recorded but never compared.
20
+ * Why: exec keeps both pid and start time while replacing the cmdline, and
21
+ * `systemd-run --scope` execs the job in place — the identity taken right
22
+ * after spawn holds systemd-run's cmdline, the live job later holds its own.
23
+ * Comparing cmdline read a LIVE job as a foreign pid after an app restart.
24
+ * A recycled pid cannot repeat the same start time within a boot.
25
+ *
19
26
  * SM_PROC_ROOT overrides the /proc root — tests only, so stat/cmdline
20
27
  * fixtures can be written under a temp dir instead of touching real /proc.
21
28
  */
@@ -146,7 +153,8 @@ function identity(pid, { platform = process.platform, execFile = execFileSync }
146
153
 
147
154
  /**
148
155
  * isDifferentProcess(recorded, live) — true ONLY when both sides are a
149
- * COMPLETE identity and differ. Every other case (missing side, incomplete
156
+ * COMPLETE identity and pid or startTicks differ. cmdline is NOT compared
157
+ * (see header: exec keeps pid + start time). Every other case (missing side, incomplete
150
158
  * side, a legacy record with no identity fields) is "not different", i.e.
151
159
  * today's pid-only behaviour — the fail-closed default.
152
160
  */
@@ -154,8 +162,7 @@ function isDifferentProcess(recorded, live) {
154
162
  if (!recorded || !live) return false;
155
163
  if (!recorded.complete || !live.complete) return false;
156
164
  return recorded.pid !== live.pid
157
- || recorded.startTicks !== live.startTicks
158
- || recorded.cmdline !== live.cmdline;
165
+ || recorded.startTicks !== live.startTicks;
159
166
  }
160
167
 
161
168
  module.exports = { identity, isDifferentProcess };
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * scopeOomPolicy.cjs — keep one child's OOM-kill from stopping the whole app.
5
+ *
6
+ * Electron runs in a transient systemd user scope
7
+ * (app-claude-code-session-manager-<pid>.scope) with the default OOMPolicy=stop,
8
+ * and every job, chat and pty lives inside it. When the kernel OOM-kills ANY
9
+ * child, systemd stops the entire scope (5 app deaths on 2026-10-31). A user
10
+ * drop-in on the scope-name prefix sets OOMPolicy=continue so a child's death
11
+ * stays that child's death. Written at boot; daemon-reload runs only when the
12
+ * file actually changed.
13
+ */
14
+
15
+ const nodeFs = require('node:fs');
16
+ const os = require('node:os');
17
+ const path = require('node:path');
18
+ const childProcess = require('node:child_process');
19
+ const atomicFs = require('../util/atomicFs.cjs');
20
+
21
+ const DROPIN_DIR = 'app-claude-code-session-manager-.scope.d';
22
+ const DROPIN_FILE = '10-oom-policy.conf';
23
+ const CONTENT = '[Scope]\nOOMPolicy=continue\n';
24
+
25
+ /**
26
+ * @param {object} [opts]
27
+ * @param {string} [opts.platform]
28
+ * @param {string} [opts.configHome]
29
+ * @param {any} [opts.fs] needs readFileSync
30
+ * @param {any} [opts.spawnSync]
31
+ * @param {(msg: string) => void} [opts.log]
32
+ * @param {(file: string, text: string) => void} [opts.writeText] defaults to atomicFs.writeTextAtomicSync
33
+ * @returns {{ applied: boolean, reason: string }}
34
+ */
35
+ function ensureScopeOomPolicy(opts = {}) {
36
+ const platform = opts.platform || process.platform;
37
+ const fs = opts.fs || nodeFs;
38
+ const spawnSync = opts.spawnSync || childProcess.spawnSync;
39
+ const log = opts.log || (() => {});
40
+ const writeText = opts.writeText || ((f, t) => atomicFs.writeTextAtomicSync(f, t));
41
+ try {
42
+ if (platform !== 'linux') return { applied: false, reason: 'not-linux' };
43
+ const configHome = opts.configHome
44
+ || process.env.XDG_CONFIG_HOME
45
+ || path.join(os.homedir(), '.config');
46
+
47
+ const probe = spawnSync('systemctl', ['--user', '--version'], { stdio: 'ignore', timeout: 5000 });
48
+ if (!probe || probe.error || probe.status !== 0) {
49
+ return { applied: false, reason: 'no-systemctl' };
50
+ }
51
+
52
+ const file = path.join(configHome, 'systemd', 'user', DROPIN_DIR, DROPIN_FILE);
53
+ let existing = null;
54
+ try { existing = fs.readFileSync(file, 'utf8'); } catch { existing = null; }
55
+ if (existing === CONTENT) return { applied: false, reason: 'already-current' };
56
+
57
+ writeText(file, CONTENT);
58
+ const reload = spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore', timeout: 15000 });
59
+ if (!reload || reload.error || reload.status !== 0) {
60
+ log(`scopeOomPolicy: daemon-reload failed (${reload?.error?.message || `status ${reload?.status}`})`);
61
+ return { applied: false, reason: 'daemon-reload-failed' };
62
+ }
63
+ return { applied: true, reason: existing === null ? 'written' : 'updated' };
64
+ } catch (e) {
65
+ return { applied: false, reason: `error: ${e?.message || e}` };
66
+ }
67
+ }
68
+
69
+ module.exports = { ensureScopeOomPolicy, DROPIN_DIR, DROPIN_FILE, CONTENT };
@@ -31,7 +31,7 @@ const LegacyAwareEpicTagSchema = z.preprocess(
31
31
  EpicTagSchema.optional(),
32
32
  );
33
33
 
34
- // Mirrors EpicSource (src/renderer/state/promptSessions.ts:22-27).
34
+ // Mirrors EpicSource (`export interface EpicSource` in src/renderer/state/promptSessions.ts).
35
35
  const EpicSourceSchema = z.object({
36
36
  producer: z.enum(['new-epic-ui', 'scheduler-dispatch', 'cross-project-feedback']),
37
37
  prdSlug: z.string().optional(),
@@ -43,6 +43,11 @@ const EpicSourceSchema = z.object({
43
43
  // there is no cross-project registry anywhere else.
44
44
  fromCwd: z.string().optional(),
45
45
  fromEpicId: z.string().optional(),
46
+ // The macro that launched this Epic (new-epic-ui Epics only).
47
+ macroId: z.string().optional(),
48
+ // Zod strips undeclared keys on the merge path; a stricter shape could make dropInvalidSessions (ipcSchemas.cjs) drop a whole row holding an older or malformed value.
49
+ proposal: z.unknown().optional(),
50
+ autoApprove: z.unknown().optional(),
46
51
  });
47
52
 
48
53
  // Mirrors EpicIntakeSection (src/renderer/lib/epicIntake.ts) — the labeled