claude-code-session-manager 0.141.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,313 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * criteriaChecks.cjs — run each structured acceptance criterion's mechanical
5
+ * check (prdCriteria.cjs shape) in a job's tree, so the outcome record and
6
+ * the validator get observed results instead of the job's own prose.
7
+ *
8
+ * - command: parsed with the gate's no-shell parser (parseChain) and run
9
+ * through the gate's own runner (runIsolatedSequence: own TMPDIR, CI=1,
10
+ * no shell). The whole chain is capped at COMMAND_CAP_MS.
11
+ * - file: repo-relative path must exist (and contain `contains`, if set);
12
+ * a path that escapes `cwd` fails closed.
13
+ * - http: loopback hosts only (re-checked here, never trusted from the
14
+ * frontmatter), no redirects followed, HTTP_TIMEOUT_MS timeout; ok when
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).
33
+ * - manual: never run — ok: null; detail carries the guidance line.
34
+ *
35
+ * Never throws: every failure becomes { ok: false, detail }. Checks run
36
+ * sequentially — one command at a time, like the gate.
37
+ */
38
+
39
+ const fs = require('node:fs');
40
+ const path = require('node:path');
41
+ const http = require('node:http');
42
+ const https = require('node:https');
43
+ const { parseChain, runIsolatedSequence } = require('./definitionOfDone.cjs');
44
+
45
+ const COMMAND_CAP_MS = 300_000;
46
+ const HTTP_TIMEOUT_MS = 15_000;
47
+ const HTTP_BODY_MAX_BYTES = 1024 * 1024;
48
+ const FILE_READ_MAX_BYTES = 16 * 1024 * 1024;
49
+ const DETAIL_MAX_CHARS = 500;
50
+ const HTTP_RETRY_ATTEMPTS = 3;
51
+ const HTTP_RETRY_DELAY_MS = 10_000;
52
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
53
+
54
+ /** @param {string} s */
55
+ function clip(s) {
56
+ const t = String(s ?? '').trim();
57
+ return t.length > DETAIL_MAX_CHARS ? `…${t.slice(-DETAIL_MAX_CHARS)}` : t;
58
+ }
59
+
60
+ /**
61
+ * @param {unknown} spec
62
+ * @param {number} capMs
63
+ * @param {string} cwd
64
+ * @returns {Promise<{ok: boolean, detail: string}>}
65
+ */
66
+ async function runCommandCheck(spec, capMs, cwd) {
67
+ if (typeof spec !== 'string' || !spec.trim()) return { ok: false, detail: 'command check has no command' };
68
+ const steps = parseChain(spec.trim());
69
+ if (!steps.length) return { ok: false, detail: 'command cannot run without a shell (refused by the gate parser)' };
70
+ const deadline = Date.now() + capMs;
71
+ for (const step of steps) {
72
+ const remaining = deadline - Date.now();
73
+ if (remaining <= 0) return { ok: false, detail: `timed out after ${capMs} ms cap` };
74
+ const timeoutMs = Math.min(step.timeoutMs, remaining);
75
+ const r = await runIsolatedSequence([{ ...step, timeoutMs }], { cwd });
76
+ const res = r.results[0];
77
+ if (r.status === 'green') continue;
78
+ if (res && res.timedOut) return { ok: false, detail: `timed out after ${timeoutMs} ms: ${res.cmd}` };
79
+ if (r.status === 'unavailable') return { ok: false, detail: `could not run: ${res ? res.cmd : step.argv.join(' ')}` };
80
+ return { ok: false, detail: clip(`exit ${res ? res.code : '?'}: ${res ? res.cmd : ''}\n${res ? res.tail : ''}`) };
81
+ }
82
+ return { ok: true, detail: `exit 0 (${steps.length} step${steps.length === 1 ? '' : 's'})` };
83
+ }
84
+
85
+ /**
86
+ * @param {unknown} spec
87
+ * @param {string} cwd
88
+ * @returns {{ok: boolean, detail: string}}
89
+ */
90
+ function runFileCheck(spec, cwd) {
91
+ /** @type {{path?: unknown, contains?: unknown}} */
92
+ const obj = typeof spec === 'string' ? { path: spec } : (spec && typeof spec === 'object' ? /** @type {any} */ (spec) : {});
93
+ const rel = obj.path;
94
+ if (typeof rel !== 'string' || !rel.trim()) return { ok: false, detail: 'file check has no path' };
95
+ const root = path.resolve(cwd);
96
+ const abs = path.resolve(root, rel);
97
+ if (path.isAbsolute(rel) || (abs !== root && !abs.startsWith(root + path.sep))) {
98
+ return { ok: false, detail: `path is not repo-relative: ${rel}` };
99
+ }
100
+ let st;
101
+ try { st = fs.statSync(abs); } catch { return { ok: false, detail: `missing: ${rel}` }; }
102
+ if (obj.contains === undefined || obj.contains === null) return { ok: true, detail: `exists: ${rel}` };
103
+ if (typeof obj.contains !== 'string') return { ok: false, detail: 'file check contains must be a string' };
104
+ if (!st.isFile()) return { ok: false, detail: `not a file: ${rel}` };
105
+ if (st.size > FILE_READ_MAX_BYTES) return { ok: false, detail: `too large to search (${st.size} bytes): ${rel}` };
106
+ let text;
107
+ try { text = fs.readFileSync(abs, 'utf8'); } catch (e) { return { ok: false, detail: `unreadable: ${rel}` }; }
108
+ return text.includes(obj.contains)
109
+ ? { ok: true, detail: `${rel} contains the text` }
110
+ : { ok: false, detail: `${rel} does not contain ${JSON.stringify(obj.contains)}` };
111
+ }
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
+
118
+ /**
119
+ * @param {unknown} spec
120
+ * @param {number} timeoutMs
121
+ * @param {boolean} [keepBody] attach { body, bodyBytes, truncated } to the result
122
+ * @returns {Promise<HttpResult>}
123
+ */
124
+ function runHttpCheck(spec, timeoutMs, keepBody = false) {
125
+ /** @type {{url?: unknown, status?: unknown, contains?: unknown}} */
126
+ const obj = typeof spec === 'string' ? { url: spec } : (spec && typeof spec === 'object' ? /** @type {any} */ (spec) : {});
127
+ let 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 }); }
129
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
130
+ return Promise.resolve({ ok: false, detail: `refused: protocol ${url.protocol} (http/https only)`, refused: true });
131
+ }
132
+ if (!LOOPBACK_HOSTS.has(url.hostname) || url.username || url.password) {
133
+ return Promise.resolve({ ok: false, detail: `refused: host "${url.hostname}" is not loopback`, refused: true });
134
+ }
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;
138
+ const lib = url.protocol === 'https:' ? https : http;
139
+ return new Promise((resolve) => {
140
+ let done = false;
141
+ /** @param {HttpResult} r */
142
+ const finish = (r) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };
143
+ /** @type {import('node:http').ClientRequest} */
144
+ let req;
145
+ const timer = setTimeout(() => {
146
+ finish({ ok: false, detail: `timed out after ${timeoutMs} ms: ${url.href}` });
147
+ try { req.destroy(); } catch { /* already gone */ }
148
+ }, timeoutMs);
149
+ try {
150
+ // Self-signed certs are normal on a loopback dev server.
151
+ req = lib.request(url, { method: 'GET', ...(lib === https ? { rejectUnauthorized: false } : {}) }, (res) => {
152
+ const got = res.statusCode;
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}` }));
194
+ });
195
+ req.on('error', (e) => finish({ ok: false, detail: `request failed: ${e && e.message ? e.message : e}` }));
196
+ req.end();
197
+ } catch (e) {
198
+ finish({ ok: false, detail: `request failed: ${e && /** @type {Error} */ (e).message ? /** @type {Error} */ (e).message : e}` });
199
+ }
200
+ });
201
+ }
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
+
248
+ /**
249
+ * Run every criterion's check in `cwd`, in order.
250
+ *
251
+ * @param {{ criteria: unknown, cwd: string, commandCapMs?: number, httpTimeoutMs?: number, keepBody?: boolean, httpRetry?: HttpRetry }} opts
252
+ * commandCapMs / httpTimeoutMs exist for tests; callers use the defaults.
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[]>}
258
+ */
259
+ async function runCriteriaChecks({ criteria, cwd, commandCapMs = COMMAND_CAP_MS, httpTimeoutMs = HTTP_TIMEOUT_MS, keepBody = false, httpRetry }) {
260
+ if (!Array.isArray(criteria) || !criteria.length) return [];
261
+ const keep = keepBody === true;
262
+ /** @type {CheckRow[]} */
263
+ const out = [];
264
+ /** @type {Array<{spec: unknown, retryable: boolean} | null>} per-index http state */
265
+ const httpState = [];
266
+ for (let i = 0; i < criteria.length; i++) {
267
+ const c = criteria[i];
268
+ const id = c && typeof c.id === 'string' ? c.id : `ac-${i + 1}`;
269
+ const check = c && c.check && typeof c.check === 'object' ? c.check : { kind: 'manual' };
270
+ const kind = typeof check.kind === 'string' ? check.kind : 'manual';
271
+ /** @type {{ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, refused?: boolean}} */
272
+ let r;
273
+ try {
274
+ if (kind === 'manual') r = { ok: null, detail: typeof check.spec === 'string' && check.spec ? check.spec : 'manual check' };
275
+ else if (kind === 'command') r = await runCommandCheck(check.spec, commandCapMs, cwd);
276
+ else if (kind === 'file') r = runFileCheck(check.spec, cwd);
277
+ else if (kind === 'http') r = await runHttpCheck(check.spec, httpTimeoutMs, keep);
278
+ else r = { ok: false, detail: `unknown check kind ${JSON.stringify(kind)}` };
279
+ } catch (e) {
280
+ r = { ok: false, detail: errDetail(e) };
281
+ }
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];
309
+ }
310
+ return out;
311
+ }
312
+
313
+ module.exports = { runCriteriaChecks, COMMAND_CAP_MS, HTTP_TIMEOUT_MS, HTTP_BODY_MAX_BYTES, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS };
@@ -12,7 +12,7 @@ const fs = require('node:fs');
12
12
  const os = require('node:os');
13
13
  const path = require('node:path');
14
14
  const { spawn, spawnSync } = require('node:child_process');
15
- const { splitFrontmatter } = require('../prd/prdFrontmatter.cjs');
15
+ const { splitFrontmatter, parsePrdFile } = require('../prd/prdFrontmatter.cjs');
16
16
  const { resolvePrdWriteDir } = require('../prd/prdLocations.cjs');
17
17
  const schedulerPaths = require('./schedulerPaths.cjs');
18
18
  const atomicFs = require('../util/atomicFs.cjs');
@@ -488,7 +488,9 @@ function extractAcCommand(prdBody) {
488
488
  * @param {{ resolvePrdPath?: (job: object) => (string|null|Promise<string|null>) }} opts
489
489
  * resolvePrdPath Finds the PRD's current absolute path for this job.
490
490
  * Required — with none, the result is always unverifiable.
491
- * @returns {Promise<{ slug: string, status: 'pass'|'fail'|'unverifiable', code: number|null, ms: number, reason?: string }>}
491
+ * @returns {Promise<{ slug: string, status: 'pass'|'fail'|'unverifiable', code: number|null, ms: number, reason?: string, criteriaChecks?: Array<{id: string, kind: string, ok: boolean|null, detail: string}> }>}
492
+ * criteriaChecks present when the PRD frontmatter has structured `criteria`
493
+ * and the gate actually ran (see criteriaChecks.cjs).
492
494
  */
493
495
  async function reverifyAc(job, { resolvePrdPath } = {}) {
494
496
  const startNs = process.hrtime.bigint();
@@ -531,19 +533,33 @@ async function reverifyAc(job, { resolvePrdPath } = {}) {
531
533
  if (source === 'none' || source === 'absent' || !sequence.length) return unverifiable('no-parseable-gate');
532
534
 
533
535
  const result = await runGateSequence(sequence, { cwd: job.cwd });
534
- if (result.status === 'green') return { slug: job.slug, status: 'pass', code: 0, ms: elapsedMs() };
535
536
  if (result.status === 'busy') return unverifiable('busy');
536
537
  if (result.status === 'unavailable') return unverifiable('gate-unavailable');
537
538
 
539
+ // Structured criteria: after the gate re-run, run each criterion's
540
+ // mechanical check in the same tree (criteriaChecks.cjs) and attach the
541
+ // observed results. Lazy require — criteriaChecks requires this module.
542
+ let criteriaChecks;
543
+ let fmCriteria = null;
544
+ try { fmCriteria = parsePrdFile(raw).frontmatter.criteria; } catch { fmCriteria = null; }
545
+ if (Array.isArray(fmCriteria) && fmCriteria.length) {
546
+ try {
547
+ criteriaChecks = await require('./criteriaChecks.cjs').runCriteriaChecks({ criteria: fmCriteria, cwd: job.cwd });
548
+ } catch { criteriaChecks = undefined; }
549
+ }
550
+ const withChecks = (r) => (criteriaChecks ? { ...r, criteriaChecks } : r);
551
+
552
+ if (result.status === 'green') return withChecks({ slug: job.slug, status: 'pass', code: 0, ms: elapsedMs() });
553
+
538
554
  // status === 'red': a step exited non-zero. A step that was killed for
539
555
  // running past its own `timeout N` is not trustworthy evidence of a real
540
556
  // failure (the machine may just be slow right now), so it is reported as
541
557
  // unverifiable instead of fail — same reasoning reverifyAc has always used
542
558
  // for a step that couldn't even start.
543
559
  const timedOutStep = result.results.find((r) => r.timedOut);
544
- if (timedOutStep) return unverifiable('timeout');
560
+ if (timedOutStep) return withChecks(unverifiable('timeout'));
545
561
  const failedStep = result.results.find((r) => r.status === 'fail');
546
- return { slug: job.slug, status: 'fail', code: failedStep ? failedStep.code : null, ms: elapsedMs() };
562
+ return withChecks({ slug: job.slug, status: 'fail', code: failedStep ? failedStep.code : null, ms: elapsedMs() });
547
563
  }
548
564
 
549
565
  /**
@@ -730,6 +746,20 @@ function writeReport(key, { acResults = [], riskFlags = [], runsDir } = {}) {
730
746
  ...acRows,
731
747
  ].join('\n');
732
748
 
749
+ // ── Criteria checks (structured criteria, criteriaChecks.cjs) ───────────────
750
+ const CHECK_MARK = (ok) => (ok === true ? '✅ pass' : ok === false ? '❌ fail' : '— manual');
751
+ const cell = (v) => String(v ?? '').replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ');
752
+ const criteriaRows = [];
753
+ for (const r of acResults) {
754
+ if (!Array.isArray(r.criteriaChecks)) continue;
755
+ for (const c of r.criteriaChecks) {
756
+ criteriaRows.push(`| ${r.slug} | ${cell(c.id)} | ${cell(c.kind)} | ${CHECK_MARK(c.ok)} | ${cell(c.detail)} |`);
757
+ }
758
+ }
759
+ const criteriaSection = criteriaRows.length
760
+ ? ['| Slug | Criterion | Kind | Result | Detail |', '|------|-----------|------|--------|--------|', ...criteriaRows].join('\n')
761
+ : '_No structured criteria._';
762
+
733
763
  // ── Risk flags table ─────────────────────────────────────────────────────────
734
764
  let riskSection;
735
765
  if (riskFlags.length === 0) {
@@ -751,6 +781,11 @@ function writeReport(key, { acResults = [], riskFlags = [], runsDir } = {}) {
751
781
  attentionLines.push(`- **${r.slug}** — unverifiable AC; manual inspection recommended for ${r.slug}`);
752
782
  }
753
783
  }
784
+ for (const r of acResults) {
785
+ if (!Array.isArray(r.criteriaChecks)) continue;
786
+ const failed = r.criteriaChecks.filter((c) => c.ok === false).map((c) => c.id);
787
+ if (failed.length) attentionLines.push(`- **${r.slug}** — criteria check failed: ${failed.join(', ')}`);
788
+ }
754
789
  for (const r of riskFlags) {
755
790
  attentionLines.push(
756
791
  `- **${r.slug}** — touches ${r.surfaces.join(', ')}; run \`/code-review\` on ${r.slug} — ${r.surfaces.join('/')} path`
@@ -774,6 +809,10 @@ function writeReport(key, { acResults = [], riskFlags = [], runsDir } = {}) {
774
809
  '',
775
810
  acTable,
776
811
  '',
812
+ '## Criteria Checks',
813
+ '',
814
+ criteriaSection,
815
+ '',
777
816
  '## Risk Flags',
778
817
  '',
779
818
  riskSection,
@@ -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
+ };