claude-code-session-manager 0.126.0 → 0.128.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 (107) hide show
  1. package/bin/cli.cjs +71 -9
  2. package/bin/supervise.cjs +84 -0
  3. package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
  4. package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
  5. package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
  6. package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
  7. package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
  8. package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
  9. package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
  10. package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
  11. package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
  12. package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
  13. package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
  14. package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
  15. package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
  16. package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
  17. package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
  18. package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
  19. package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
  20. package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
  21. package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
  22. package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
  23. package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
  24. package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
  25. package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
  26. package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
  27. package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
  28. package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
  29. package/dist/assets/index-DzY_GXYY.js +3081 -0
  30. package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
  33. package/dist/index.html +2 -2
  34. package/dist-web/app.css +1 -1
  35. package/dist-web/app.js +343 -341
  36. package/package.json +1 -1
  37. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  38. package/scripts/scheduler-mcp-server.cjs +209 -7
  39. package/src/main/build-info.json +4 -4
  40. package/src/main/chatRunner.cjs +37 -4
  41. package/src/main/crashDiagnostics.cjs +83 -8
  42. package/src/main/health.cjs +16 -5
  43. package/src/main/index.cjs +46 -0
  44. package/src/main/ipcSchemas.cjs +107 -0
  45. package/src/main/lib/chatBootRecovery.cjs +136 -0
  46. package/src/main/lib/chatInflight.cjs +88 -0
  47. package/src/main/lib/claude/agentModelResolve.cjs +26 -7
  48. package/src/main/lib/claude/personaToolScope.cjs +40 -2
  49. package/src/main/lib/demo-video-kit/capture.cjs +113 -0
  50. package/src/main/lib/demo-video-kit/character.cjs +97 -0
  51. package/src/main/lib/demo-video-kit/checks.cjs +150 -0
  52. package/src/main/lib/demo-video-kit/frames.cjs +200 -0
  53. package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
  54. package/src/main/lib/demo-video-kit/sound.cjs +312 -0
  55. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  56. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  57. package/src/main/lib/epic/epicValidationHook.cjs +31 -3
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  59. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
  60. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +93 -14
  62. package/src/main/lib/opsOwnership.cjs +9 -5
  63. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
  64. package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
  65. package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
  66. package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
  67. package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
  68. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
  69. package/src/main/lib/prd/prdCreate.cjs +17 -2
  70. package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
  71. package/src/main/lib/process/childWithLog.cjs +38 -95
  72. package/src/main/lib/process/memoryScope.cjs +140 -0
  73. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  74. package/src/main/lib/process/procIdentity.cjs +10 -3
  75. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  76. package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
  77. package/src/main/lib/project-pages/playerBridge.cjs +129 -0
  78. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  79. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  80. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  81. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  82. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  83. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  84. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  85. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  86. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  87. package/src/main/lib/smfileHeaders.cjs +11 -3
  88. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  89. package/src/main/projectPages.cjs +107 -30
  90. package/src/main/promptSessionsIpc.cjs +131 -0
  91. package/src/main/scheduler/budget.cjs +31 -0
  92. package/src/main/scheduler/prdParser.cjs +2 -0
  93. package/src/main/scheduler/prdPaths.cjs +54 -0
  94. package/src/main/scheduler/reviewLadder.cjs +17 -0
  95. package/src/main/scheduler/starvation.cjs +22 -0
  96. package/src/main/scheduler.cjs +548 -77
  97. package/src/main/seedSchedulerMcp.cjs +10 -1
  98. package/src/main/templates/PRD_AUTHORING.md +5 -2
  99. package/src/main/transcripts.cjs +8 -0
  100. package/src/main/usage.cjs +4 -2
  101. package/src/main/webRemote.cjs +3 -1
  102. package/src/preload/api.d.ts +113 -7
  103. package/src/preload/apiSurface.json +70 -0
  104. package/src/preload/index.cjs +13 -0
  105. package/src/seed/agents/demo-video-builder.md +141 -43
  106. package/src/seed/agents/project-home-builder.md +26 -13
  107. package/dist/assets/index-DgPUERhe.js +0 -3079
@@ -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 ?? {},
@@ -93,6 +93,8 @@ const ScheduleJobSchema = z
93
93
  sourceTabId: z.string().nullable().optional(),
94
94
  sourcePromptId: z.string().nullable().optional(),
95
95
  epicId: z.string().nullable().optional(),
96
+ // Macro press this job's PRD came from (PRD frontmatter `macroId`).
97
+ macroId: z.string().nullable().optional(),
96
98
  statusHistory: z.array(ScheduleJobStatusHistoryEntrySchema).optional(),
97
99
  // Opt-in exclusive-lease PRD flag (PRD 1107) — serializes this job against
98
100
  // every other job machine-wide for its run so a timing-sensitive gate
@@ -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
@@ -15,6 +15,14 @@ const DEMO_VIDEO_CSP_HEADER = [
15
15
  ].join('; ');
16
16
 
17
17
  const DEMO_VIDEO_PATH_MARKER = '/session-manager-operations/project-pages/demo-video/';
18
+ const VIDEOS_PATH_MARKER = '/session-manager-operations/project-pages/videos/';
19
+ // Legacy demo-video marker stays until the videos/ migration has run everywhere.
20
+ const PATH_MARKERS = [DEMO_VIDEO_PATH_MARKER, VIDEOS_PATH_MARKER];
21
+
22
+ /** @param {string} normalised forward-slash path */
23
+ function matchesFence(normalised) {
24
+ return PATH_MARKERS.some((m) => normalised.includes(m));
25
+ }
18
26
 
19
27
  /**
20
28
  * Response headers for a file served over the smfile:// protocol. A file
@@ -27,7 +35,7 @@ const DEMO_VIDEO_PATH_MARKER = '/session-manager-operations/project-pages/demo-v
27
35
  function smfileResponseHeaders(realPath, contentType) {
28
36
  const normalised = String(realPath).replace(/\\/g, '/');
29
37
  const headers = { 'content-type': contentType };
30
- if (normalised.includes(DEMO_VIDEO_PATH_MARKER)) {
38
+ if (matchesFence(normalised)) {
31
39
  headers['content-security-policy'] = DEMO_VIDEO_CSP_HEADER;
32
40
  }
33
41
  return headers;
@@ -55,7 +63,7 @@ function shouldBlockFrameNavigation({ isMainFrame, currentUrl, targetUrl }) {
55
63
  } catch {
56
64
  return false;
57
65
  }
58
- if (!pathname.includes(DEMO_VIDEO_PATH_MARKER)) return false;
66
+ if (!matchesFence(pathname)) return false;
59
67
 
60
68
  if (typeof targetUrl !== 'string') return false;
61
69
  if (targetUrl.startsWith('smfile:')) return false;
@@ -79,4 +87,4 @@ function smfileUrlToPath(pathname, platform = process.platform) {
79
87
  return require('node:path').win32.normalize(stripped);
80
88
  }
81
89
 
82
- module.exports = { DEMO_VIDEO_CSP_HEADER, smfileResponseHeaders, shouldBlockFrameNavigation, smfileUrlToPath };
90
+ module.exports = { DEMO_VIDEO_CSP_HEADER, VIDEOS_PATH_MARKER, smfileResponseHeaders, shouldBlockFrameNavigation, smfileUrlToPath };
@@ -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';
@@ -17,8 +17,9 @@ const fs = require('node:fs');
17
17
  const path = require('node:path');
18
18
  const chokidar = require('chokidar');
19
19
  const config = require('./config.cjs');
20
- const { opsPath } = require('./lib/opsOwnership.cjs');
20
+ const { opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
21
21
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
22
+ const { listLibrary, migrateLegacy } = require('./lib/project-pages/pagesLibrary.cjs');
22
23
 
23
24
  let mainWindow = null;
24
25
  function attachWindow(window) {
@@ -33,18 +34,6 @@ function demoVideoPath(cwd) {
33
34
  return opsPath(cwd, 'project-pages', 'demo-video', 'index.html');
34
35
  }
35
36
 
36
- /** -> { path: string, mtimeMs: number } | null */
37
- async function getDemoVideo(realCwd) {
38
- const file = demoVideoPath(realCwd);
39
- try {
40
- const stat = await fs.promises.stat(file);
41
- return { path: file, mtimeMs: stat.mtimeMs };
42
- } catch (e) {
43
- if (e.code === 'ENOENT') return null;
44
- throw e;
45
- }
46
- }
47
-
48
37
  /**
49
38
  * Resolve `cwd`'s home.html path, treating the opsOwnership "ephemeral cwd"
50
39
  * throw (a tmpdir/linked-worktree project root) as "no path available"
@@ -59,15 +48,47 @@ function tryHomePath(realCwd) {
59
48
  }
60
49
  }
61
50
 
62
- /** -> { html: string|null, mtimeMs: number|null, demoVideo: {path, mtimeMs}|null } */
51
+ const EMPTY = () => ({ knowledge: [], videos: [], html: null, mtimeMs: null, demoVideo: null });
52
+
53
+ /**
54
+ * -> { knowledge, videos, html, mtimeMs, demoVideo }. Runs the one-shot legacy
55
+ * migration first. html/mtimeMs come from the `overview` knowledge page and
56
+ * demoVideo from the newest video (both kept for the phone remote).
57
+ */
63
58
  async function get({ cwd }) {
64
59
  const realCwd = config.validatePath(cwd);
65
- const { file, ephemeral } = tryHomePath(realCwd);
66
- if (ephemeral) return { html: null, mtimeMs: null, demoVideo: null };
67
- const res = await config.readText(file);
68
- const demoVideo = await getDemoVideo(realCwd);
69
- if (!res.exists) return { html: null, mtimeMs: null, demoVideo };
70
- return { html: res.text, mtimeMs: res.mtimeMs, demoVideo };
60
+ const { ephemeral } = tryHomePath(realCwd);
61
+ if (ephemeral) return EMPTY();
62
+ await migrateLegacy(realCwd);
63
+ const { knowledge, videos } = await listLibrary(realCwd);
64
+ const overview = knowledge.find((k) => k.id === 'overview');
65
+ let html = null;
66
+ if (overview) {
67
+ try {
68
+ html = await fs.promises.readFile(overview.path, 'utf8');
69
+ } catch (e) {
70
+ if (e.code !== 'ENOENT') throw e;
71
+ }
72
+ }
73
+ const newest = videos[0];
74
+ return {
75
+ knowledge,
76
+ videos,
77
+ html,
78
+ mtimeMs: html === null ? null : overview.mtimeMs,
79
+ demoVideo: newest ? { path: newest.path, mtimeMs: newest.mtimeMs } : null,
80
+ };
81
+ }
82
+
83
+ /** True for paths whose change should refresh the library (relative to project-pages/). */
84
+ function isLibraryPath(rel) {
85
+ const parts = rel.split(path.sep);
86
+ if (parts.length === 1) return parts[0] === 'home.html';
87
+ if (parts.length === 2) return parts[0] === 'demo-video' && parts[1] === 'index.html';
88
+ if (parts.length === 3 && (parts[0] === 'knowledge' || parts[0] === 'videos')) {
89
+ return parts[1] !== '_character' && (parts[2] === 'index.html' || parts[2] === 'meta.json');
90
+ }
91
+ return false;
71
92
  }
72
93
 
73
94
  // ─── Push channel ─────────────────────────────────────────────────────────
@@ -110,13 +131,9 @@ async function watchOutput(cwd) {
110
131
  const dir = path.dirname(file);
111
132
  fs.mkdirSync(dir, { recursive: true });
112
133
 
113
- const demoVideoFile = demoVideoPath(realCwd);
114
134
  const push = async (changedPath) => {
115
- // Only home.html or demo-video/index.html — ignore every other sibling file.
116
- if (changedPath) {
117
- const resolved = path.resolve(changedPath);
118
- if (resolved !== path.resolve(file) && resolved !== path.resolve(demoVideoFile)) return;
119
- }
135
+ // Only library files (and the two legacy ones) — ignore everything else.
136
+ if (changedPath && !isLibraryPath(path.relative(dir, path.resolve(changedPath)))) return;
120
137
  let result;
121
138
  try {
122
139
  result = await get({ cwd: realCwd });
@@ -125,16 +142,15 @@ async function watchOutput(cwd) {
125
142
  }
126
143
  sendIfAlive(mainWindow, 'project-pages:changed', {
127
144
  cwd: realCwd,
128
- html: result.html,
129
- mtimeMs: result.mtimeMs,
130
- demoVideo: result.demoVideo,
145
+ ...result,
131
146
  });
132
147
  };
133
148
 
134
149
  const watcher = chokidar.watch(dir, {
135
150
  ignoreInitial: true,
136
151
  persistent: true,
137
- depth: 1,
152
+ depth: 3,
153
+ ignored: (p) => p.split(path.sep).includes('_character'),
138
154
  // Same 50ms/25ms shape config.cjs's generic watcher uses.
139
155
  awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 25 },
140
156
  });
@@ -175,10 +191,69 @@ function closeAllOutputWatchers() {
175
191
  outputWatchers.clear();
176
192
  }
177
193
 
194
+ const WRITER = 'project-home';
195
+
196
+ /**
197
+ * Resolve one library entry folder for rename/delete. Refuses a bad id,
198
+ * '_character', a missing entry, and anything whose realpath is not a direct
199
+ * child (same name) of the kind folder — a symlink escape.
200
+ */
201
+ async function resolveEntry({ cwd, kind, id }) {
202
+ const { schemas, ENTRY_ID_RE } = require('./ipcSchemas.cjs');
203
+ if (kind !== 'knowledge' && kind !== 'video') throw new Error('invalid kind');
204
+ if (typeof id !== 'string' || id === '_character' || !ENTRY_ID_RE.test(id)) throw new Error('invalid entry id');
205
+ const realCwd = config.validatePath(cwd);
206
+ const folder = kind === 'video' ? 'videos' : 'knowledge';
207
+ const kindDir = opsPath(realCwd, 'project-pages', folder);
208
+ const dir = path.join(kindDir, id);
209
+ let realDir;
210
+ let realKind;
211
+ try {
212
+ realDir = await fs.promises.realpath(dir);
213
+ realKind = await fs.promises.realpath(kindDir);
214
+ } catch (e) {
215
+ if (e.code === 'ENOENT') throw new Error('entry not found');
216
+ throw e;
217
+ }
218
+ if (path.dirname(realDir) !== realKind || path.basename(realDir) !== id) {
219
+ throw new Error('entry resolves outside its kind folder');
220
+ }
221
+ const st = await fs.promises.stat(realDir);
222
+ if (!st.isDirectory()) throw new Error('entry not found');
223
+ return { dir: realDir, schema: kind === 'video' ? schemas.projectVideoMeta : schemas.projectPageMeta };
224
+ }
225
+
226
+ /** Rewrite one entry's meta.json title (schema-validated before and after). */
227
+ async function renameEntry(input) {
228
+ const { dir, schema } = await resolveEntry(input);
229
+ const metaFile = path.join(dir, 'meta.json');
230
+ let raw;
231
+ try {
232
+ raw = JSON.parse(await fs.promises.readFile(metaFile, 'utf8'));
233
+ } catch (e) {
234
+ throw new Error(`meta.json unreadable: ${e.code === 'ENOENT' ? 'missing' : e.message}`);
235
+ }
236
+ const current = schema.safeParse(raw);
237
+ if (!current.success) throw new Error('meta.json invalid');
238
+ const next = schema.parse({ ...current.data, title: input.title });
239
+ await config.writeTextAtomic(metaFile, JSON.stringify(next, null, 2) + '\n', { writer: WRITER });
240
+ return { ok: true, title: next.title };
241
+ }
242
+
243
+ /** Remove exactly one entry folder. */
244
+ async function deleteEntry(input) {
245
+ const { dir } = await resolveEntry(input);
246
+ assertOpsWrite(dir, WRITER);
247
+ await fs.promises.rm(dir, { recursive: true, force: false });
248
+ return { ok: true };
249
+ }
250
+
178
251
  function registerProjectPagesIpc() {
179
252
  const { schemas: s, validated: v } = require('./ipcSchemas.cjs');
180
253
  ipcMain.handle('project-pages:get', v(s.projectPagesCwd, get));
181
254
  ipcMain.handle('project-pages:watch', v(s.projectPagesCwd, ({ cwd }) => watchOutput(cwd)));
255
+ ipcMain.handle('project-pages:rename', v(s.projectPagesRename, renameEntry));
256
+ ipcMain.handle('project-pages:delete', v(s.projectPagesDelete, deleteEntry));
182
257
  ipcMain.handle('project-pages:unwatch', v(s.projectPagesCwd, ({ cwd }) => {
183
258
  unwatchOutput(cwd);
184
259
  return { ok: true };
@@ -189,6 +264,8 @@ module.exports = {
189
264
  attachWindow,
190
265
  registerProjectPagesIpc,
191
266
  get,
267
+ renameEntry,
268
+ deleteEntry,
192
269
  watchOutput,
193
270
  unwatchOutput,
194
271
  closeAllOutputWatchers,