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.
- package/bin/cli.cjs +71 -9
- package/bin/supervise.cjs +84 -0
- package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-DKQznr7o.js} +1 -1
- package/dist/assets/{Button-8dWfDDuQ.js → Button-CZXqmIiM.js} +1 -1
- package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-piyV33To.js} +1 -1
- package/dist/assets/{History-hsztE6yh.js → History-BxwtrKF2.js} +1 -1
- package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-DogeSPII.js} +1 -1
- package/dist/assets/{Library-Czt3Bojd.js → Library-BDt6EeQQ.js} +1 -1
- package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-CwS-LKar.js} +1 -1
- package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-D2HVljgS.js} +1 -1
- package/dist/assets/{Memory-caujO8O3.js → Memory-hNzuOGn8.js} +1 -1
- package/dist/assets/{Panel-D64i9tGz.js → Panel-BLDrsUeq.js} +1 -1
- package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-DzZ5vaJW.js} +1 -1
- package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-Cz9yaxzG.js} +2 -2
- package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
- package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-Shmn699J.js} +1 -1
- package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-Bqr0WHNd.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
- package/dist/assets/{Settings-Bcf65bpL.js → Settings-Ci8in-yF.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-BWwljba8.js} +1 -1
- package/dist/assets/{Skills-DwnQKJVc.js → Skills-BON6o-c4.js} +1 -1
- package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-D5epIYYs.js} +1 -1
- package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-C2qDZROJ.js} +1 -1
- package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-SZhI3-bW.js} +1 -1
- package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C_qFDG0g.js} +1 -1
- package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-C9q5WCEd.js} +1 -1
- package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-BCl7IOhY.js} +1 -1
- package/dist/assets/{index-DgPUERhe.js → index-CMIYLbPb.js} +73 -73
- package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-BBrRBrBr.js} +1 -1
- package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-B01qJk6N.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-web/app.js +307 -307
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
- package/scripts/scheduler-mcp-server.cjs +39 -1
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +37 -4
- package/src/main/crashDiagnostics.cjs +83 -8
- package/src/main/health.cjs +16 -5
- package/src/main/index.cjs +32 -0
- package/src/main/lib/chatBootRecovery.cjs +136 -0
- package/src/main/lib/chatInflight.cjs +88 -0
- package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
- package/src/main/lib/epic/epicValidationHook.cjs +14 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
- package/src/main/lib/mcpToolCatalog.cjs +22 -3
- package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
- package/src/main/lib/persona-macro/macroLibrary.cjs +57 -3
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/prdCreate.cjs +5 -1
- package/src/main/lib/process/childWithLog.cjs +38 -95
- package/src/main/lib/process/memoryScope.cjs +140 -0
- package/src/main/lib/process/ozonePlatform.cjs +15 -0
- package/src/main/lib/process/procIdentity.cjs +10 -3
- package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
- package/src/main/lib/scheduler/cpuSample.cjs +147 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
- package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
- package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
- package/src/main/lib/scheduler/loadGate.cjs +116 -45
- package/src/main/lib/scheduler/queueStore.cjs +5 -2
- package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
- package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
- package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
- package/src/main/scheduler/budget.cjs +31 -0
- package/src/main/scheduler/prdPaths.cjs +54 -0
- package/src/main/scheduler/reviewLadder.cjs +17 -0
- package/src/main/scheduler/starvation.cjs +22 -0
- package/src/main/scheduler.cjs +522 -68
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/usage.cjs +4 -2
- package/src/preload/api.d.ts +12 -2
- package/src/seed/agents/demo-video-builder.md +62 -14
|
@@ -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
|
-
*
|
|
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
|
|
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
|
-
//
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
|
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
|
|
152
|
+
if (process.platform === 'win32') return;
|
|
190
153
|
|
|
191
154
|
const pid = child.pid;
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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
|
|
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.
|
|
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 };
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* cpuSample.cjs — measured machine-wide CPU use over a real window.
|
|
5
|
+
*
|
|
6
|
+
* The 1-minute load average counts parked D-state tasks and short bursts, so
|
|
7
|
+
* it can read high on a mostly idle machine (2026-11-01, 14 CPUs: 25 D-state
|
|
8
|
+
* tasks gave loadavg1 22.39 while the CPU was only 24% busy over 75 s). This
|
|
9
|
+
* helper derives busy/total from cumulative counters over a window of about a
|
|
10
|
+
* minute instead. Pure and injectable (`read`, `now`).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const fs = require('node:fs');
|
|
14
|
+
const os = require('node:os');
|
|
15
|
+
|
|
16
|
+
// Matches the 1-minute load average's horizon.
|
|
17
|
+
const DEFAULT_WINDOW_MS = 60_000;
|
|
18
|
+
// Anything shorter is a snapshot, not a sample: the two readings that started
|
|
19
|
+
// this work were 8 s long and fell in quiet gaps.
|
|
20
|
+
const MIN_WINDOW_MS = 20_000;
|
|
21
|
+
const MAX_WINDOW_MS = 180_000;
|
|
22
|
+
const MIN_SPACING_MS = 5_000;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Parse the aggregate `cpu ` line of /proc/stat into { busy, iowait, total }.
|
|
26
|
+
* Columns: user nice system idle iowait irq softirq steal guest guest_nice.
|
|
27
|
+
* Only the first 8 count (guest time is already inside user).
|
|
28
|
+
* - iowait is not busy: the CPU is idle during it and the load gate judges CPU
|
|
29
|
+
* only. Swap-in waits land there on this host, and the memory gate and swap
|
|
30
|
+
* clamp run before the load gate. It is carried as its own figure. os.cpus()
|
|
31
|
+
* has no such column, so macOS matches.
|
|
32
|
+
* - nice counts as busy: every Session Manager process here runs at nice 12,
|
|
33
|
+
* so nice is the largest column on this box.
|
|
34
|
+
* @param {string} text
|
|
35
|
+
* @returns {{ busy: number, iowait: number, total: number } | null}
|
|
36
|
+
*/
|
|
37
|
+
function parseProcStat(text) {
|
|
38
|
+
if (typeof text !== 'string' || !text) return null;
|
|
39
|
+
const line = text.split('\n').find((l) => l.startsWith('cpu '));
|
|
40
|
+
if (!line) return null;
|
|
41
|
+
const parts = line.trim().split(/\s+/).slice(1, 9);
|
|
42
|
+
if (parts.length < 4) return null;
|
|
43
|
+
const nums = [];
|
|
44
|
+
for (const p of parts) {
|
|
45
|
+
const n = Number(p);
|
|
46
|
+
if (!Number.isFinite(n)) return null;
|
|
47
|
+
nums.push(n);
|
|
48
|
+
}
|
|
49
|
+
while (nums.length < 8) nums.push(0);
|
|
50
|
+
const total = nums.reduce((a, b) => a + b, 0);
|
|
51
|
+
const idle = nums[3];
|
|
52
|
+
const iowait = nums[4];
|
|
53
|
+
return { busy: total - idle - iowait, iowait, total };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {{ platform?: string, readFile?: (p: string) => string, cpus?: () => import('node:os').CpuInfo[] }} [deps]
|
|
58
|
+
* @returns {{ busy: number, iowait: number, total: number } | null}
|
|
59
|
+
*/
|
|
60
|
+
function readCpuTimes({
|
|
61
|
+
platform = process.platform,
|
|
62
|
+
readFile = (p) => fs.readFileSync(p, 'utf8'),
|
|
63
|
+
cpus = () => os.cpus(),
|
|
64
|
+
} = {}) {
|
|
65
|
+
try {
|
|
66
|
+
if (platform === 'linux') return parseProcStat(readFile('/proc/stat'));
|
|
67
|
+
const list = cpus();
|
|
68
|
+
if (!Array.isArray(list) || list.length === 0) return null;
|
|
69
|
+
let busy = 0;
|
|
70
|
+
let idle = 0;
|
|
71
|
+
for (const c of list) {
|
|
72
|
+
const t = c.times;
|
|
73
|
+
busy += t.user + t.nice + t.sys + t.irq;
|
|
74
|
+
idle += t.idle;
|
|
75
|
+
}
|
|
76
|
+
if (![busy, idle].every(Number.isFinite)) return null;
|
|
77
|
+
return { busy, iowait: 0, total: busy + idle };
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {{ read?: () => ({busy:number,iowait?:number,total:number}|null), now?: () => number,
|
|
85
|
+
* windowMs?: number, minWindowMs?: number, maxWindowMs?: number, minSpacingMs?: number }} [opts]
|
|
86
|
+
*/
|
|
87
|
+
function createCpuSampler({
|
|
88
|
+
read = readCpuTimes,
|
|
89
|
+
now = () => Date.now(),
|
|
90
|
+
windowMs = DEFAULT_WINDOW_MS,
|
|
91
|
+
minWindowMs = MIN_WINDOW_MS,
|
|
92
|
+
maxWindowMs = MAX_WINDOW_MS,
|
|
93
|
+
minSpacingMs = MIN_SPACING_MS,
|
|
94
|
+
} = {}) {
|
|
95
|
+
/** @type {{ at: number, busy: number, iowait: number, total: number }[]} */
|
|
96
|
+
let entries = [];
|
|
97
|
+
|
|
98
|
+
function observe() {
|
|
99
|
+
const t = now();
|
|
100
|
+
const r = read();
|
|
101
|
+
if (!r) return;
|
|
102
|
+
const newest = entries[entries.length - 1];
|
|
103
|
+
if (newest && t - newest.at < minSpacingMs) return;
|
|
104
|
+
entries.push({ at: t, busy: r.busy, iowait: r.iowait ?? 0, total: r.total });
|
|
105
|
+
entries = entries.filter((e) => t - e.at <= maxWindowMs);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function sample() {
|
|
109
|
+
const t = now();
|
|
110
|
+
const r = read();
|
|
111
|
+
if (!r) return null;
|
|
112
|
+
let best = null;
|
|
113
|
+
let bestDiff = Infinity;
|
|
114
|
+
for (const e of entries) {
|
|
115
|
+
const age = t - e.at;
|
|
116
|
+
if (age < minWindowMs || age > maxWindowMs) continue;
|
|
117
|
+
const diff = Math.abs(age - windowMs);
|
|
118
|
+
if (diff < bestDiff) {
|
|
119
|
+
best = e;
|
|
120
|
+
bestDiff = diff;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!best) return null;
|
|
124
|
+
const dBusy = r.busy - best.busy;
|
|
125
|
+
const dTotal = r.total - best.total;
|
|
126
|
+
const dIowait = (r.iowait ?? 0) - best.iowait;
|
|
127
|
+
// Per-CPU idle and iowait counters can step backwards.
|
|
128
|
+
if (dTotal <= 0 || dBusy < 0) return null;
|
|
129
|
+
return {
|
|
130
|
+
busyFraction: Math.min(1, dBusy / dTotal),
|
|
131
|
+
iowaitFraction: Math.min(1, Math.max(0, dIowait / dTotal)),
|
|
132
|
+
windowMs: t - best.at,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { observe, sample };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = {
|
|
140
|
+
parseProcStat,
|
|
141
|
+
readCpuTimes,
|
|
142
|
+
createCpuSampler,
|
|
143
|
+
DEFAULT_WINDOW_MS,
|
|
144
|
+
MIN_WINDOW_MS,
|
|
145
|
+
MAX_WINDOW_MS,
|
|
146
|
+
MIN_SPACING_MS,
|
|
147
|
+
};
|
|
@@ -389,6 +389,45 @@ function resolveGate(prdText) {
|
|
|
389
389
|
return { source: 'absent', sequence: [] };
|
|
390
390
|
}
|
|
391
391
|
|
|
392
|
+
const TIMEOUT_UNIT_MS = { '': 1000, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
393
|
+
|
|
394
|
+
/** Time one `&&` step may take: every `timeout N` outside quotes, else the default. */
|
|
395
|
+
function stepTimeoutMs(step) {
|
|
396
|
+
const bare = step.replace(/'[^']*'|"[^"]*"/g, ' ');
|
|
397
|
+
let sum = 0;
|
|
398
|
+
for (const m of bare.matchAll(/(?:^|\s)timeout\s+(\d+)([smhd]?)(?=\s|$)/g)) {
|
|
399
|
+
sum += parseInt(m[1], 10) * TIMEOUT_UNIT_MS[m[2]];
|
|
400
|
+
}
|
|
401
|
+
return sum || DEFAULT_GATE_TIMEOUT_MS;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* The most one full pass over a PRD's gate can take: the sum of every step's
|
|
406
|
+
* `timeout`. Not built on resolveGate because that returns an empty sequence
|
|
407
|
+
* for a gate the no-shell parser refuses (Bilko-Game-Academy 872-fix-e2e-no-gpu-suite
|
|
408
|
+
* read as 0 minutes though it is 47.5), yet a validator runs gates through
|
|
409
|
+
* Bash, so that time is real. Returns 0 for a none gate, a PRD with no gate,
|
|
410
|
+
* or non-string/empty input.
|
|
411
|
+
*
|
|
412
|
+
* @param {unknown} prdText
|
|
413
|
+
* @returns {number} milliseconds
|
|
414
|
+
*/
|
|
415
|
+
function gateTimeoutMs(prdText) {
|
|
416
|
+
if (!prdText || typeof prdText !== 'string') return 0;
|
|
417
|
+
const explicit = readExplicitGate(prdText);
|
|
418
|
+
if (explicit) {
|
|
419
|
+
if (explicit.kind === 'none') return 0;
|
|
420
|
+
let total = 0;
|
|
421
|
+
for (const chain of explicit.chains) {
|
|
422
|
+
for (const seg of splitOnAndAnd(chain)) {
|
|
423
|
+
if (seg.trim()) total += stepTimeoutMs(seg.trim());
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return total;
|
|
427
|
+
}
|
|
428
|
+
return resolveGate(prdText).sequence.reduce((sum, step) => sum + step.timeoutMs, 0);
|
|
429
|
+
}
|
|
430
|
+
|
|
392
431
|
/**
|
|
393
432
|
* The gate as an ordered list of no-shell commands: [{argv, timeoutMs}, …].
|
|
394
433
|
* Empty when there is no parseable gate or the PRD opted out with `gate: none`
|
|
@@ -918,6 +957,7 @@ module.exports = {
|
|
|
918
957
|
explainChain,
|
|
919
958
|
isNoneGate,
|
|
920
959
|
resolveGate,
|
|
960
|
+
gateTimeoutMs,
|
|
921
961
|
runGateSequence,
|
|
922
962
|
runIsolatedSequence,
|
|
923
963
|
extractSection,
|