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
@@ -0,0 +1,204 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * jobLeftovers.cjs — read-only detection of processes that outlived their
5
+ * scheduler job.
6
+ *
7
+ * Why it exists: the post-exit group sweep only reaches the job's own process
8
+ * group. A child that called setsid (pnpm dev trees: concurrently, tsx watch,
9
+ * vite; Playwright web servers) escapes that group, so run metas report
10
+ * leakedDescendants [] while the tree runs for days.
11
+ *
12
+ * Identity is the SM_SCHEDULER_JOB_SLUG environment marker every job process
13
+ * inherits — never cwd or command line (the scheduler's own git/gate commands
14
+ * run in retained worktrees without the marker). Linux /proc only; no signal
15
+ * is sent here.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const { isClaudeArgv } = require('./reaperHelpers.cjs');
21
+ const procIdentity = require('../process/procIdentity.cjs');
22
+
23
+ const LEFTOVER_GRACE_MS = 120000;
24
+ const MARKER = 'SM_SCHEDULER_JOB_SLUG=';
25
+ const LIVE_STATUSES = new Set(['running', 'investigating', 'pending']);
26
+
27
+ function parseStat(raw) {
28
+ const open = raw.indexOf('(');
29
+ const close = raw.lastIndexOf(')');
30
+ if (open === -1 || close === -1 || close < open) return null;
31
+ const f = raw.slice(close + 1).trim().split(/\s+/);
32
+ const ppid = Number(f[1]);
33
+ if (f.length < 20 || !Number.isFinite(ppid)) return null;
34
+ return {
35
+ comm: raw.slice(open + 1, close),
36
+ state: f[0],
37
+ ppid,
38
+ tty: Number(f[4]) || 0,
39
+ utime: Number(f[11]) || 0,
40
+ stime: Number(f[12]) || 0,
41
+ startTicks: Number(f[19]) || 0,
42
+ };
43
+ }
44
+
45
+ function scanJobProcesses({ fsImpl = fs, procRoot = process.env.SM_PROC_ROOT || '/proc', platform = process.platform } = {}) {
46
+ const empty = () => ({ procs: [], parentOf: new Map() });
47
+ if (platform !== 'linux') return empty();
48
+ let names;
49
+ try {
50
+ names = fsImpl.readdirSync(procRoot);
51
+ } catch {
52
+ return empty();
53
+ }
54
+ let uptime = 0;
55
+ try {
56
+ uptime = Number(String(fsImpl.readFileSync(path.join(procRoot, 'uptime'), 'utf8')).split(/\s+/)[0]) || 0;
57
+ } catch { /* leave 0 */ }
58
+
59
+ const procs = [];
60
+ const parentOf = new Map();
61
+ for (const name of names) {
62
+ if (!/^\d+$/.test(name)) continue;
63
+ const pid = Number(name);
64
+ const dir = path.join(procRoot, name);
65
+ try {
66
+ const st = parseStat(String(fsImpl.readFileSync(path.join(dir, 'stat'), 'utf8')));
67
+ if (!st) continue;
68
+ parentOf.set(pid, st.ppid);
69
+ let env;
70
+ try {
71
+ env = String(fsImpl.readFileSync(path.join(dir, 'environ'), 'utf8')).split('\0');
72
+ } catch { continue; }
73
+ const entry = env.find((e) => e.startsWith(MARKER));
74
+ if (!entry || st.state === 'Z') continue;
75
+ const slug = entry.slice(MARKER.length);
76
+ let argv = [];
77
+ try {
78
+ argv = String(fsImpl.readFileSync(path.join(dir, 'cmdline'), 'utf8')).split('\0');
79
+ if (argv.length && argv[argv.length - 1] === '') argv.pop();
80
+ } catch { /* empty argv */ }
81
+ let cwd = null;
82
+ try {
83
+ cwd = String(fsImpl.readlinkSync(path.join(dir, 'cwd'))).replace(/ \(deleted\)$/, '');
84
+ } catch { /* null */ }
85
+ const etimes = Math.max(0, uptime - st.startTicks / 100);
86
+ const pcpu = etimes > 0 ? (((st.utime + st.stime) / 100) / etimes) * 100 : 0;
87
+ procs.push({ pid, ppid: st.ppid, tty: st.tty, slug, argv, cwd, comm: st.comm, startTicks: st.startTicks, etimes, pcpu });
88
+ } catch { /* pid vanished or denied mid-scan */ }
89
+ }
90
+ return { procs, parentOf };
91
+ }
92
+
93
+ function rowEndedMs(row) {
94
+ if (row && row.finishedAt) {
95
+ const t = Date.parse(row.finishedAt);
96
+ if (Number.isFinite(t)) return t;
97
+ }
98
+ const h = row && Array.isArray(row.statusHistory) ? row.statusHistory : [];
99
+ if (h.length) {
100
+ const t = Date.parse(h[h.length - 1] && h[h.length - 1].at);
101
+ if (Number.isFinite(t)) return t;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ function selectLeftovers({ scan, rows, runningSlugs, now, selfPid } = {}) {
107
+ const procs = (scan && scan.procs) || [];
108
+ const parentOf = (scan && scan.parentOf) || new Map();
109
+ const allRows = Array.isArray(rows) ? rows : [];
110
+ const running = runningSlugs instanceof Set ? runningSlugs : new Set(runningSlugs || []);
111
+
112
+ const bySlug = new Map();
113
+ for (const p of procs) {
114
+ if (!bySlug.has(p.slug)) bySlug.set(p.slug, []);
115
+ bySlug.get(p.slug).push(p);
116
+ }
117
+
118
+ const ancestors = new Set();
119
+ let cur = selfPid;
120
+ for (let i = 0; i < 64 && cur != null && parentOf.has(cur); i++) {
121
+ cur = parentOf.get(cur);
122
+ if (!cur || ancestors.has(cur)) break;
123
+ ancestors.add(cur);
124
+ }
125
+ const isDescendant = (pid) => {
126
+ let c = pid;
127
+ for (let i = 0; i < 64 && parentOf.has(c); i++) {
128
+ c = parentOf.get(c);
129
+ if (c === selfPid) return true;
130
+ if (!c) return false;
131
+ }
132
+ return false;
133
+ };
134
+
135
+ const out = [];
136
+ for (const [slug, list] of bySlug) {
137
+ if (running.has(slug)) continue;
138
+ if (list.some((p) => isClaudeArgv(p.argv))) continue;
139
+ const slugRows = allRows.filter((r) => r && r.slug === slug);
140
+ if (slugRows.some((r) => LIVE_STATUSES.has(r.status))) continue;
141
+ let ended = true;
142
+ for (const r of slugRows) {
143
+ const t = rowEndedMs(r);
144
+ if (t == null || now - t < LEFTOVER_GRACE_MS) { ended = false; break; }
145
+ }
146
+ if (!ended) continue;
147
+ const keep = list.filter((p) => !(p.tty !== 0 || p.pid === selfPid || ancestors.has(p.pid) || isDescendant(p.pid)));
148
+ if (keep.length) out.push({ slug, procs: keep });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * stopLeftovers(procs, deps) — SIGTERM each pid, then after graceMs SIGKILL only
155
+ * pids whose live identity is complete and not a different process from the one
156
+ * recorded before SIGTERM (a recycled pid is never killed). Never throws.
157
+ * Returns the pids that were signalled.
158
+ */
159
+ function stopLeftovers(procs, {
160
+ kill = process.kill.bind(process),
161
+ identityOf = procIdentity.identity,
162
+ isDifferentProcess = procIdentity.isDifferentProcess,
163
+ setTimer = setTimeout,
164
+ graceMs = 5000,
165
+ } = {}) {
166
+ const recorded = new Map();
167
+ const signalled = [];
168
+ for (const p of Array.isArray(procs) ? procs : []) {
169
+ const pid = p && p.pid;
170
+ if (!Number.isInteger(pid) || pid <= 1) continue;
171
+ try { recorded.set(pid, identityOf(pid)); } catch { recorded.set(pid, null); }
172
+ try {
173
+ kill(pid, 'SIGTERM');
174
+ signalled.push(pid);
175
+ } catch { /* already gone */ }
176
+ }
177
+ if (signalled.length === 0) return signalled;
178
+ const timer = setTimer(() => {
179
+ for (const pid of signalled) {
180
+ try {
181
+ const live = identityOf(pid);
182
+ if (!live || live.complete !== true) continue;
183
+ if (isDifferentProcess(recorded.get(pid), live)) continue;
184
+ kill(pid, 'SIGKILL');
185
+ } catch { /* gone */ }
186
+ }
187
+ }, graceMs);
188
+ if (timer && typeof timer.unref === 'function') timer.unref();
189
+ return signalled;
190
+ }
191
+
192
+ /**
193
+ * listJobSurvivors(slug, pid, opts) — every scanned process carrying the job's
194
+ * SM_SCHEDULER_JOB_SLUG marker except `pid` itself, whatever its process group or
195
+ * session. opts is passed to scanJobProcesses (injectable fs/procRoot/platform).
196
+ */
197
+ function listJobSurvivors(slug, pid, opts) {
198
+ const { procs } = scanJobProcesses(opts);
199
+ return procs
200
+ .filter((p) => p.slug === slug && p.pid !== pid)
201
+ .map((p) => ({ pid: p.pid, pcpu: Math.round(p.pcpu * 10) / 10, etimes: Math.round(p.etimes), comm: p.comm }));
202
+ }
203
+
204
+ module.exports = { scanJobProcesses, listJobSurvivors, selectLeftovers, stopLeftovers, LEFTOVER_GRACE_MS };
@@ -40,7 +40,7 @@ function recordPath(runDir, slug) {
40
40
  */
41
41
  function writeSupervisorRecord({
42
42
  runDir, slug, cwd, runId, pid, pgid, identity, execCwd, worktreeDir, worktreeBranch,
43
- sessionId, startedAt, budgetMs, maxDurationMs, idleKillMs, schedulerPid, codeSha, kind,
43
+ sessionId, startedAt, budgetMs, maxDurationMs, idleKillMs, schedulerPid, codeSha, kind, scopeUnit,
44
44
  }) {
45
45
  if (!runDir || !slug) throw new Error('writeSupervisorRecord: runDir and slug are required');
46
46
  const record = {
@@ -51,6 +51,7 @@ function writeSupervisorRecord({
51
51
  sessionId: sessionId ?? null, startedAt: startedAt ?? null,
52
52
  budgetMs: budgetMs ?? null, maxDurationMs: maxDurationMs ?? null, idleKillMs: idleKillMs ?? null,
53
53
  schedulerPid: schedulerPid ?? null, codeSha: codeSha ?? null,
54
+ scopeUnit: scopeUnit ?? null,
54
55
  };
55
56
  writeJsonAtomicSync(recordPath(runDir, slug), record);
56
57
  return record;
@@ -26,20 +26,36 @@
26
26
  const os = require('node:os');
27
27
  const { execFileSync } = require('node:child_process');
28
28
  const { loadGateThreshold, JOB_OVERRUN_FLOOR_MS } = require('./schedulerConfig.cjs');
29
+ const { createCpuSampler } = require('./cpuSample.cjs');
30
+
31
+ // A high loadavg only keeps holding launches when the measured CPU is NOT mostly
32
+ // idle. loadavg counts D-state tasks and short bursts, so it can read high on an
33
+ // idle CPU. The bar is 0.5, not 0.85: on SMT and hybrid chips half the logical
34
+ // CPUs is already most of the real capacity, and the gate exists to stop test
35
+ // batteries stretching past their timeouts (2026-09-01: loadavg 12.95 on 14
36
+ // cores), so a machine at 70% busy is not spare capacity. No sample = no
37
+ // evidence, so loadavg decides (a broken reader must never disable the gate).
38
+ const MOSTLY_IDLE_BUSY = 0.5;
39
+
40
+ // Three bands by measured CPU busy fraction (with loadavg over threshold):
41
+ // < MOSTLY_IDLE_BUSY (0.5): the gate stands down at once.
42
+ // 0.5 .. SATURATED_BUSY (0.85): it holds, and at the yield limit lets ONE job
43
+ // through, because capacity remains.
44
+ // >= SATURATED_BUSY: it keeps holding past the limit and escalates to a human
45
+ // (once per yield window), because launching there is what the gate exists
46
+ // to prevent. A null sample cannot prove saturation, so it yields at the limit.
47
+ // Both bars use Math.min(threshold, bar) so a strict threshold stays strict.
48
+ const SATURATED_BUSY = 0.85;
29
49
 
30
50
  // One audit row per this interval while continuously gated — the poll loop
31
51
  // ticks every 60 s and a saturated box stays saturated for a while; auditing
32
52
  // every tick would bury the signal in its own noise.
33
53
  const AUDIT_INTERVAL_MS = 10 * 60_000;
34
54
 
35
- // Default hysteresis release window for the gated stretch (PRD: boundary-
36
- // hovering load). A box sitting right at the threshold oscillates above/below
37
- // it tick to tick; clearing `gatedSince` on the first sub-threshold sample
38
- // reset the stretch counter every time, so `escalate` (and the warn-log with
39
- // topCpuConsumers()) never fired even after 80+ minutes of effectively
40
- // continuous gating. The stretch now only clears once load has stayed below
41
- // threshold continuously for this long.
42
- const RELEASE_WINDOW_MS = 2 * 60_000;
55
+ // A gated tick credits at most this much held time. A longer gap between gated
56
+ // ticks means slots or memory were the limiter in between (evaluate() runs only
57
+ // once they admit a batch), and that time is not this gate's.
58
+ const HOLD_CREDIT_CAP_MS = 2 * 60_000;
43
59
 
44
60
  /**
45
61
  * isLoadGated(loadavg1, cores, threshold) → boolean
@@ -59,7 +75,7 @@ function isLoadGated(loadavg1, cores, threshold) {
59
75
 
60
76
  /**
61
77
  * Best-effort top-N CPU consumers, for the audit line the scheduler warn-logs
62
- * when the load gate has held jobs past its escalation window. Diagnostic only
78
+ * when the load gate yields a job or escalates a saturated hold at its limit. Diagnostic only
63
79
  * — nothing downstream branches on the result, so it fails to [] rather than
64
80
  * throwing. Supported on Linux AND macOS (the two platforms this app targets);
65
81
  * [] anywhere else or on any error.
@@ -93,16 +109,29 @@ function topCpuConsumers(n = 3, { execImpl = execFileSync, platform = process.pl
93
109
  }
94
110
 
95
111
  /**
96
- * createLoadGate(opts) → { evaluate, snapshot }
112
+ * createLoadGate(opts) → { evaluate, observe, snapshot, endHold }
113
+ *
114
+ * Decision: loadavg over threshold AND the CPU sample not mostly idle (busy
115
+ * fraction >= min(threshold, MOSTLY_IDLE_BUSY)) holds; over threshold with a
116
+ * mostly idle sample stands down (standDown:true); no sample keeps the loadavg
117
+ * verdict. observe() feeds the sampler and must run every tick.
97
118
  *
98
119
  * Holds the small amount of state the gate needs across ticks (when it was
99
- * last audited, when the current gated stretch began). `evaluate({ bypass })`
120
+ * last audited, the time this gate itself has held a batch). `evaluate({ bypass })`
100
121
  * returns the decision for THIS tick:
101
122
  * { gated, ratio, threshold, loadavg1, cores, bypassed,
102
- * shouldAudit, escalate, gatedSinceMs }
123
+ * shouldAudit, shouldAuditStandDown, heldMs, yielded, escalated }
103
124
  * - shouldAudit: true at most once per AUDIT_INTERVAL_MS while gated.
104
- * - escalate: true once the current gated stretch exceeds JOB_OVERRUN_FLOOR_MS
105
- * (45 min by default) — the caller warn-logs with topCpuConsumers().
125
+ * - heldMs: time this gate itself held a batch. Each gated tick adds
126
+ * max(0, min(gap since previous gated tick, holdCreditCapMs)); only
127
+ * endHold() resets it (evaluate() never does).
128
+ * - yielded: heldMs reached yieldAfterMs (JOB_OVERRUN_FLOOR_MS, 45 min by
129
+ * default) AND the CPU is not saturated (busy < min(threshold, SATURATED_BUSY),
130
+ * or no sample). gated is false, it stays true on later ticks until the caller
131
+ * calls endHold() after a real launch, and the caller launches one job.
132
+ * - saturated at the limit: gated stays true, yielded false, heldMs keeps
133
+ * growing, and `escalated` is true at most once per yieldAfterMs of wall clock
134
+ * (per-tick only, never in snapshot()). endHold() clears that clock.
106
135
  * - bypassed: `bypass` was set (an explicit human Run now) and the gate would
107
136
  * otherwise have held; the caller launches anyway and logs that it did.
108
137
  *
@@ -114,15 +143,24 @@ function createLoadGate({
114
143
  now = () => Date.now(),
115
144
  threshold = loadGateThreshold,
116
145
  auditIntervalMs = AUDIT_INTERVAL_MS,
117
- escalateAfterMs = JOB_OVERRUN_FLOOR_MS,
118
- releaseWindowMs = RELEASE_WINDOW_MS,
146
+ holdCreditCapMs = HOLD_CREDIT_CAP_MS,
147
+ yieldAfterMs = JOB_OVERRUN_FLOOR_MS,
119
148
  platform = process.platform,
149
+ cpu = createCpuSampler(),
120
150
  } = {}) {
121
151
  let lastAuditAt = null; // null = never audited; the first gated tick always audits
122
- let gatedSince = null;
123
- let belowSince = null; // start of the current continuous sub-threshold run, while a stretch is open
152
+ let heldMs = 0;
153
+ let lastHeldAt = null;
154
+ let lastStandDownAuditAt = null;
155
+ let lastEscalatedAt = null;
124
156
  let last = null;
125
157
 
158
+ function observe() {
159
+ if (platform !== 'win32') cpu.observe();
160
+ }
161
+
162
+ // Returns `last` plus per-tick shouldAudit, shouldAuditStandDown, escalated and
163
+ // `saturated` (CPU sample proves busy >= min(threshold, SATURATED_BUSY); never in snapshot()).
126
164
  function evaluate({ bypass = false } = {}) {
127
165
  const t = now();
128
166
  if (platform === 'win32') {
@@ -133,36 +171,42 @@ function createLoadGate({
133
171
  ratio: 0,
134
172
  threshold: typeof threshold === 'function' ? threshold() : threshold,
135
173
  loadavg1: null,
174
+ cpuBusy: null,
175
+ cpuIowait: null,
176
+ cpuWindowMs: null,
177
+ standDown: false,
136
178
  cores: cores(),
137
- gatedSinceMs: 0,
179
+ heldMs: 0,
180
+ yielded: false,
138
181
  reason: 'loadavg-unavailable-win32',
139
182
  at: new Date(t).toISOString(),
140
183
  };
141
- return { ...last, shouldAudit: false, escalate: false };
184
+ return { ...last, shouldAudit: false, shouldAuditStandDown: false, escalated: false, saturated: false };
142
185
  }
143
186
  const [l1] = loadavg();
144
187
  const c = cores();
145
188
  const th = typeof threshold === 'function' ? threshold() : threshold;
146
189
  const ratio = c > 0 && Number.isFinite(l1) ? l1 / c : 0;
147
- const wouldGate = isLoadGated(l1, c, th);
148
-
149
- // Hysteresis: the STRETCH (gatedSince) only clears after load has stayed
150
- // below threshold continuously for releaseWindowMs. This never affects
151
- // `gated` itself below — a sub-threshold tick still returns gated:false
152
- // immediately; only the bookkeeping/escalation lags behind.
153
- if (wouldGate) {
154
- if (gatedSince === null) gatedSince = t;
155
- belowSince = null;
156
- } else if (gatedSince !== null) {
157
- if (belowSince === null) belowSince = t;
158
- if (t - belowSince >= releaseWindowMs) {
159
- gatedSince = null;
160
- belowSince = null;
161
- }
162
- } else {
163
- belowSince = null;
190
+ const sample = cpu.sample();
191
+ const overLoad = isLoadGated(l1, c, th);
192
+ const standDown = overLoad && sample !== null && sample.busyFraction < Math.min(th, MOSTLY_IDLE_BUSY);
193
+ const wouldGate = overLoad && !standDown;
194
+
195
+ const holding = wouldGate && !bypass;
196
+ if (holding) {
197
+ if (lastHeldAt !== null) heldMs += Math.max(0, Math.min(t - lastHeldAt, holdCreditCapMs));
198
+ lastHeldAt = t;
199
+ }
200
+ // A yield stays armed until the caller proves a launch with endHold().
201
+ const saturated = sample !== null && sample.busyFraction >= Math.min(th, SATURATED_BUSY);
202
+ const atLimit = holding && heldMs >= yieldAfterMs;
203
+ const yielded = atLimit && !saturated;
204
+ const gated = holding && !yielded;
205
+ let escalated = false;
206
+ if (atLimit && saturated && (lastEscalatedAt === null || t - lastEscalatedAt >= yieldAfterMs)) {
207
+ escalated = true;
208
+ lastEscalatedAt = t;
164
209
  }
165
- const gated = wouldGate && !bypass;
166
210
  const bypassed = wouldGate && bypass;
167
211
 
168
212
  let shouldAudit = false;
@@ -170,27 +214,54 @@ function createLoadGate({
170
214
  shouldAudit = true;
171
215
  lastAuditAt = t;
172
216
  }
173
- const gatedSinceMs = gatedSince === null ? 0 : t - gatedSince;
174
- const escalate = gated && gatedSinceMs >= escalateAfterMs;
175
-
217
+ let shouldAuditStandDown = false;
218
+ if (standDown && (lastStandDownAuditAt === null || t - lastStandDownAuditAt >= auditIntervalMs)) {
219
+ shouldAuditStandDown = true;
220
+ lastStandDownAuditAt = t;
221
+ }
176
222
  last = {
177
223
  gated,
178
224
  bypassed,
179
225
  ratio: Number(ratio.toFixed(3)),
180
226
  threshold: th,
181
227
  loadavg1: Number.isFinite(l1) ? Number(l1.toFixed(2)) : null,
228
+ cpuBusy: sample ? Number(sample.busyFraction.toFixed(3)) : null,
229
+ cpuIowait: sample ? Number(sample.iowaitFraction.toFixed(3)) : null,
230
+ cpuWindowMs: sample ? sample.windowMs : null,
231
+ standDown,
182
232
  cores: c,
183
- gatedSinceMs,
233
+ heldMs: holding ? heldMs : 0,
234
+ yielded,
184
235
  at: new Date(t).toISOString(),
185
236
  };
186
- return { ...last, shouldAudit, escalate };
237
+ return { ...last, shouldAudit, shouldAuditStandDown, escalated, saturated };
238
+ }
239
+
240
+ // Only the caller knows a launch really happened (or that nothing is waiting
241
+ // on this gate), so only the caller ends a hold.
242
+ function endHold() {
243
+ heldMs = 0;
244
+ lastHeldAt = null;
245
+ lastEscalatedAt = null;
187
246
  }
188
247
 
189
248
  function snapshot() {
190
249
  return last;
191
250
  }
192
251
 
193
- return { evaluate, snapshot };
252
+ // Read-only, for automatic launch paths that never reach evaluate(): true only
253
+ // when the load gate would hold AND a CPU sample proves a saturated CPU. Touches
254
+ // no hold clock, audit state or `last`.
255
+ function isSaturated() {
256
+ if (platform === 'win32') return false;
257
+ const [l1] = loadavg();
258
+ const th = typeof threshold === 'function' ? threshold() : threshold;
259
+ if (!isLoadGated(l1, cores(), th)) return false;
260
+ const sample = cpu.sample();
261
+ return sample !== null && sample.busyFraction >= Math.min(th, SATURATED_BUSY);
262
+ }
263
+
264
+ return { evaluate, observe, snapshot, endHold, isSaturated };
194
265
  }
195
266
 
196
- module.exports = { isLoadGated, createLoadGate, topCpuConsumers, AUDIT_INTERVAL_MS };
267
+ module.exports = { isLoadGated, createLoadGate, topCpuConsumers, AUDIT_INTERVAL_MS, MOSTLY_IDLE_BUSY, SATURATED_BUSY };
@@ -237,6 +237,8 @@ function shapeMachine(data) {
237
237
  // the queue at all, whether or not that evaluation ends in a launch. See
238
238
  // classifyQueueStarvation's header for why the two must never merge.
239
239
  lastDispatchAttemptAt: data.lastDispatchAttemptAt ?? null,
240
+ // Last launch time per project cwd (finished rows leave queue.json; lastRunAt is machine-wide).
241
+ lastDispatchAtByCwd: data.lastDispatchAtByCwd && typeof data.lastDispatchAtByCwd === 'object' && !Array.isArray(data.lastDispatchAtByCwd) ? data.lastDispatchAtByCwd : {},
240
242
  paused: data.paused ?? null,
241
243
  // Upgrade-drain state (lib/scheduler/upgradeDrain.cjs): deliberately NOT part of
242
244
  // `paused`, so a rate-limit pause can neither overwrite it nor have the
@@ -462,7 +464,7 @@ function shapeJobs(raw, file) {
462
464
  * writeSplit can persist "this project now has zero jobs".
463
465
  */
464
466
  function readMergedSync(opts) {
465
- const out = { config: {}, jobs: [], lastRunAt: null, lastDispatchAttemptAt: null, paused: null, drain: null, launchBlocks: {}, launchMitigations: {}, invalidJobs: [], unreadableCwds: [] };
467
+ const out = { config: {}, jobs: [], lastRunAt: null, lastDispatchAttemptAt: null, lastDispatchAtByCwd: {}, paused: null, drain: null, launchBlocks: {}, launchMitigations: {}, invalidJobs: [], unreadableCwds: [] };
466
468
  const sourceCwds = [];
467
469
  const machine = loadMachineStateSync();
468
470
  if (machine.shaped) {
@@ -496,7 +498,7 @@ function readMergedSync(opts) {
496
498
 
497
499
  /** Async twin of readMergedSync for IPC hot paths. */
498
500
  async function readMerged(opts) {
499
- const out = { config: {}, jobs: [], lastRunAt: null, lastDispatchAttemptAt: null, paused: null, drain: null, launchBlocks: {}, launchMitigations: {}, invalidJobs: [], unreadableCwds: [] };
501
+ const out = { config: {}, jobs: [], lastRunAt: null, lastDispatchAttemptAt: null, lastDispatchAtByCwd: {}, paused: null, drain: null, launchBlocks: {}, launchMitigations: {}, invalidJobs: [], unreadableCwds: [] };
500
502
  const sourceCwds = [];
501
503
  const machine = await loadMachineState();
502
504
  if (machine.shaped) {
@@ -549,6 +551,7 @@ async function writeSplit(state, defaultCwd) {
549
551
  config: state.config,
550
552
  lastRunAt: state.lastRunAt ?? null,
551
553
  lastDispatchAttemptAt: state.lastDispatchAttemptAt ?? null,
554
+ lastDispatchAtByCwd: state.lastDispatchAtByCwd && typeof state.lastDispatchAtByCwd === 'object' && !Array.isArray(state.lastDispatchAtByCwd) ? state.lastDispatchAtByCwd : {},
552
555
  paused: state.paused ?? null,
553
556
  drain: state.drain ?? null,
554
557
  launchBlocks: state.launchBlocks ?? {},
@@ -672,7 +672,7 @@ function pickNextBatch(allJobs, running, freeSlots, quietOpts = {}) {
672
672
  }
673
673
 
674
674
  /**
675
- * findStarvedProjects(jobs, now, thresholdMs) → [{ cwd, pendingCount, oldestPendingSlug, ageMs }]
675
+ * findStarvedProjects(jobs, now, thresholdMs, lastDispatchAtByCwd = {}) → [{ cwd, pendingCount, oldestPendingSlug, ageMs }]
676
676
  *
677
677
  * PRD 1087 — the escalation counterpart to the fairness rule above. A project
678
678
  * is STARVED when it has pending work, nothing of its own running, its oldest
@@ -680,12 +680,17 @@ function pickNextBatch(allJobs, running, freeSlots, quietOpts = {}) {
680
680
  * project currently has a running job (so the machine is dispatching, just
681
681
  * not for this project — an idle or paused machine is not starvation).
682
682
  *
683
+ * ageMs is now minus the LATER of the oldest pending row's enqueue time and
684
+ * the project's last dispatch (lastDispatchAtByCwd[cwd], ISO stamp; missing or
685
+ * unparseable = no dispatch), so a project draining a long queue is not
686
+ * starved in the gap between two jobs.
687
+ *
683
688
  * Pure and escalation-only: never mutates, reorders or dispatches. A pending
684
689
  * row whose age cannot be proven (no enqueue timestamp — see
685
690
  * enqueueTimestamp) is warn-logged and NOT reported, the same posture as
686
691
  * findStrandedInvestigations.
687
692
  */
688
- function findStarvedProjects(jobs, now, thresholdMs) {
693
+ function findStarvedProjects(jobs, now, thresholdMs, lastDispatchAtByCwd = {}) {
689
694
  const byCwd = new Map();
690
695
  for (const j of jobs ?? []) {
691
696
  const key = j.cwd || DEFAULT_PROJECT_CWD;
@@ -713,7 +718,9 @@ function findStarvedProjects(jobs, now, thresholdMs) {
713
718
  console.warn(`[scheduler] findStarvedProjects: ${cwd} has ${pending.length} pending job(s) with no enqueue timestamp — cannot prove age, leaving alone`);
714
719
  continue;
715
720
  }
716
- const ageMs = now - oldestMs;
721
+ const stamp = lastDispatchAtByCwd && typeof lastDispatchAtByCwd === 'object' ? Date.parse(lastDispatchAtByCwd[cwd]) : NaN;
722
+ const sinceMs = Number.isNaN(stamp) ? oldestMs : Math.max(oldestMs, stamp);
723
+ const ageMs = now - sinceMs;
717
724
  if (ageMs < thresholdMs) continue;
718
725
  out.push({ cwd, pendingCount: pending.length, oldestPendingSlug: oldest.slug, ageMs, unprovable });
719
726
  }
@@ -155,8 +155,13 @@ module.exports = {
155
155
  // recorded finishedAt+exitCode.
156
156
  INVESTIGATION_MAX_MS: 60 * 60_000,
157
157
 
158
- // CPU-load launch gate (loadGate.cjs): no NEW executor is launched while
159
- // the 1-minute load average per core exceeds this. The dynamic complement
158
+ // CPU-load launch gate (loadGate.cjs): holds NEW executors while the
159
+ // 1-minute load average per core exceeds this. Bands by a ~1-minute CPU
160
+ // sample (nice counts as busy, iowait does not; it is logged as cpuIowait):
161
+ // under half busy stands down; 50-85% holds, then one job goes through at
162
+ // 45 minutes (load_gate_yielded); 85%+ holds and never launches, with a
163
+ // load_gate_escalated audit row and toast every 45 minutes. No sample
164
+ // yields at the limit (it cannot prove saturation). The dynamic complement
160
165
  // to DEFAULT_PROJECT_JOB_CAP above — that cap is static and project-local;
161
166
  // this sees the machine. Observed 2026-09-01: 4 Godot test batteries under
162
167
  // Xvfb, loadavg 12.95 / 14 cores = 0.93, every battery stretching past its
@@ -43,12 +43,16 @@ const MEMORY_PRESSURE_MB = 3000;
43
43
  const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
44
44
 
45
45
  /**
46
- * Turns the previous run's last sample into a likely cause. silentGapSec is
46
+ * Turns the previous run's evidence into a likely cause. Launcher evidence
47
+ * (stderr tail, exit record) outranks the sample-based rules. silentGapSec is
47
48
  * accepted for the caller's meta but does not change the verdict.
48
- * @param {{ lastLoopDelayMaxMs?: unknown, lastTotalMb?: unknown, silentGapSec?: unknown }} [sample]
49
- * @returns {'main-hang' | 'memory-pressure' | 'unknown'}
49
+ * @param {{ lastLoopDelayMaxMs?: unknown, lastTotalMb?: unknown, silentGapSec?: unknown, exitRecord?: { signal?: unknown } | null, stderrTail?: unknown }} [sample]
50
+ * @returns {string} 'compositor-disconnect' | `signal:<NAME>` | 'main-hang' | 'memory-pressure' | 'unknown'
50
51
  */
51
- function classifyUncleanShutdown({ lastLoopDelayMaxMs, lastTotalMb } = {}) {
52
+ function classifyUncleanShutdown({ lastLoopDelayMaxMs, lastTotalMb, exitRecord, stderrTail } = {}) {
53
+ if (typeof stderrTail === 'string' && stderrTail.includes('Fatal Wayland communication error')) return 'compositor-disconnect';
54
+ const sig = exitRecord && exitRecord.signal;
55
+ if (typeof sig === 'string' && /^[A-Z0-9]{2,16}$/.test(sig)) return `signal:${sig}`;
52
56
  if (isNum(lastLoopDelayMaxMs) && lastLoopDelayMaxMs >= HANG_LOOP_DELAY_MS) return 'main-hang';
53
57
  if (isNum(lastTotalMb) && lastTotalMb >= MEMORY_PRESSURE_MB) return 'memory-pressure';
54
58
  return 'unknown';
@@ -240,6 +240,16 @@ function shouldKillForBudget(elapsedMs, budgetMs) {
240
240
  return elapsedMs >= budgetMs;
241
241
  }
242
242
 
243
+ /**
244
+ * resolveBudgetEstimate({ estimateMinutes, validatorEstimate, personaEstimate }) → number | null
245
+ * An explicit estimate wins; otherwise the larger of the validator-derived and
246
+ * persona-default estimates (persona stays a lower bound); null if neither.
247
+ */
248
+ function resolveBudgetEstimate({ estimateMinutes, validatorEstimate, personaEstimate } = {}) {
249
+ if (estimateMinutes != null) return estimateMinutes;
250
+ return Math.max(validatorEstimate ?? 0, personaEstimate ?? 0) || null;
251
+ }
252
+
243
253
  /**
244
254
  * resolveBudgetKillOutcome({ killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes })
245
255
  * → { killedByWatchdog: 'budget'|null, budgetKillReason: string|null }
@@ -544,7 +554,27 @@ function selectLeftoverQuarantineTarget(job) {
544
554
  return { slug: job.slug, cwd: job.cwd, paths };
545
555
  }
546
556
 
557
+ /**
558
+ * Why a tick found zero free slots. Pure. A degraded usage-meter cap that
559
+ * binds while the pool still has room is its own reason; a truly full pool
560
+ * stays 'slots-exhausted' even when the meter is also degraded.
561
+ */
562
+ function describeSlotHold({ total, inUse, holders = [], degradedCap = null, running = 0, deferredCount = 0 } = {}) {
563
+ if (degradedCap != null && inUse < total) {
564
+ return {
565
+ reason: 'usage-meter-degraded',
566
+ detail: `usage meter down: running capped at ${degradedCap} (${running} running, ${inUse} of ${total} slots in use)`,
567
+ };
568
+ }
569
+ const owners = (holders || []).map((h) => h.owner).join(', ');
570
+ return {
571
+ reason: 'slots-exhausted',
572
+ detail: `${inUse} of ${total} session slots busy${owners ? ` (${owners})` : ''}`,
573
+ };
574
+ }
575
+
547
576
  module.exports = {
577
+ describeSlotHold,
548
578
  BACKOFF_MAX_MS,
549
579
  FAILURE_STREAK_WARN_THRESHOLD,
550
580
  FAILURE_STREAK_ESCALATION_MS,
@@ -571,6 +601,7 @@ module.exports = {
571
601
  isJobBudgetExempt,
572
602
  shouldKillForBudget,
573
603
  resolveBudgetKillOutcome,
604
+ resolveBudgetEstimate,
574
605
  findStrandedInvestigations,
575
606
  computeDepHistorySatisfaction,
576
607
  };