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
@@ -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 ?? {},
@@ -50,6 +50,7 @@ const VERDICT_LABELS = {
50
50
  no_verdict_sentinel: 'no commit or verdict sentinel',
51
51
  abandoned_background_task: 'abandoned auto-backgrounded task',
52
52
  pass_no_commit: 'PASS sentinel but no commit landed',
53
+ run_commit_not_landed: 'run made a commit that never landed',
53
54
  sentinel_fail: 'executor reported SCHEDULER_VERDICT: FAIL',
54
55
  pass_no_commit_already_shipped: 'PASS with no commit — deliverables already shipped',
55
56
  pass_no_commit_prior_run_verified: 'PASS with no commit — prior run of this slug already landed the work',
@@ -201,6 +201,7 @@ const HUMAN_CAUSE = {
201
201
  uncommitted_changes: 'the run left changes in the working tree without committing them',
202
202
  reaped_without_integration: 'the run was stopped before its work was merged into the main checkout',
203
203
  budget_exceeded: 'the run used up its time or cost budget before finishing',
204
+ run_commit_not_landed: 'the run committed work that never reached the main branch; the commit is kept under a named ref',
204
205
  };
205
206
 
206
207
  function humanCauseFor(cause) {
@@ -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';
@@ -28,6 +28,8 @@
28
28
  * verify_unavailable → 'needs_review' (unreadable log / verifier threw)
29
29
  * no_verdict_sentinel → 'needs_review'
30
30
  * abandoned_background_task → 'needs_review'
31
+ * run_commit_not_landed → 'needs_review' (PASS but transcript SHA unreachable)
32
+ * pass_no_commit_already_shipped → historical rows only; no longer emitted
31
33
  *
32
34
  * Time complexity: O(N·L) where N = log line count, L = avg content line count.
33
35
  * The log is read once with readFileSync (700 KB typical; well within Node.js
@@ -129,8 +131,9 @@ function parseLog(logPath) {
129
131
  if (obj.type === 'system' && obj.subtype === 'vcs_state_changed' && obj.kind === 'commit') {
130
132
  transcriptCommitLanded = true;
131
133
  }
132
- if (obj.tool_use_result?.gitOperation?.commit?.kind === 'committed') {
133
- transcriptCommitLanded = true;
134
+ const gitOpKind = obj.tool_use_result?.gitOperation?.commit?.kind;
135
+ if (gitOpKind === 'committed' || gitOpKind === 'cherry-picked') {
136
+ if (gitOpKind === 'committed') transcriptCommitLanded = true;
134
137
  const sha = obj.tool_use_result.gitOperation.commit.sha;
135
138
  if (typeof sha === 'string' && sha) transcriptCommitShaSet.add(sha);
136
139
  }
@@ -478,18 +481,13 @@ function isAncestorCommit({ cwd, sha, timeoutMs = GH_CHECK_TIMEOUT_MS, execImpl
478
481
  }
479
482
  }
480
483
 
481
- /**
482
- * True when `cwd` is inside a git repository. Used to gate the transcript
483
- * commit-evidence fallback below: a job whose cwd is not a git repo can never
484
- * produce committedDuringRun=true (gitHead()/committedInWindow() fail closed
485
- * there), so the fallback must only apply in that narrow case — never when
486
- * git ancestry is actually observable.
487
- */
488
- function isGitRepo(cwd) {
489
- if (!cwd) return false;
484
+ /** True when this repo holds the commit object `sha` (bounded, never throws). */
485
+ function commitExistsInRepo({ cwd, sha, timeoutMs = GH_CHECK_TIMEOUT_MS, execImpl = execFileSync }) {
486
+ if (!sha) return false;
490
487
  try {
491
- execFileSync('git', ['-C', cwd, 'rev-parse', '--git-dir'], {
492
- timeout: 10_000,
488
+ execImpl('git', ['cat-file', '-e', `${sha}^{commit}`], {
489
+ cwd: cwd || process.cwd(),
490
+ timeout: timeoutMs,
493
491
  encoding: 'utf8',
494
492
  stdio: ['ignore', 'pipe', 'pipe'],
495
493
  });
@@ -499,73 +497,37 @@ function isGitRepo(cwd) {
499
497
  }
500
498
  }
501
499
 
502
- // ─── already-shipped postcondition exemption (original PRD re-runs) ─────────
503
-
504
- const PRD_DELIVERABLE_PATH_RE = /(?:^|[`\s(])((?:src|scripts|session-manager-operations|test|tests|docs|bin)\/[A-Za-z0-9_./-]*[A-Za-z0-9_-]\.[A-Za-z0-9]+)\b/g;
505
-
506
- // Repo-root config files a PRD can legitimately name as its only deliverable.
507
- // Deliberately an exact-name allowlist, not a general root-file pattern:
508
- // a loose rule would match prose mentions (README.md, queue.json) and grant
509
- // false exemptions. Incident: PRD 816 named vitest.config.ts as its primary
510
- // deliverable and it was silently dropped from extraction.
511
- const PRD_ROOT_CONFIG_DELIVERABLES = [
512
- 'package.json',
513
- 'tsconfig.json',
514
- 'vitest.config.ts',
515
- 'vite.config.ts',
516
- 'playwright.config.ts',
517
- 'eslint.config.js',
518
- 'tailwind.config.js',
519
- 'postcss.config.js',
520
- ];
521
-
522
500
  /**
523
- * Extract the deliverable file paths a PRD body names — backticked or bare
524
- * paths under a source dir with a file extension (e.g. `src/main/lib/foo.cjs`,
525
- * `src/renderer/components/Bar.tsx`, `scripts/baz.cjs`), plus any allowlisted
526
- * repo-root config filename named as a whole word (e.g. `vitest.config.ts`).
527
- * Deliberately narrow: only repo-relative paths under a known source root or
528
- * an exact-name root-config allowlist, no globs, no node_modules, no URLs.
529
- * O(n) over the PRD body length.
501
+ * True when some branch/tag/remote ref holds `sha`. A git error resolves false
502
+ * so the run parks instead of passing.
530
503
  */
531
- function extractPrdDeliverablePaths(prdBody) {
532
- if (typeof prdBody !== 'string' || !prdBody) return [];
533
- const seen = new Set();
534
- const out = [];
535
- let m;
536
- PRD_DELIVERABLE_PATH_RE.lastIndex = 0;
537
- while ((m = PRD_DELIVERABLE_PATH_RE.exec(prdBody)) !== null) {
538
- const p = m[1];
539
- if (p.includes('node_modules') || p.includes('..') || seen.has(p)) continue;
540
- seen.add(p);
541
- out.push(p);
542
- }
543
- for (const name of PRD_ROOT_CONFIG_DELIVERABLES) {
544
- if (seen.has(name)) continue;
545
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
546
- const re = new RegExp(`(?:^|[\`\\s(])${escaped}(?:[\`\\s)]|$)`);
547
- if (re.test(prdBody)) {
548
- seen.add(name);
549
- out.push(name);
550
- }
504
+ function commitOnAnyRef({ cwd, sha, timeoutMs = GH_CHECK_TIMEOUT_MS, execImpl = execFileSync }) {
505
+ if (!sha) return false;
506
+ try {
507
+ const out = execImpl('git', ['rev-list', '--count', sha, '--not', '--branches', '--tags', '--remotes'], {
508
+ cwd: cwd || process.cwd(),
509
+ timeout: timeoutMs,
510
+ encoding: 'utf8',
511
+ stdio: ['ignore', 'pipe', 'pipe'],
512
+ });
513
+ return String(out).trim() === '0';
514
+ } catch {
515
+ return false;
551
516
  }
552
- return out;
553
517
  }
554
518
 
555
519
  /**
556
- * Materially check whether every deliverable path a PRD names is already
557
- * tracked in git — i.e. the PRD's work landed in an EARLIER run/commit and
558
- * this run correctly had nothing to do. Uses `git ls-files --error-unmatch`
559
- * (bounded, execImpl injectable for tests). Fails safe in every direction:
560
- * any error, a non-git cwd, or zero paths returns false, which falls straight
561
- * through to today's pass_no_commit behavior.
520
+ * True when `cwd` is inside a git repository. Used to gate the transcript
521
+ * commit-evidence fallback below: a job whose cwd is not a git repo can never
522
+ * produce committedDuringRun=true (gitHead()/committedInWindow() fail closed
523
+ * there), so the fallback must only apply in that narrow case — never when
524
+ * git ancestry is actually observable.
562
525
  */
563
- function allDeliverablesAlreadyTracked({ cwd, paths, execImpl = execFileSync, timeoutMs = 15_000 }) {
564
- if (!Array.isArray(paths) || paths.length === 0) return false;
526
+ function isGitRepo(cwd) {
527
+ if (!cwd) return false;
565
528
  try {
566
- execImpl('git', ['ls-files', '--error-unmatch', '--', ...paths], {
567
- cwd: cwd || process.cwd(),
568
- timeout: timeoutMs,
529
+ execFileSync('git', ['-C', cwd, 'rev-parse', '--git-dir'], {
530
+ timeout: 10_000,
569
531
  encoding: 'utf8',
570
532
  stdio: ['ignore', 'pipe', 'pipe'],
571
533
  });
@@ -575,7 +537,6 @@ function allDeliverablesAlreadyTracked({ cwd, paths, execImpl = execFileSync, ti
575
537
  }
576
538
  }
577
539
 
578
-
579
540
  /**
580
541
  * Material check for a DECLARED artifact-only PRD (`deliverable: artifact` +
581
542
  * `artifactPaths`). Returns true only when every declared path resolves inside
@@ -718,7 +679,7 @@ async function verifyRun({
718
679
  }
719
680
 
720
681
  // ── 2. Parse log ───────────────────────────────────────────────────────
721
- const { events, resultEvent, error: parseError, transcriptCommitLanded } = parseLog(logPath);
682
+ const { events, resultEvent, error: parseError, transcriptCommitLanded, transcriptCommitShas } = parseLog(logPath);
722
683
 
723
684
  if (parseError) {
724
685
  return conclude('verify_unavailable', `log unreadable: ${parseError}`, 'needs_review');
@@ -848,7 +809,25 @@ async function verifyRun({
848
809
  // bare PASS with no commit from one is still a strong silent-failure
849
810
  // signal and stays covered by this check.
850
811
  const isFixPlanJob = /^\d+-fix-/.test(queueEntry?.slug || '');
851
- if (sentinel === 'pass' && !commitEvidence && !isFixPlanJob) {
812
+ // A transcript-reported commit that is not reachable from the repo was
813
+ // dropped (detached HEAD, off-branch); no no-commit exemption may excuse it.
814
+ let unlandedTranscriptShas = [];
815
+ if (sentinel === 'pass' && !commitEvidence && cwdIsGitRepo) {
816
+ unlandedTranscriptShas = (transcriptCommitShas || [])
817
+ .filter((sha) => commitExistsInRepo({ cwd: queueEntry?.cwd, sha }))
818
+ .filter((sha) => (isMergeMainSlug(queueEntry?.slug)
819
+ ? !commitOnAnyRef({ cwd: queueEntry?.cwd, sha })
820
+ : !isAncestorCommit({ cwd: queueEntry?.cwd, sha })));
821
+ }
822
+ if (unlandedTranscriptShas.length > 0) {
823
+ issues.push({
824
+ verdict: 'run_commit_not_landed',
825
+ reason: 'SCHEDULER_VERDICT: PASS but the transcript reports a commit that is not reachable from the repo: '
826
+ + unlandedTranscriptShas.join(', '),
827
+ priority: 1,
828
+ downgradeTo: 'needs_review',
829
+ });
830
+ } else if (sentinel === 'pass' && !commitEvidence && !isFixPlanJob) {
852
831
  // EXEMPTION: `-merge-main` PRDs (see isMergeMainSlug) can genuinely and
853
832
  // correctly find nothing left to do when an out-of-band actor (a human,
854
833
  // another agent, a sibling scheduler job) already merged/updated the
@@ -889,9 +868,7 @@ async function verifyRun({
889
868
  // re-checked every AC item, found it all already implemented by an
890
869
  // earlier run of this exact PRD, declined to make a no-op commit, and
891
870
  // printed a truthful PASS" is correct, idempotent behavior — the
892
- // systemic false-failure class this exemption exists to catch (distinct
893
- // from the already-shipped exemption below, which looks at PRD-named
894
- // file paths rather than a specific prior run's SHA).
871
+ // systemic false-failure class this exemption exists to catch.
895
872
  // (Incident: 812-workbench-review-nits-cleanup, 2026-07-31 — re-fired
896
873
  // ~24 min after its own prior run landed 00d891c; re-verified,
897
874
  // re-ran typecheck + 17 green tests, made no new commit, printed a
@@ -913,34 +890,6 @@ async function verifyRun({
913
890
  },
914
891
  );
915
892
  }
916
- // EXEMPTION: an ORIGINAL PRD re-queued after its deliverables already
917
- // landed. "I checked, the work is already committed and green, nothing
918
- // to change" is a truthful PASS, not a silent no-op — the same
919
- // reasoning that exempts fix-plan slugs above. Materially checked
920
- // against real git state, never inferred from the transcript.
921
- // (Incident: 655-needs-review-rca-feedback-hook, 2026-07-31 — verified
922
- // rcaFeedbackHook.cjs shipped in e13168d, ran typecheck + 23 green
923
- // tests, made no commit, printed a truthful PASS, and was parked
924
- // anyway.)
925
- let alreadyShipped = false;
926
- if (!mergeMainVerified && !priorRunVerified) {
927
- const deliverablePaths = extractPrdDeliverablePaths(prdBody);
928
- if (deliverablePaths.length > 0
929
- && allDeliverablesAlreadyTracked({ cwd: queueEntry?.cwd, paths: deliverablePaths })) {
930
- alreadyShipped = true;
931
- return conclude(
932
- 'pass_no_commit_already_shipped',
933
- `SCHEDULER_VERDICT: PASS with no commit, but every PRD-named deliverable path is already `
934
- + `tracked in git (${deliverablePaths.join(', ')}) — this PRD's work landed in an earlier run`,
935
- null,
936
- {
937
- ...(annotations.length ? { annotations } : {}),
938
- sentinel,
939
- alreadyTrackedPaths: deliverablePaths,
940
- },
941
- );
942
- }
943
- }
944
893
  // EXEMPTION: a PRD that DECLARES `deliverable: artifact` + `artifactPaths`
945
894
  // (all deliverables live in a git-excluded dir, so "no commit" is
946
895
  // correct). Reads the declared list from frontmatter — never scrapes
@@ -950,7 +899,7 @@ async function verifyRun({
950
899
  // through to pass_no_commit below. The commit guard separately requires
951
900
  // a clean tree for this verdict (scheduler.cjs commitGuardVerdict).
952
901
  let artifactVerified = false;
953
- if (!mergeMainVerified && !priorRunVerified && !alreadyShipped) {
902
+ if (!mergeMainVerified && !priorRunVerified) {
954
903
  let fm = null;
955
904
  try { fm = parsePrdFile(prdFullText).frontmatter; } catch { fm = null; }
956
905
  if (fm && fm.deliverable === 'artifact' && Array.isArray(fm.artifactPaths) && fm.artifactPaths.length > 0) {
@@ -976,7 +925,7 @@ async function verifyRun({
976
925
  }
977
926
  }
978
927
  }
979
- if (!mergeMainVerified && !priorRunVerified && !alreadyShipped && !artifactVerified) {
928
+ if (!mergeMainVerified && !priorRunVerified && !artifactVerified) {
980
929
  issues.push({
981
930
  verdict: 'pass_no_commit',
982
931
  reason: 'SCHEDULER_VERDICT: PASS but no commit landed during the run window — the run claims success but produced no code change',
@@ -1020,10 +969,10 @@ module.exports = {
1020
969
  isMergeMainSlug,
1021
970
  extractMergeMainPrNumber,
1022
971
  checkMergeablePr,
1023
- extractPrdDeliverablePaths,
1024
- allDeliverablesAlreadyTracked,
1025
972
  artifactsVerifiedOnDisk,
1026
973
  isAncestorCommit,
974
+ commitExistsInRepo,
975
+ commitOnAnyRef,
1027
976
  isGitRepo,
1028
977
  hasAbandonedBackgroundTask,
1029
978
  };