claude-code-session-manager 0.142.0 → 0.143.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -12,7 +12,24 @@
12
12
  * a path that escapes `cwd` fails closed.
13
13
  * - http: loopback hosts only (re-checked here, never trusted from the
14
14
  * frontmatter), no redirects followed, HTTP_TIMEOUT_MS timeout; ok when
15
- * the response status equals the expected one (default 200).
15
+ * the response status equals the expected one (default 200) and, when
16
+ * `contains` is set, the first HTTP_BODY_MAX_BYTES of the body include it.
17
+ * With keepBody, each http row also carries { body, bodyBytes, truncated }
18
+ * (body capped at HTTP_BODY_MAX_BYTES); without it rows never hold a body.
19
+ * - httpRetry (opt-in, { attempts?, delayMs?, sleep? }): a dev server that is
20
+ * mid-reload refuses or 404s for a moment, so after the first in-order pass
21
+ * every http row that failed AFTER its request was sent (request/response
22
+ * error, timeout, status mismatch, contains miss) is re-run in order after
23
+ * ONE sleep(delayMs) per round, until none fail or `attempts` is reached
24
+ * (default HTTP_RETRY_ATTEMPTS = 3, clamped 1..3; delayMs default
25
+ * HTTP_RETRY_DELAY_MS). A re-run replaces the row in place (ok, detail and,
26
+ * with keepBody, the body fields). NEVER retried: spec refusals (invalid
27
+ * URL, non-http(s) protocol, non-loopback host, credentials in the URL) and
28
+ * file / command / manual rows. With httpRetry every http row carries
29
+ * `attempts` (1..3; a refusal is 1); without it no row has that key.
30
+ * Worst case per runCriteriaChecks call: each http check at most 3 attempts
31
+ * of at most HTTP_TIMEOUT_MS (15 s) each, plus at most 2 waits of delayMs
32
+ * shared by the whole call (not per check).
16
33
  * - manual: never run — ok: null; detail carries the guidance line.
17
34
  *
18
35
  * Never throws: every failure becomes { ok: false, detail }. Checks run
@@ -27,8 +44,11 @@ const { parseChain, runIsolatedSequence } = require('./definitionOfDone.cjs');
27
44
 
28
45
  const COMMAND_CAP_MS = 300_000;
29
46
  const HTTP_TIMEOUT_MS = 15_000;
47
+ const HTTP_BODY_MAX_BYTES = 1024 * 1024;
30
48
  const FILE_READ_MAX_BYTES = 16 * 1024 * 1024;
31
49
  const DETAIL_MAX_CHARS = 500;
50
+ const HTTP_RETRY_ATTEMPTS = 3;
51
+ const HTTP_RETRY_DELAY_MS = 10_000;
32
52
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
33
53
 
34
54
  /** @param {string} s */
@@ -90,27 +110,35 @@ function runFileCheck(spec, cwd) {
90
110
  : { ok: false, detail: `${rel} does not contain ${JSON.stringify(obj.contains)}` };
91
111
  }
92
112
 
113
+ /**
114
+ * refused: internal marker for a spec refusal (never sent, never retried); never copied onto a row.
115
+ * @typedef {{ok: boolean, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, refused?: boolean}} HttpResult
116
+ */
117
+
93
118
  /**
94
119
  * @param {unknown} spec
95
120
  * @param {number} timeoutMs
96
- * @returns {Promise<{ok: boolean, detail: string}>}
121
+ * @param {boolean} [keepBody] attach { body, bodyBytes, truncated } to the result
122
+ * @returns {Promise<HttpResult>}
97
123
  */
98
- function runHttpCheck(spec, timeoutMs) {
99
- /** @type {{url?: unknown, status?: unknown}} */
124
+ function runHttpCheck(spec, timeoutMs, keepBody = false) {
125
+ /** @type {{url?: unknown, status?: unknown, contains?: unknown}} */
100
126
  const obj = typeof spec === 'string' ? { url: spec } : (spec && typeof spec === 'object' ? /** @type {any} */ (spec) : {});
101
127
  let url;
102
- try { url = new URL(String(obj.url)); } catch { return Promise.resolve({ ok: false, detail: 'http check url is not a valid URL' }); }
128
+ try { url = new URL(String(obj.url)); } catch { return Promise.resolve({ ok: false, detail: 'http check url is not a valid URL', refused: true }); }
103
129
  if (url.protocol !== 'http:' && url.protocol !== 'https:') {
104
- return Promise.resolve({ ok: false, detail: `refused: protocol ${url.protocol} (http/https only)` });
130
+ return Promise.resolve({ ok: false, detail: `refused: protocol ${url.protocol} (http/https only)`, refused: true });
105
131
  }
106
132
  if (!LOOPBACK_HOSTS.has(url.hostname) || url.username || url.password) {
107
- return Promise.resolve({ ok: false, detail: `refused: host "${url.hostname}" is not loopback` });
133
+ return Promise.resolve({ ok: false, detail: `refused: host "${url.hostname}" is not loopback`, refused: true });
108
134
  }
109
135
  const want = Number.isInteger(obj.status) ? /** @type {number} */ (obj.status) : 200;
136
+ const contains = typeof obj.contains === 'string' && obj.contains !== '' ? obj.contains : null;
137
+ const readBody = contains !== null || keepBody;
110
138
  const lib = url.protocol === 'https:' ? https : http;
111
139
  return new Promise((resolve) => {
112
140
  let done = false;
113
- /** @param {{ok: boolean, detail: string}} r */
141
+ /** @param {HttpResult} r */
114
142
  const finish = (r) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };
115
143
  /** @type {import('node:http').ClientRequest} */
116
144
  let req;
@@ -121,11 +149,48 @@ function runHttpCheck(spec, timeoutMs) {
121
149
  try {
122
150
  // Self-signed certs are normal on a loopback dev server.
123
151
  req = lib.request(url, { method: 'GET', ...(lib === https ? { rejectUnauthorized: false } : {}) }, (res) => {
124
- res.resume();
125
152
  const got = res.statusCode;
126
- finish(got === want
127
- ? { ok: true, detail: `HTTP ${got}` }
128
- : { ok: false, detail: `HTTP ${got}, expected ${want}` });
153
+ if (!readBody) {
154
+ res.resume();
155
+ finish(got === want
156
+ ? { ok: true, detail: `HTTP ${got}` }
157
+ : { ok: false, detail: `HTTP ${got}, expected ${want}` });
158
+ return;
159
+ }
160
+ /** @type {Buffer[]} */
161
+ const chunks = [];
162
+ let bytes = 0;
163
+ let truncated = false;
164
+ let settled = false;
165
+ const decide = () => {
166
+ if (settled) return;
167
+ settled = true;
168
+ const buf = Buffer.concat(chunks, bytes);
169
+ const text = buf.toString('utf8');
170
+ /** @type {HttpResult} */
171
+ let r;
172
+ if (got !== want) r = { ok: false, detail: `HTTP ${got}, expected ${want}` };
173
+ else if (contains === null) r = { ok: true, detail: `HTTP ${got}` };
174
+ else if (text.includes(contains)) r = { ok: true, detail: `HTTP ${got}, body contains the text` };
175
+ else r = { ok: false, detail: clip(`HTTP ${got}, body does not contain ${JSON.stringify(contains)}`) };
176
+ if (keepBody) Object.assign(r, { body: text, bodyBytes: bytes, truncated });
177
+ finish(r);
178
+ };
179
+ res.on('data', (/** @type {Buffer} */ chunk) => {
180
+ if (settled) return;
181
+ const room = HTTP_BODY_MAX_BYTES - bytes;
182
+ if (chunk.length > room) {
183
+ if (room > 0) { chunks.push(chunk.subarray(0, room)); bytes += room; }
184
+ truncated = true;
185
+ decide();
186
+ res.destroy();
187
+ return;
188
+ }
189
+ chunks.push(chunk);
190
+ bytes += chunk.length;
191
+ });
192
+ res.on('end', decide);
193
+ res.on('error', (e) => finish({ ok: false, detail: `response failed: ${e && e.message ? e.message : e}` }));
129
194
  });
130
195
  req.on('error', (e) => finish({ ok: false, detail: `request failed: ${e && e.message ? e.message : e}` }));
131
196
  req.end();
@@ -135,35 +200,114 @@ function runHttpCheck(spec, timeoutMs) {
135
200
  });
136
201
  }
137
202
 
203
+ /**
204
+ * @typedef {{id: string, kind: string, ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, attempts?: number}} CheckRow
205
+ * @typedef {{ attempts?: number, delayMs?: number, sleep?: (ms: number) => Promise<void> }} HttpRetry
206
+ */
207
+
208
+ /**
209
+ * @param {string} id
210
+ * @param {string} kind
211
+ * @param {{ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean}} r
212
+ * @param {boolean} keepBody
213
+ * @returns {CheckRow}
214
+ */
215
+ function toRow(id, kind, r, keepBody) {
216
+ /** @type {CheckRow} */
217
+ const row = { id, kind, ok: r.ok, detail: r.detail };
218
+ if (keepBody && kind === 'http' && typeof r.body === 'string') {
219
+ row.body = r.body;
220
+ row.bodyBytes = r.bodyBytes;
221
+ row.truncated = r.truncated;
222
+ }
223
+ return row;
224
+ }
225
+
226
+ /** @param {unknown} e */
227
+ function errDetail(e) {
228
+ return `check error: ${e && /** @type {Error} */ (e).message ? /** @type {Error} */ (e).message : e}`;
229
+ }
230
+
231
+ /**
232
+ * @param {HttpRetry} httpRetry
233
+ * @returns {{attempts: number, delayMs: number, sleep: (ms: number) => Promise<void>}}
234
+ */
235
+ function normalizeRetry(httpRetry) {
236
+ const a = httpRetry.attempts;
237
+ const attempts = typeof a === 'number' && Number.isInteger(a)
238
+ ? Math.min(HTTP_RETRY_ATTEMPTS, Math.max(1, a))
239
+ : HTTP_RETRY_ATTEMPTS;
240
+ const d = httpRetry.delayMs;
241
+ const delayMs = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : HTTP_RETRY_DELAY_MS;
242
+ const sleep = typeof httpRetry.sleep === 'function'
243
+ ? httpRetry.sleep
244
+ : (/** @type {number} */ ms) => new Promise((r) => setTimeout(r, ms));
245
+ return { attempts, delayMs, sleep: /** @type {(ms: number) => Promise<void>} */ (sleep) };
246
+ }
247
+
138
248
  /**
139
249
  * Run every criterion's check in `cwd`, in order.
140
250
  *
141
- * @param {{ criteria: unknown, cwd: string, commandCapMs?: number, httpTimeoutMs?: number }} opts
251
+ * @param {{ criteria: unknown, cwd: string, commandCapMs?: number, httpTimeoutMs?: number, keepBody?: boolean, httpRetry?: HttpRetry }} opts
142
252
  * commandCapMs / httpTimeoutMs exist for tests; callers use the defaults.
143
- * @returns {Promise<Array<{id: string, kind: string, ok: boolean|null, detail: string}>>}
253
+ * keepBody (default false): http rows also carry { body, bodyBytes, truncated };
254
+ * off, every row is exactly { id, kind, ok, detail } (gate shadow + job row store no body).
255
+ * httpRetry (default off): re-run failed-after-sent http checks (see header);
256
+ * http rows then also carry `attempts`.
257
+ * @returns {Promise<CheckRow[]>}
144
258
  */
145
- async function runCriteriaChecks({ criteria, cwd, commandCapMs = COMMAND_CAP_MS, httpTimeoutMs = HTTP_TIMEOUT_MS }) {
259
+ async function runCriteriaChecks({ criteria, cwd, commandCapMs = COMMAND_CAP_MS, httpTimeoutMs = HTTP_TIMEOUT_MS, keepBody = false, httpRetry }) {
146
260
  if (!Array.isArray(criteria) || !criteria.length) return [];
261
+ const keep = keepBody === true;
262
+ /** @type {CheckRow[]} */
147
263
  const out = [];
264
+ /** @type {Array<{spec: unknown, retryable: boolean} | null>} per-index http state */
265
+ const httpState = [];
148
266
  for (let i = 0; i < criteria.length; i++) {
149
267
  const c = criteria[i];
150
268
  const id = c && typeof c.id === 'string' ? c.id : `ac-${i + 1}`;
151
269
  const check = c && c.check && typeof c.check === 'object' ? c.check : { kind: 'manual' };
152
270
  const kind = typeof check.kind === 'string' ? check.kind : 'manual';
153
- /** @type {{ok: boolean|null, detail: string}} */
271
+ /** @type {{ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, refused?: boolean}} */
154
272
  let r;
155
273
  try {
156
274
  if (kind === 'manual') r = { ok: null, detail: typeof check.spec === 'string' && check.spec ? check.spec : 'manual check' };
157
275
  else if (kind === 'command') r = await runCommandCheck(check.spec, commandCapMs, cwd);
158
276
  else if (kind === 'file') r = runFileCheck(check.spec, cwd);
159
- else if (kind === 'http') r = await runHttpCheck(check.spec, httpTimeoutMs);
277
+ else if (kind === 'http') r = await runHttpCheck(check.spec, httpTimeoutMs, keep);
160
278
  else r = { ok: false, detail: `unknown check kind ${JSON.stringify(kind)}` };
161
279
  } catch (e) {
162
- r = { ok: false, detail: `check error: ${e && /** @type {Error} */ (e).message ? /** @type {Error} */ (e).message : e}` };
280
+ r = { ok: false, detail: errDetail(e) };
163
281
  }
164
- out.push({ id, kind, ok: r.ok, detail: r.detail });
282
+ httpState.push(kind === 'http' ? { spec: check.spec, retryable: r.refused !== true } : null);
283
+ out.push(toRow(id, kind, r, keep));
284
+ }
285
+ if (!httpRetry || typeof httpRetry !== 'object') return out;
286
+
287
+ const { attempts, delayMs, sleep } = normalizeRetry(httpRetry);
288
+ /** @type {number[]} */
289
+ const ran = out.map(() => 1);
290
+ for (let attempt = 2; attempt <= attempts; attempt++) {
291
+ const due = [];
292
+ for (let i = 0; i < out.length; i++) {
293
+ const st = httpState[i];
294
+ if (st && st.retryable && out[i].ok === false) due.push(i);
295
+ }
296
+ if (!due.length) break;
297
+ await sleep(delayMs);
298
+ for (const i of due) {
299
+ const st = /** @type {{spec: unknown, retryable: boolean}} */ (httpState[i]);
300
+ /** @type {HttpResult} */
301
+ let r;
302
+ try { r = await runHttpCheck(st.spec, httpTimeoutMs, keep); } catch (e) { r = { ok: false, detail: errDetail(e) }; }
303
+ ran[i] = attempt;
304
+ out[i] = toRow(out[i].id, out[i].kind, r, keep);
305
+ }
306
+ }
307
+ for (let i = 0; i < out.length; i++) {
308
+ if (httpState[i]) out[i].attempts = ran[i];
165
309
  }
166
310
  return out;
167
311
  }
168
312
 
169
- module.exports = { runCriteriaChecks, COMMAND_CAP_MS, HTTP_TIMEOUT_MS };
313
+ module.exports = { runCriteriaChecks, COMMAND_CAP_MS, HTTP_TIMEOUT_MS, HTTP_BODY_MAX_BYTES, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS };
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * heldSchedulerTurns.cjs — the one place that decides whether a scheduler-started
5
+ * chat turn (origin 'scheduler': PLAN SETTLED digests, job notices, auto-start
6
+ * follow-ups) may start under the usage hold, and that keeps every held message
7
+ * durably until the hold ends.
8
+ *
9
+ * Store: schedulerPaths.heldSchedulerTurnsPath() — { version: 1, entries: [] }.
10
+ * Each entry: { id, tabId, kind, prompt, sessionId, cwd, heldAt, holdReason, holdDetail, lastAttempt? }.
11
+ *
12
+ * An 'unconfirmed' send that carries a requestId (the renderer ack timed out) stamps
13
+ * its entries with lastAttempt { requestId, at } and drain skips them for
14
+ * LAST_ATTEMPT_GRACE_MS: the renderer may still have run the turn. A late ack
15
+ * (chatRunner → confirmLateDelivery(requestId)) removes them; no ack → resent once
16
+ * after the grace.
17
+ *
18
+ * drain() delivers each tab's held messages ONCE, oldest first, as one coalesced
19
+ * prompt; entries are removed only after the send resolved a disposition that
20
+ * produced (or queued) a run.
21
+ *
22
+ * Must NOT require chatRunner.cjs or scheduler.cjs — both require this module.
23
+ * No audit writes here: callers audit drain()'s return value.
24
+ */
25
+
26
+ const crypto = require('node:crypto');
27
+ const { writeJsonAtomicSync, readJsonOrSync } = require('../util/atomicFs.cjs');
28
+ const { heldSchedulerTurnsPath } = require('./schedulerPaths.cjs');
29
+
30
+ const KINDS = Object.freeze(['settle-digest', 'job-notice', 'auto-start-follow-up', 'scheduler-notice']);
31
+ // 'held': the hold returned between the drain check and the send. The batch is not
32
+ // re-deferred (heldBatch), so the originals must stay or they are lost.
33
+ const NOT_ACCEPTED = new Set(['refused', 'unconfirmed', 'held']);
34
+ const LAST_ATTEMPT_GRACE_MS = 10 * 60 * 1000;
35
+
36
+ /** @type {null | (() => any)} */
37
+ let holdProvider = null;
38
+ /** @type {null | Promise<Array<{ tabId: string, delivered: number, dropped: number }>>} */
39
+ let draining = null;
40
+
41
+ function setHoldProvider(fn) {
42
+ holdProvider = typeof fn === 'function' ? fn : null;
43
+ }
44
+
45
+ /** The current usage hold object, or null (no provider, provider throws, or no hold). */
46
+ function currentHold() {
47
+ if (!holdProvider) return null;
48
+ try {
49
+ const hold = holdProvider();
50
+ return hold && typeof hold === 'object' ? hold : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ function isEntry(e) {
57
+ return !!e && typeof e === 'object' && typeof e.id === 'string'
58
+ && typeof e.tabId === 'string' && typeof e.prompt === 'string';
59
+ }
60
+
61
+ function readEntries() {
62
+ let file;
63
+ try { file = readJsonOrSync(heldSchedulerTurnsPath(), null); } catch { return []; }
64
+ if (!file || typeof file !== 'object' || !Array.isArray(file.entries)) return [];
65
+ return file.entries.filter(isEntry);
66
+ }
67
+
68
+ function writeEntries(entries) {
69
+ writeJsonAtomicSync(heldSchedulerTurnsPath(), { version: 1, entries });
70
+ }
71
+
72
+ /**
73
+ * Keep one scheduler message for later. The same tabId+kind+prompt already held
74
+ * is not stored twice (the existing entry is returned).
75
+ */
76
+ function defer({ tabId, prompt, kind, sessionId, cwd, hold } = /** @type {any} */ ({})) {
77
+ if (typeof tabId !== 'string' || !tabId) throw new TypeError('defer: tabId required');
78
+ if (typeof prompt !== 'string' || !prompt) throw new TypeError('defer: prompt required');
79
+ const k = KINDS.includes(kind) ? kind : 'scheduler-notice';
80
+ const entries = readEntries();
81
+ const existing = entries.find((e) => e.tabId === tabId && e.kind === k && e.prompt === prompt);
82
+ if (existing) return existing;
83
+ const entry = {
84
+ id: crypto.randomUUID(),
85
+ tabId,
86
+ kind: k,
87
+ prompt,
88
+ sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,
89
+ cwd: typeof cwd === 'string' && cwd ? cwd : null,
90
+ heldAt: new Date().toISOString(),
91
+ holdReason: hold && typeof hold.reason === 'string' ? hold.reason : null,
92
+ holdDetail: hold && typeof hold.detail === 'string' ? hold.detail : null,
93
+ };
94
+ entries.push(entry);
95
+ writeEntries(entries);
96
+ return entry;
97
+ }
98
+
99
+ const SUMMARY_TAB_LIMIT = 20;
100
+
101
+ /** { count, tabs }: tabs = unique tab ids, oldest-held first, at most SUMMARY_TAB_LIMIT. */
102
+ function summary() {
103
+ const entries = readEntries();
104
+ const tabs = [...new Set([...entries].sort(byHeldAt).map((e) => e.tabId))].slice(0, SUMMARY_TAB_LIMIT);
105
+ return { count: entries.length, tabs };
106
+ }
107
+
108
+ function byHeldAt(a, b) {
109
+ const ta = Date.parse(a.heldAt) || 0;
110
+ const tb = Date.parse(b.heldAt) || 0;
111
+ return ta - tb;
112
+ }
113
+
114
+ function buildCoalescedPrompt(entries) {
115
+ const list = [...entries].sort(byHeldAt);
116
+ const n = list.length;
117
+ const parts = [
118
+ `The usage hold kept ${n} scheduler message(s) for this session while automatic work was paused. They are delivered now, oldest first.`,
119
+ ];
120
+ list.forEach((e, i) => { parts.push(`--- ${i + 1} of ${n} ---\n${e.prompt}`); });
121
+ return parts.join('\n\n');
122
+ }
123
+
124
+ /** True while an entry's last unconfirmed attempt may still be acked late. */
125
+ function inAttemptGrace(e, now) {
126
+ const a = e.lastAttempt;
127
+ if (!a || typeof a !== 'object' || typeof a.requestId !== 'string') return false;
128
+ const at = Date.parse(a.at);
129
+ return Number.isFinite(at) && now - at < LAST_ATTEMPT_GRACE_MS;
130
+ }
131
+
132
+ /** Stamp the given entry ids with lastAttempt (one atomic write). */
133
+ function stampAttempt(ids, requestId) {
134
+ const at = new Date().toISOString();
135
+ const entries = readEntries();
136
+ let changed = false;
137
+ for (const e of entries) {
138
+ if (ids.has(e.id)) { e.lastAttempt = { requestId, at }; changed = true; }
139
+ }
140
+ if (changed) writeEntries(entries);
141
+ }
142
+
143
+ /**
144
+ * The renderer acked a timed-out send late (a run was produced): remove exactly
145
+ * the entries stamped with that requestId, in one atomic write. Returns the count.
146
+ */
147
+ function confirmLateDelivery(requestId) {
148
+ if (typeof requestId !== 'string' || !requestId) return 0;
149
+ const entries = readEntries();
150
+ const left = entries.filter((e) => !(e.lastAttempt && e.lastAttempt.requestId === requestId));
151
+ const removed = entries.length - left.length;
152
+ if (removed > 0) writeEntries(left);
153
+ return removed;
154
+ }
155
+
156
+ async function drainOnce({ send, isStillNeeded }) {
157
+ const now = Date.now();
158
+ const entries = readEntries().filter((e) => !inAttemptGrace(e, now));
159
+ if (entries.length === 0) return [];
160
+ /** @type {Map<string, any[]>} */
161
+ const groups = new Map();
162
+ for (const e of [...entries].sort(byHeldAt)) {
163
+ if (!groups.has(e.tabId)) groups.set(e.tabId, []);
164
+ groups.get(e.tabId).push(e);
165
+ }
166
+ const remove = new Set();
167
+ const results = [];
168
+ for (const [tabId, group] of groups) {
169
+ const keep = [];
170
+ let dropped = 0;
171
+ for (const e of group) {
172
+ let needed = true;
173
+ if (typeof isStillNeeded === 'function') {
174
+ try { needed = (await isStillNeeded(e)) !== false; } catch { needed = true; }
175
+ }
176
+ if (needed) keep.push(e);
177
+ else { dropped += 1; remove.add(e.id); }
178
+ }
179
+ let delivered = 0;
180
+ if (keep.length > 0) {
181
+ const head = keep.find((e) => e.sessionId) ?? keep[0];
182
+ const withCwd = keep.find((e) => e.cwd) ?? keep[0];
183
+ let disposition = 'unconfirmed';
184
+ let requestId = null;
185
+ try {
186
+ const res = await send(tabId, buildCoalescedPrompt(keep), {
187
+ origin: 'scheduler',
188
+ heldBatch: true,
189
+ sessionId: head.sessionId ?? undefined,
190
+ cwd: withCwd.cwd ?? undefined,
191
+ });
192
+ disposition = res && typeof res.disposition === 'string' ? res.disposition : 'unconfirmed';
193
+ requestId = res && typeof res.requestId === 'string' && res.requestId ? res.requestId : null;
194
+ } catch {
195
+ disposition = 'unconfirmed';
196
+ }
197
+ // Stamp right away (synchronously after the send resolved) so a late ack
198
+ // arriving while other tabs are still sending finds its entries.
199
+ if (disposition === 'unconfirmed' && requestId) {
200
+ stampAttempt(new Set(keep.map((e) => e.id)), requestId);
201
+ }
202
+ if (!NOT_ACCEPTED.has(disposition)) {
203
+ delivered = keep.length;
204
+ for (const e of keep) remove.add(e.id);
205
+ }
206
+ }
207
+ results.push({ tabId, delivered, dropped });
208
+ }
209
+ if (remove.size > 0) {
210
+ // Re-read: entries deferred while sends were in flight are kept.
211
+ writeEntries(readEntries().filter((e) => !remove.has(e.id)));
212
+ }
213
+ return results;
214
+ }
215
+
216
+ /**
217
+ * Deliver every tab's held messages once. Single-flight: a call while a drain
218
+ * runs returns that drain's promise.
219
+ * @param {{ send: (tabId: string, prompt: string, extra: object) => Promise<{ disposition: string }>, isStillNeeded?: (entry: any) => boolean | Promise<boolean> }} opts
220
+ */
221
+ function drain(opts) {
222
+ if (draining) return draining;
223
+ if (!opts || typeof opts.send !== 'function') return Promise.resolve([]);
224
+ draining = drainOnce(opts).finally(() => { draining = null; });
225
+ return draining;
226
+ }
227
+
228
+ module.exports = {
229
+ KINDS,
230
+ setHoldProvider,
231
+ currentHold,
232
+ defer,
233
+ summary,
234
+ buildCoalescedPrompt,
235
+ drain,
236
+ confirmLateDelivery,
237
+ LAST_ATTEMPT_GRACE_MS,
238
+ };
@@ -57,6 +57,16 @@ function normalizeSample(s) {
57
57
  return out;
58
58
  }
59
59
 
60
+ /**
61
+ * Re-append identity of a stored sample, independent of its key order (never JSON.stringify).
62
+ * With runId + unit: (runId, unit, at). Without either: every field (agentType, peakMb, at,
63
+ * runId, unit), so a legacy or provenance-less peak never collides with another on `at` alone.
64
+ */
65
+ function sampleKey(x) {
66
+ if (x.runId && x.unit) return `p\0${x.runId}\0${x.unit}\0${x.at}`;
67
+ return `f\0${x.agentType}\0${x.peakMb}\0${x.at}\0${x.runId || ''}\0${x.unit || ''}`;
68
+ }
69
+
60
70
  function defaultStorePath() {
61
71
  return path.join(require('./schedulerPaths.cjs').schedulerHome(), STORE_FILE);
62
72
  }
@@ -269,8 +279,8 @@ function createJobMemoryStats(deps = {}) {
269
279
  liveDuringWrite = null;
270
280
  if (landed.length && samples && samples.length) {
271
281
  const stored = readSamplesUncached(file);
272
- const have = new Set(stored.map((x) => JSON.stringify(x)));
273
- const missing = landed.filter((x) => !have.has(JSON.stringify(x)));
282
+ const have = new Set(stored.map(sampleKey));
283
+ const missing = landed.filter((x) => !have.has(sampleKey(x)));
274
284
  if (missing.length) writeSamples(file, [...stored, ...missing]);
275
285
  }
276
286
  }
@@ -303,6 +313,7 @@ module.exports = {
303
313
  backfillFromRunLogs: defaultInstance.backfillFromRunLogs,
304
314
  createJobMemoryStats,
305
315
  quantile,
316
+ sampleKey,
306
317
  STORE_FILE,
307
318
  MAX_SAMPLES,
308
319
  RECENT_PER_TYPE,