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
@@ -50,12 +50,14 @@ const os = require('node:os');
50
50
  const { AsyncLocalStorage } = require('node:async_hooks');
51
51
  const { startDispatchLoop } = require('./lib/scheduler/dispatchLoop.cjs');
52
52
  const schedulerPaths = require('./lib/scheduler/schedulerPaths.cjs');
53
+ const { VOICE_ID_RE } = require('./lib/demo-video-kit/voiceLibrary.cjs');
53
54
  const { randomUUID } = require('node:crypto');
54
55
  const { execFile, execFileSync, spawnSync } = require('node:child_process');
55
- const { buildJobSandboxSettings, sandboxDependencies, sandboxChildEnv, SANDBOX_PROFILES } = require('./lib/claude/jobSandboxPolicy.cjs');
56
+ const { buildJobSandboxSettings, sandboxDependencies, sandboxChildEnv, jobEnvironmentName, environmentHookEnv, wouldBlockRecord } = require('./lib/claude/jobSandboxPolicy.cjs');
57
+ const { loadEnvironment } = require('./lib/claude/environmentProfiles.cjs');
56
58
  const { ipcMain } = require('electron');
57
59
  const billing = require('./usage.cjs');
58
- const { cleanChildEnv, pathWithUserBins } = require('./lib/process/cleanEnv.cjs');
60
+ const { cleanChildEnv, pathWithUserBins, assertNoCredentials } = require('./lib/process/cleanEnv.cjs');
59
61
  const { ensureTimeoutShim, withTimeoutShimOnPath } = require('./lib/process/timeoutShim.cjs');
60
62
  const supervisor = require('./supervisor.cjs');
61
63
  const { processGroupRssMb } = require('./lib/process/procGroupRss.cjs');
@@ -98,15 +100,23 @@ const { checkMainDependencyHealth, repairMainDependencies } = require('./lib/git
98
100
  const mainDepsRepairAt = new Map();
99
101
  const MAIN_DEPS_REPAIR_COOLDOWN_MS = 10 * 60_000;
100
102
  const { resolveBindingRateLimitReset } = require('./lib/claude/rateLimitWindow.cjs');
101
- const { isResetFresh, bindingWindow, degradedBudget, meterFailureBudget } = require('./lib/claude/usageCircuit.cjs');
103
+ const { isResetFresh, bindingWindow, usageWindows, degradedBudget, meterFailureBudget } = require('./lib/claude/usageCircuit.cjs');
104
+ // The one rule for whether an automatic tick may dispatch (named apart from the
105
+ // `utilizationHold` snapshot variable below).
106
+ const autoDispatchHold = require('./scheduler/utilizationHold.cjs');
102
107
  const { computeQueueHealth } = require('./lib/scheduler/queueHealth.cjs');
103
- const { createLoadGate, topCpuConsumers } = require('./lib/scheduler/loadGate.cjs');
108
+ const { createLoadGate, topCpuConsumers, formatLoadGateDetail, measuredMemoryGate, formatMemoryGateDetail } = require('./lib/scheduler/loadGate.cjs');
109
+ const jobMemoryStats = require('./lib/scheduler/jobMemoryStats.cjs');
104
110
  const { openLog, withChildAndLog } = require('./lib/process/childWithLog.cjs');
111
+ const epicEventLog = require('./lib/epic/epicEventLog.cjs');
112
+ const { createJobToolUseEmitter } = require('./lib/toolUseClassify.cjs');
105
113
  const { killTree, detachedSpawnOpts } = require('./lib/process/killTree.cjs');
114
+ const { reniceLeftovers } = require('./lib/process/leftoverRenice.cjs');
106
115
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
107
116
  const { createBroadcastCoalescer } = require('./lib/broadcastCoalescer.cjs');
108
117
  const prdParser = require('./scheduler/prdParser.cjs');
109
118
  const reviewLadder = require('./scheduler/reviewLadder.cjs');
119
+ const { isCancelledRow } = require('./lib/scheduler/cancelledRow.cjs');
110
120
  const starvation = require('./scheduler/starvation.cjs');
111
121
  const budget = require('./scheduler/budget.cjs');
112
122
  const { validatorEstimateMinutes } = require('./lib/epic/epicSweepValidator.cjs');
@@ -115,21 +125,25 @@ const prdPaths = require('./scheduler/prdPaths.cjs');
115
125
  const sessionsStore = require('./sessionsStore.cjs');
116
126
  const { enqueueExternalPrompt } = require('./chatRunner.cjs');
117
127
  const { appendResponseEventIfKnown, appendResponseEventWithReason } = require('./promptSessionEvents.cjs');
128
+ const { postArtifactReadyNotice } = require('./lib/epic/artifactNotice.cjs');
118
129
  const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFromEnv, buildPreflightHoldNotice, preflightHoldNoticeKey } = require('./lib/scheduler/reviewNotice.cjs');
130
+ const { phaseOfJob } = require('./lib/phaseProjection.cjs');
119
131
  const epicValidationHook = require('./lib/epic/epicValidationHook.cjs');
120
132
  const prdCreate = require('./lib/prd/prdCreate.cjs');
121
133
  const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
122
134
  const { expandHome } = require('./lib/util/expandHome.cjs');
123
135
  const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
124
136
  const promptSessionTranscript = require('./promptSessionTranscript.cjs');
125
- const { verifyRun, parseLog, scanSentinel, scanForeignWipPathsClaim } = require('./runVerify.cjs');
137
+ const { verifyRun, captureArtifactEvidence, parseLog, scanSentinel, scanForeignWipPathsClaim } = require('./runVerify.cjs');
126
138
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/scheduler/terminalRunOutcome.cjs');
127
139
  const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath } = require('./lib/scheduler/fixPlanSlug.cjs');
128
140
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
129
141
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
130
142
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
131
143
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
132
- const { harvestPlanRecords } = require('./lib/scheduler/planRecordHarvest.cjs');
144
+ const { harvestPlanRecords, saveValidatorVerdicts } = require('./lib/scheduler/planRecordHarvest.cjs');
145
+ const artifactStore = require('./lib/epic/artifactStore.cjs');
146
+ const prdOutcomeRecord = require('./lib/scheduler/prdOutcomeRecord.cjs');
133
147
  const logs = require('./logs.cjs');
134
148
  const { schemas, validated, SCHEDULE_SLUG_RE } = require('./ipcSchemas.cjs');
135
149
  const { readBody, sendJson } = require('./lib/feedback-remote/localAdminHttp.cjs');
@@ -144,6 +158,7 @@ const {
144
158
  INVESTIGATION_MAX_MS,
145
159
  STARVATION_ESCALATE_MS,
146
160
  STARVE_ESCALATION_MS,
161
+ environmentEnforcement,
147
162
  } = require('./lib/scheduler/schedulerConfig.cjs');
148
163
  // A running job past this fraction of its own budget gets a durable
149
164
  // `budgetWarning` stamp on its row (see the budget watchdog below) so the
@@ -154,6 +169,7 @@ const { runDefinitionOfDoneOnDrain } = require('./lib/scheduler/dodDrainHook.cjs
154
169
  const { writeRcaReport, extractRcaBlock } = require('./lib/scheduler/rcaReport.cjs');
155
170
  const queueHistory = require('./lib/scheduler/queueHistory.cjs');
156
171
  const { resolveGate, runGateSequence, gateTimeoutMs } = require('./lib/scheduler/definitionOfDone.cjs');
172
+ const { runCriteriaChecks, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS } = require('./lib/scheduler/criteriaChecks.cjs');
157
173
  const queueOps = require('./queueOps.cjs');
158
174
  // Feedback-auto-PRD sweep — formerly only run by the external scheduler-watchdog
159
175
  // while the app was down (PRD 686 moved it in-app so it also runs while alive).
@@ -163,14 +179,17 @@ const queueOps = require('./queueOps.cjs');
163
179
  const { listEpicPrdDirs, listArchivedPrdDirs, deriveProjectCwdFromPrdPath, isSafeEpicId } = require('./lib/prd/prdLocations.cjs');
164
180
  const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/epic/epicMint.cjs');
165
181
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
182
+ const agentSnapshot = require('./lib/claude/agentSnapshot.cjs');
166
183
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
167
- const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv } = require('./lib/claude/personaToolScope.cjs');
168
- const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured } = require('./lib/scheduler/validatorVerdictSchema.cjs');
184
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames } = require('./lib/claude/personaToolScope.cjs');
185
+ const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured, expectedFromCriteria, formatCriteriaChecksSection } = require('./lib/scheduler/validatorVerdictSchema.cjs');
169
186
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
170
- const { transitionJob, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
187
+ const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
171
188
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
172
189
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
173
190
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
191
+ const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
192
+ const autoStartedSession = require('./lib/feedback-remote/autoStartedSession.cjs');
174
193
  const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
175
194
  const needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
176
195
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
@@ -208,9 +227,10 @@ const { splitFrontmatter, parsePrdFile, serializePrdFile, isArtifactOnlyDeclarat
208
227
  const { applyStructuredPrdPatch } = require('./lib/prd/prdBodyPatch.cjs');
209
228
  const { resolvePersonaDefaultEstimate, DEFAULT_PRD_AGENT_TYPE } = require('./lib/prd/prdAgentType.cjs');
210
229
  const { resolveDepSlug, findNearMatches, bareSlug } = require('./lib/prd/depSlugResolve.cjs');
211
- const { writeJsonAtomic, readJsonOrSync } = require('./lib/util/atomicFs.cjs');
230
+ const { writeJsonAtomic, readJsonOrSync, readJsonOr } = require('./lib/util/atomicFs.cjs');
212
231
  const { writeToolRiskGuardSettingsFile } = require('./lib/epic/guardSpawnSettings.cjs');
213
232
  const toolRiskMarks = require('./lib/claude/toolRiskMarks.cjs');
233
+ const toolClearance = require('./lib/scheduler/toolClearance.cjs');
214
234
  const { computeDispositionRewrite, mintPlanId, resolveInheritedPlanId } = require('./lib/prd/prdDisposition.cjs');
215
235
  const cancelDependents = require('./scheduler/cancelDependents.cjs');
216
236
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
@@ -406,15 +426,39 @@ const FINISH_ARTIFACT_ONLY_VERDICT_LINE = `
406
426
  const FINISH_ARTIFACT_ONLY_COMMIT_LINE = `
407
427
  This job is artifact-only: its output is git-excluded, so there is nothing to stage. Skip the commit and go to the next step.`;
408
428
 
429
+ /**
430
+ * jobDeclaredArtifactPaths(job) → Promise<string[]> — the job PRD's
431
+ * frontmatter artifactPaths (live PRD, else its archived copy). [] on any
432
+ * read/parse error; never throws.
433
+ */
434
+ async function jobDeclaredArtifactPaths(job) {
435
+ try {
436
+ const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
437
+ if (!prdPath) return [];
438
+ const fm = parsePrdFile(fs.readFileSync(prdPath, 'utf8')).frontmatter;
439
+ if (!fm || !Array.isArray(fm.artifactPaths)) return [];
440
+ // Only plan-records entries are this harvest's; every other declared
441
+ // artifact belongs to harvestJobArtifacts and must not log a refusal here.
442
+ return fm.artifactPaths.filter((p) => typeof p === 'string'
443
+ && path.posix.normalize(p.replace(/\\/g, '/')).startsWith(ARTIFACT_PLAN_RECORDS_PREFIX));
444
+ } catch {
445
+ return [];
446
+ }
447
+ }
448
+
409
449
  /**
410
450
  * harvestJobPlanRecords(job, worktreeDir, projectRoot) — copy this run's
411
- * plan records from its worktree into the main checkout. Logs, never throws.
451
+ * plan records from its worktree into the main checkout: the job's own
452
+ * plan-records/<epicId>/ folder plus every plan record its PRD declares in
453
+ * frontmatter artifactPaths (which may sit in another Epic's folder).
454
+ * Logs, never throws.
412
455
  */
413
- function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
456
+ async function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
414
457
  try {
415
458
  const epicId = job.epicId || job.sourcePromptId;
416
459
  if (!epicId || !worktreeDir || !projectRoot || path.resolve(worktreeDir) === path.resolve(projectRoot)) return;
417
- const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId });
460
+ const declaredPaths = await jobDeclaredArtifactPaths(job);
461
+ const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths });
418
462
  if (copied.length) console.log(`[scheduler] ${job.slug}: harvested ${copied.length} plan record(s) into ${projectRoot}`);
419
463
  for (const sk of skipped) console.warn(`[scheduler] ${job.slug}: plan record not harvested: ${sk.path} — ${sk.reason}`);
420
464
  } catch (e) {
@@ -422,6 +466,82 @@ function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
422
466
  }
423
467
  }
424
468
 
469
+ const ARTIFACT_PLAN_RECORDS_PREFIX = 'session-manager-operations/plan-records/';
470
+
471
+ /**
472
+ * jobArtifactRunId(job, runId) — the staging-folder key for ONE job run. The
473
+ * batch runId (pickRunDir) is shared by every job in a tick, so the job slug
474
+ * is appended; an id the store would refuse falls back to a stable hash.
475
+ */
476
+ function jobArtifactRunId(job, runId) {
477
+ const slug = job && typeof job.slug === 'string' ? job.slug : '';
478
+ const base = [runId, slug].filter((v) => typeof v === 'string' && v).join('-');
479
+ if (base && artifactStore.RUN_ID_RE.test(base)) return base;
480
+ return `job-${require('node:crypto').createHash('sha256').update(base || 'unknown').digest('hex').slice(0, 32)}`;
481
+ }
482
+
483
+ /**
484
+ * harvestJobArtifacts(job, worktreeDir, projectRoot, { runId }) — copy this
485
+ * job's declared artifactPaths (regular files under worktreeDir; plan records
486
+ * excluded — harvestJobPlanRecords owns them) and its SM_ARTIFACTS_DIR staging
487
+ * folder into the project's Artifacts store (artifacts/<epic-id>/, producer
488
+ * prdSlug) before the worktree is removed. Logs, never throws.
489
+ */
490
+ async function harvestJobArtifacts(job, worktreeDir, projectRoot, { runId = job && job.runId } = {}) {
491
+ const slug = job && job.slug;
492
+ try {
493
+ const epicId = job.epicId || job.sourcePromptId;
494
+ if (!epicId || !worktreeDir || !projectRoot) return;
495
+ if (!fs.existsSync(worktreeDir)) {
496
+ console.warn(`[scheduler] ${slug}: artifact harvest skipped — worktree missing: ${worktreeDir}`);
497
+ return;
498
+ }
499
+ const producer = { epicId, prdSlug: slug || null, sessionId: job.sessionId || null };
500
+ const wtBase = path.resolve(worktreeDir);
501
+ let published = 0;
502
+ /** every publish result of this harvest, for the one 'artifact-ready' notice */
503
+ const landed = [];
504
+ const declared = Array.isArray(job.artifactPaths) ? job.artifactPaths : [];
505
+ for (const p of declared) {
506
+ if (typeof p !== 'string' || !p || p.includes('\0')) continue;
507
+ const norm = path.posix.normalize(p.replace(/\\/g, '/'));
508
+ if (norm.startsWith(ARTIFACT_PLAN_RECORDS_PREFIX)) continue;
509
+ const abs = path.resolve(wtBase, p);
510
+ const rel = path.relative(wtBase, abs);
511
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
512
+ console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — outside the worktree`);
513
+ continue;
514
+ }
515
+ let st;
516
+ try { st = fs.lstatSync(abs); } catch { console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — missing`); continue; }
517
+ if (!st.isFile()) { console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — not a regular file`); continue; }
518
+ const res = await artifactStore.publishArtifact({
519
+ projectRoot, epicId, srcPath: abs, producer, allowedRoots: [wtBase],
520
+ });
521
+ if (res.ok) { published += 1; landed.push({ storedPath: res.storedPath, entry: res.entry }); }
522
+ else console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — ${res.error}`);
523
+ }
524
+ if (runId) {
525
+ let stagingDir = null;
526
+ try { stagingDir = artifactStore.stagingDirFor({ runId: jobArtifactRunId(job, runId) }); } catch (e) {
527
+ console.warn(`[scheduler] ${slug}: artifact staging folder unavailable — ${e && e.message ? e.message : e}`);
528
+ }
529
+ if (stagingDir) {
530
+ const { published: pub, skipped } = await artifactStore.ingestDir({ projectRoot, epicId, srcDir: stagingDir, producer });
531
+ published += pub.length;
532
+ landed.push(...pub);
533
+ for (const sk of skipped) console.warn(`[scheduler] ${slug}: staged artifact not harvested: ${sk.path} — ${sk.reason}`);
534
+ try { fs.rmdirSync(stagingDir); } catch { /* not empty (skipped files) or already gone */ }
535
+ }
536
+ }
537
+ if (published) console.log(`[scheduler] ${slug}: harvested ${published} artifact(s) into ${projectRoot}`);
538
+ // One 'artifact-ready' notice for everything this harvest published (never throws).
539
+ if (landed.length) await postArtifactReadyNotice({ cwd: projectRoot, epicId, entries: landed });
540
+ } catch (e) {
541
+ console.error(`[scheduler] ${slug}: artifact harvest failed`, e);
542
+ }
543
+ }
544
+
425
545
  // Validator jobs only (`--json-schema`): the CLI replaces the result text
426
546
  // with the JSON, so the scheduler reads the verdict from structured output.
427
547
  const FINISH_VALIDATOR_VERDICT_LINE = `
@@ -435,6 +555,10 @@ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPl
435
555
  ${commitStepNum}. COMMIT — stage only the exact paths you created or changed for this PRD,
436
556
  then commit:
437
557
  \`git add <path> [<path>...] && git commit -m "<type>(<scope>): <summary>"\`
558
+ If you found work worth doing outside this PRD's criteria, add one
559
+ \`Follow-up: <one line>\` trailer per item (a second -m), for example:
560
+ \`git commit -m "<type>(<scope>): <summary>" -m "Follow-up: <item>"\`
561
+ Do not do that work.
438
562
  Never stage the whole tree with a wildcard or blanket git add.
439
563
  Why: other jobs may be writing files in this same working tree right now.
440
564
  A blanket add puts their half-done work in your commit and breaks both
@@ -522,14 +646,11 @@ const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
522
646
  const HEARTBEAT_MAX_BYTES = 1024 * 1024;
523
647
  // DEFAULT_PROJECT_CWD imported from lib/scheduler/schedulerBatch.cjs (single source of truth).
524
648
 
525
- // Each headless claude -p job can shell out to tsc/vite/pytest and grow well
526
- // past 1 GB at peak; reserve 2.5 GB of PEAK headroom per running+pending slot.
527
- // A running job's already-resident memory is credited back (consumedMb in
528
- // memoryLimitedBatchSize) because MemAvailable is already net of it. Raised from 1.5 GB
529
- // after the 2026-06-16 OOM: 3 concurrent cross-project jobs + their build
530
- // subprocesses pushed a 24 GB host ~10 GB into swap and the OOM killer took
531
- // Electron — every pty got SIGHUP (code=0 signal=1).
532
- const MIN_FREE_MB_PER_JOB = 2500;
649
+ // Per-job memory reservations are MEASURED (lib/scheduler/jobMemoryStats.cjs: p75 for
650
+ // a new job, p50 growth for a running one, one shared spike buffer) and applied by
651
+ // loadGate.measuredMemoryGate in tickBody. The flat 2.5 GB/job rule (raised from 1.5 GB
652
+ // after the 2026-06-16 OOM: 3 concurrent jobs pushed a 24 GB host ~10 GB into swap and
653
+ // the OOM killer took Electron) survives only as jobMemoryStats' too-few-samples fallback.
533
654
 
534
655
  // Absolute headroom kept free for the Electron host (main + renderer + GPU) and
535
656
  // the OS — NEVER lent to jobs. Without it the gate green-lights a job whenever
@@ -621,23 +742,6 @@ function swapLimitedBatchSize(mem, runningCount, batchLen) {
621
742
  return Math.min(batchLen, Math.max(0, 1 - runningCount));
622
743
  }
623
744
 
624
- /**
625
- * Pure helper: clamp a batch down so launching `toLaunch` more jobs doesn't
626
- * drop available memory below MIN_FREE_MB_PER_JOB per active slot.
627
- * Exported for unit tests.
628
- */
629
- function memoryLimitedBatchSize(availableMb, minPerJob, runningCount, batchLen, consumedMb = 0) {
630
- if (availableMb === Infinity) return batchLen;
631
- // Credit is bounded by the running jobs' own reservations: never negative,
632
- // never more permissive than a 0-running machine.
633
- const credit = Math.min(Math.max(Number(consumedMb) || 0, 0), minPerJob * runningCount);
634
- let allowed = batchLen;
635
- while (allowed > 0 && availableMb < minPerJob * (runningCount + allowed) - credit) {
636
- allowed--;
637
- }
638
- return allowed;
639
- }
640
-
641
745
  /**
642
746
  * Memory available to LAUNCH jobs with: MemAvailable minus the host reserve,
643
747
  * floored at 0. Keeping the host reserve out of the job budget is what stops the
@@ -678,14 +782,26 @@ const memoryScope = require('./lib/process/memoryScope.cjs');
678
782
  */
679
783
  function planJobScope({ jobSpawn, jobArgs, slug, startedAt, deps = {} }) {
680
784
  // Limits first: with the cap off, never probe systemd.
681
- const limits = (deps.memoryLimitsFor || memoryScope.memoryLimitsFor)({ totalRamMb: Math.floor(os.totalmem() / 1048576) });
785
+ const limits = deps.memoryLimitsFor
786
+ ? deps.memoryLimitsFor({ totalRamMb: Math.floor(os.totalmem() / 1048576) })
787
+ : memoryScope.schedulerJobMemoryLimits();
682
788
  const supported = limits ? (deps.scopeSupported || memoryScope.scopeSupported)() : false;
683
- if (!supported || !limits) return { spawn: jobSpawn, unit: null };
789
+ if (!supported || !limits) return { spawn: jobSpawn, unit: null, memoryMaxMb: null };
684
790
  const unit = `sm-job-${memoryScope.sanitizeUnit(slug)}-${startedAt}`;
685
791
  const wrapped = (deps.wrapInMemoryScope || memoryScope.wrapInMemoryScope)({
686
792
  command: jobSpawn.command, args: jobSpawn.args || jobArgs, unit, limits,
687
793
  });
688
- return { spawn: { ...jobSpawn, command: wrapped.command, args: wrapped.args, argv0: undefined }, unit };
794
+ return { spawn: { ...jobSpawn, command: wrapped.command, args: wrapped.args, argv0: undefined }, unit, memoryMaxMb: limits.memoryMaxMb };
795
+ }
796
+
797
+ /**
798
+ * Failure reason for a job its own scope OOM-killed: the last sampled
799
+ * oom_kill > 0 on a non-zero (or signal) exit. Null otherwise.
800
+ */
801
+ function memoryCapFailureReason(state, exitCode) {
802
+ if (!state || !(Number(state.oomKills) > 0) || exitCode === 0) return null;
803
+ const cap = Number(state.memoryMaxMb) > 0 ? `${Math.round(state.memoryMaxMb / 1024)} GB ` : '';
804
+ return `job hit its ${cap}memory cap (oom_kill=${state.oomKills})`;
689
805
  }
690
806
 
691
807
  /** Reads the job's cgroup dir from /proc/<pid>/cgroup (cgroup v2). Null when unavailable. */
@@ -715,6 +831,78 @@ function sampleJobScope(state, fsImpl = fs) {
715
831
 
716
832
  const JOB_SCOPE_SAMPLE_MS = 30000;
717
833
 
834
+ // Newest run logs the boot backfill reads at most (each read whole; repeats are deduped).
835
+ const MEMORY_BACKFILL_MAX_FILES = 500;
836
+
837
+ /** The heartbeat's view of the last memory-gate decision (deferred or clamped), or null. */
838
+ function heartbeatMemGate(g) {
839
+ if (!g) return null;
840
+ const pick = ['availableMb', 'threshold', 'reservationMb', 'spikeBufferMb', 'runningGrowthMb', 'consumedMb', 'measured', 'deferred', 'clamped', 'at'];
841
+ return Object.fromEntries(pick.filter((k) => g[k] !== undefined).map((k) => [k, g[k]]));
842
+ }
843
+
844
+ /**
845
+ * Seeds the job-memory store from the scheduler runs folder itself
846
+ * (schedulerPaths.runsDir(): <runId>/<slug>.log). jobMemoryStats.backfillFromRunLogs
847
+ * lists at most 2 × MEMORY_BACKFILL_MAX_FILES run folders, reads the newest
848
+ * MEMORY_BACKFILL_MAX_FILES logs in bounded batches, runs only while the store holds
849
+ * fewer than 30 samples, dedupes by run folder + unit, and never rejects. Its store
850
+ * reads, run-log I/O and final store write (atomicFs.writeTextAtomic) are all async;
851
+ * the one synchronous step is re-appending a live recordPeak that landed during that
852
+ * write (see backfillFromRunLogs). `deps.runsDir` defaults to schedulerPaths.runsDir().
853
+ * Resolves to the number of samples added.
854
+ */
855
+ async function backfillMemoryStats(deps = {}) {
856
+ const runsDir = deps.runsDir || schedulerPaths.runsDir();
857
+ const added = await (deps.backfillFromRunLogs || jobMemoryStats.backfillFromRunLogs)(runsDir, { maxFiles: MEMORY_BACKFILL_MAX_FILES });
858
+ if (added > 0) console.log(`[scheduler] memory stats: backfilled ${added} job peak(s) from ${runsDir}`);
859
+ return added;
860
+ }
861
+
862
+ // Delay after scheduler start before the one memory backfill pass (keeps it off the boot path).
863
+ const MEMORY_BACKFILL_DELAY_MS = 60_000;
864
+ let memoryBackfillTimer = null;
865
+ let memoryBackfillPending = null;
866
+ let memoryBackfillSettle = null; // resolves memoryBackfillPending early (cancel)
867
+
868
+ /**
869
+ * Schedules ONE backfillMemoryStats pass MEMORY_BACKFILL_DELAY_MS from now on an
870
+ * unref'd timer, so boot itself never reads run logs. A second call while a pass
871
+ * is pending returns the same promise. Resolves to the samples added (0 on error,
872
+ * 0 when cancelMemoryBackfill() runs first). Scheduling itself does no fs work.
873
+ */
874
+ function scheduleMemoryBackfill(deps = {}) {
875
+ if (memoryBackfillPending) return memoryBackfillPending;
876
+ const delayMs = deps.delayMs ?? MEMORY_BACKFILL_DELAY_MS;
877
+ memoryBackfillPending = new Promise((resolve) => {
878
+ memoryBackfillSettle = resolve;
879
+ memoryBackfillTimer = setTimeout(() => {
880
+ memoryBackfillTimer = null;
881
+ backfillMemoryStats(deps).catch(() => 0).then(resolve);
882
+ }, delayMs);
883
+ if (memoryBackfillTimer.unref) memoryBackfillTimer.unref();
884
+ });
885
+ const pending = memoryBackfillPending.finally(() => {
886
+ if (memoryBackfillPending === pending) { memoryBackfillPending = null; memoryBackfillSettle = null; }
887
+ });
888
+ memoryBackfillPending = pending;
889
+ return pending;
890
+ }
891
+
892
+ /**
893
+ * stop() path: clears a not-yet-fired backfill timer and settles the pending
894
+ * scheduleMemoryBackfill() promise with 0, so no awaiter hangs after stop(). A pass
895
+ * already reading logs is not interrupted (it never rejects and ends on its own);
896
+ * its awaiters still see 0.
897
+ */
898
+ function cancelMemoryBackfill() {
899
+ if (memoryBackfillTimer) { clearTimeout(memoryBackfillTimer); memoryBackfillTimer = null; }
900
+ const settle = memoryBackfillSettle;
901
+ memoryBackfillSettle = null;
902
+ memoryBackfillPending = null;
903
+ if (settle) settle(0);
904
+ }
905
+
718
906
  /** Starts the unref'd 30 s sampler once cgroupDir is known; finalizeJobScope clears it. */
719
907
  function startJobScopeSampling(state, fsImpl = fs) {
720
908
  if (!state || !state.cgroupDir || state.finalized || state.sampler) return;
@@ -723,7 +911,11 @@ function startJobScopeSampling(state, fsImpl = fs) {
723
911
  if (state.sampler.unref) state.sampler.unref();
724
912
  }
725
913
 
726
- /** Logs the last sampled memory.peak + oom_kill to the run log, then stops the scope exactly once. */
914
+ /**
915
+ * Logs the last sampled memory.peak + oom_kill to the run log, records the peak with
916
+ * the job's agentType ('dev-lead' when absent) and run folder (state.runId) through jobMemoryStats.recordPeak (the
917
+ * memory gate's measured reservations), then stops the scope exactly once.
918
+ */
727
919
  function finalizeJobScope(state, safeLog, deps = {}) {
728
920
  if (!state || !state.unit || state.finalized) return;
729
921
  state.finalized = true;
@@ -738,6 +930,13 @@ function finalizeJobScope(state, safeLog, deps = {}) {
738
930
  safeLog(`\n[scheduler] memory scope ${state.unit}: peak=${hasPeak ? `${Math.round(state.peak / 1048576)}MB` : 'n/a'} ` +
739
931
  `oom_kill=${hasOom ? state.oomKills : 'n/a'}\n`);
740
932
  }
933
+ if (hasPeak) {
934
+ const agentType = typeof state.agentType === 'string' && state.agentType ? state.agentType : 'dev-lead';
935
+ (deps.recordPeak || jobMemoryStats.recordPeak)({
936
+ agentType, peakMb: Math.round(state.peak / 1048576), unit: state.unit,
937
+ ...(state.runId ? { runId: state.runId } : {}),
938
+ });
939
+ }
741
940
  } catch { /* stats are best-effort */ }
742
941
  (deps.stopScope || memoryScope.stopScope)(state.unit);
743
942
  }
@@ -885,6 +1084,12 @@ function loadSchedulerState() {
885
1084
  if (typeof s.backoffNextAt === 'number' || s.backoffNextAt === null) backoffNextAt = s.backoffNextAt;
886
1085
  if (typeof s.cachedUtilization === 'number' || s.cachedUtilization === null) cachedUtilization = s.cachedUtilization;
887
1086
  if (typeof s.cachedBindingWindowName === 'string' || s.cachedBindingWindowName === null) cachedBindingWindowName = s.cachedBindingWindowName;
1087
+ // A pre-provenance file has no flag: a restored number was a real reading.
1088
+ cachedUtilizationKnown = typeof s.cachedUtilizationKnown === 'boolean'
1089
+ ? s.cachedUtilizationKnown
1090
+ : typeof cachedUtilization === 'number';
1091
+ restoredUsageWindows = isValidUsageWindowList(s.usageWindows) ? s.usageWindows : null;
1092
+ openAutoDispatchHold = restoreOpenAutoDispatchHold(s.openAutoDispatchHold);
888
1093
  } catch { /* first boot or corrupt — start fresh */ }
889
1094
  }
890
1095
 
@@ -893,6 +1098,93 @@ function getSchedulerStateSnapshot() {
893
1098
  return { lastPollOk, lastFailureKind, backoffNextAt, cachedUtilization, cachedBindingWindowName };
894
1099
  }
895
1100
 
1101
+ /** A persisted open hold is trusted only with a string holdKey and a parseable startedAt; restored ones are marked. */
1102
+ function restoreOpenAutoDispatchHold(v) {
1103
+ if (!v || typeof v !== 'object' || typeof v.holdKey !== 'string') return null;
1104
+ if (typeof v.startedAt !== 'string' || !Number.isFinite(Date.parse(v.startedAt))) return null;
1105
+ return {
1106
+ holdKey: v.holdKey,
1107
+ reason: typeof v.reason === 'string' ? v.reason : null,
1108
+ window: typeof v.window === 'string' ? v.window : null,
1109
+ threshold: Number.isFinite(v.threshold) ? v.threshold : null,
1110
+ resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null,
1111
+ startedAt: v.startedAt,
1112
+ maxPercent: Number.isFinite(v.maxPercent) ? v.maxPercent : null,
1113
+ heldTicks: Number.isFinite(v.heldTicks) ? v.heldTicks : 0,
1114
+ restored: true,
1115
+ };
1116
+ }
1117
+
1118
+ /** Test-only seam: the open audit hold, and a reset that drops it from memory (a simulated process exit). */
1119
+ function _getOpenAutoDispatchHoldForTests() { return openAutoDispatchHold; }
1120
+ function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1121
+
1122
+ /**
1123
+ * Track the auto-dispatch hold in audit-log.jsonl: one started event when a
1124
+ * hold opens, one ended event when it lifts or its identity changes. Never
1125
+ * throws (an audit failure must not break the tick).
1126
+ * @param {object | null} hold currentAutoDispatchHold() result
1127
+ * @param {number} pending pending-row count for the started event
1128
+ */
1129
+ function trackAutoDispatchHoldAudit(hold, pending) {
1130
+ try {
1131
+ const identity = hold ? autoDispatchHold.holdIdentityKey(hold) : null;
1132
+ const open = openAutoDispatchHold;
1133
+ if (open && open.holdKey === identity) {
1134
+ if (Number.isFinite(hold.percent) && (open.maxPercent == null || hold.percent > open.maxPercent)) open.maxPercent = hold.percent;
1135
+ open.heldTicks += 1;
1136
+ return;
1137
+ }
1138
+ if (open) {
1139
+ appendAuditEvent('auto_dispatch_hold_ended', {
1140
+ reason: open.reason,
1141
+ window: open.window,
1142
+ threshold: open.threshold,
1143
+ resetsAt: open.resetsAt,
1144
+ holdKey: open.holdKey,
1145
+ startedAt: open.startedAt,
1146
+ endedAt: new Date().toISOString(),
1147
+ maxPercent: open.maxPercent,
1148
+ heldTicks: open.heldTicks,
1149
+ ...(open.restored ? { endedAcrossRestart: true } : {}),
1150
+ });
1151
+ openAutoDispatchHold = null;
1152
+ }
1153
+ if (hold) {
1154
+ appendAuditEvent('auto_dispatch_hold_started', {
1155
+ reason: hold.reason,
1156
+ window: hold.window ?? null,
1157
+ percent: hold.percent ?? null,
1158
+ threshold: hold.threshold ?? null,
1159
+ baseThreshold: hold.baseThreshold ?? null,
1160
+ resetsAt: hold.resetsAt ?? null,
1161
+ holdKey: identity,
1162
+ pending,
1163
+ version: SCHEDULER_BUILD_IDENTITY.version,
1164
+ });
1165
+ openAutoDispatchHold = {
1166
+ holdKey: identity,
1167
+ reason: hold.reason,
1168
+ window: hold.window ?? null,
1169
+ threshold: hold.threshold ?? null,
1170
+ baseThreshold: hold.baseThreshold ?? null,
1171
+ resetsAt: hold.resetsAt ?? null,
1172
+ startedAt: new Date().toISOString(),
1173
+ maxPercent: Number.isFinite(hold.percent) ? hold.percent : null,
1174
+ heldTicks: 1,
1175
+ };
1176
+ }
1177
+ persistSchedulerState();
1178
+ } catch (e) {
1179
+ console.warn('[scheduler] auto-dispatch hold audit failed', e?.message);
1180
+ }
1181
+ }
1182
+
1183
+ /** A persisted usageWindows list is trusted only if every entry names a window with a finite percent. */
1184
+ function isValidUsageWindowList(v) {
1185
+ return Array.isArray(v) && v.every((w) => w && typeof w.window === 'string' && Number.isFinite(w.percent));
1186
+ }
1187
+
896
1188
  function persistSchedulerState() {
897
1189
  // Sync write: called from many sync hot paths (clearPause, pollLoop catch
898
1190
  // block) and the sidecar is tiny (<1 KB). Converting to async here would
@@ -929,6 +1221,24 @@ function persistSchedulerState() {
929
1221
  backoffNextAt,
930
1222
  cachedUtilization,
931
1223
  cachedBindingWindowName,
1224
+ // Real reading vs the 100% "no reading ever" placeholder, and every
1225
+ // unscoped window of the last real reading — so a restart during a
1226
+ // non-429 outage (no payload held) still knows weekly_all, not only
1227
+ // the binding session window.
1228
+ cachedUtilizationKnown,
1229
+ usageWindows: utilizationReading().windows,
1230
+ openAutoDispatchHold: openAutoDispatchHold
1231
+ ? {
1232
+ holdKey: openAutoDispatchHold.holdKey,
1233
+ reason: openAutoDispatchHold.reason,
1234
+ window: openAutoDispatchHold.window,
1235
+ threshold: openAutoDispatchHold.threshold,
1236
+ resetsAt: openAutoDispatchHold.resetsAt,
1237
+ startedAt: openAutoDispatchHold.startedAt,
1238
+ maxPercent: openAutoDispatchHold.maxPercent,
1239
+ heldTicks: openAutoDispatchHold.heldTicks,
1240
+ }
1241
+ : null,
932
1242
  });
933
1243
  } catch (e) {
934
1244
  console.warn('[scheduler] failed to persist scheduler state', e?.message);
@@ -1241,7 +1551,19 @@ function heartbeatTick(deps = {}) {
1241
1551
  // Which window `utilization` (and nextReset) refer to — a reader of
1242
1552
  // this log can't otherwise tell a 5h hold from a weekly one.
1243
1553
  utilizationWindow: cachedBindingWindowName,
1554
+ utilizationHold,
1555
+ // Scheduler chat turns the usage hold is keeping (heldSchedulerTurns.cjs).
1556
+ heldSchedulerTurns: (() => {
1557
+ const sum = heldSchedulerTurns.summary() || {};
1558
+ return {
1559
+ count: Number(sum.count) || 0,
1560
+ tabs: Array.isArray(sum.tabs) ? sum.tabs : [],
1561
+ };
1562
+ })(),
1244
1563
  consecutiveFailures,
1564
+ // Why a memory-held tick held (PRD 4019): the new job's reservation, the
1565
+ // shared spike buffer and the running jobs' growth term. null = not gated.
1566
+ memGate: heartbeatMemGate(lastMemGate),
1245
1567
  // State/consecutiveFailures/degraded-budget snapshot of the shared
1246
1568
  // usage-meter breaker, so a human reading only the heartbeat log can
1247
1569
  // see the meter's own health apart from the queue's.
@@ -1249,6 +1571,9 @@ function heartbeatTick(deps = {}) {
1249
1571
  state: billing.usageCircuit.state(),
1250
1572
  consecutiveFailures,
1251
1573
  degradedBudget: computeDegradedBudget(),
1574
+ // The cap tickQueue actually applies (degradedBudget above is a
1575
+ // display recompute); null = the full slot pool.
1576
+ appliedConcurrencyCap: degradedConcurrencyCapValue,
1252
1577
  },
1253
1578
  };
1254
1579
  });
@@ -1259,6 +1584,11 @@ function heartbeatTick(deps = {}) {
1259
1584
  entry = { ts: Date.now(), pid: process.pid, build: heartbeatBuild(), degraded: true, errors };
1260
1585
  }
1261
1586
  appendHeartbeat(entry);
1587
+ // Deliver held scheduler turns once the hold has cleared (no-op while held).
1588
+ guard('held-scheduler-turns-drain', () => {
1589
+ const run = deps.drainHeldSchedulerTurns ?? drainHeldSchedulerTurns;
1590
+ Promise.resolve(run()).catch(() => {});
1591
+ });
1262
1592
  return entry;
1263
1593
  }
1264
1594
 
@@ -1382,9 +1712,15 @@ function normalizeConfig(cfg) {
1382
1712
  return cfg;
1383
1713
  }
1384
1714
 
1715
+ // Last config object a queue read produced — the same object tickBody hands
1716
+ // currentAutoDispatchHold (state.config). The held-turns store's hold provider
1717
+ // reads it synchronously; undefined before the first read (DEFAULT_CONFIG applies).
1718
+ let lastSeenConfig;
1719
+
1385
1720
  function readQueueSync() {
1386
1721
  const s = queueStore.readMergedSync();
1387
1722
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1723
+ lastSeenConfig = s.config;
1388
1724
  return flagUnreadable(s);
1389
1725
  }
1390
1726
 
@@ -1394,6 +1730,7 @@ function readQueueSync() {
1394
1730
  async function readQueue() {
1395
1731
  const s = await queueStore.readMerged();
1396
1732
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1733
+ lastSeenConfig = s.config;
1397
1734
  return flagUnreadable(s);
1398
1735
  }
1399
1736
 
@@ -1520,15 +1857,15 @@ async function mutateBody(fn) {
1520
1857
  const parsePrdRaw = prdParser.parsePrdRaw;
1521
1858
  const parsePrd = prdParser.parsePrd;
1522
1859
  // Aggregates every candidate PRD dir's files into one flat, sorted list.
1523
- // prdParser's dir-mtime cache is keyed per-dir internally by its own single
1524
- // mtime var, so scanning N dirs here costs N stat+readdir passes rather than
1525
- // one — acceptable: PRD counts per project are bounded (hundreds, not
1526
- // millions), and correctness across multiple project dirs matters more than
1527
- // preserving the single-dir cache's steady-state zero-read fast path.
1860
+ // prdParser caches each dir's listing by its path (validated by that dir's
1861
+ // mtime), so a steady-state pass over N unchanged dirs costs N stats and no
1862
+ // readdir, and two dirs sharing an mtime never see each other's files.
1528
1863
  async function listPrdFiles(skipCwds) {
1529
1864
  ensureDirs();
1530
1865
  const dirs = prdPaths.candidatePrdsDirs();
1531
1866
  const perDir = await Promise.all(dirs.map((dir) => prdParser.listPrdFiles(dir)));
1867
+ // Forget cached folders this pass no longer scans (e.g. a removed Epic's prds/).
1868
+ prdParser.retainPrdDirs(dirs);
1532
1869
  let files = perDir.flat();
1533
1870
  // A quarantined project has no job rows this pass; scanning its PRDs would
1534
1871
  // mint fresh `pending` rows for work that may already be running.
@@ -1544,28 +1881,6 @@ function quarantinedCwdSet(state) {
1544
1881
  return new Set((state?.unreadableCwds ?? []).map((u) => u.cwd));
1545
1882
  }
1546
1883
 
1547
- /**
1548
- * Best-effort epic_state_changed emission for the tick (lib/epic/epicStateWatcher.cjs).
1549
- * Watches every known project cwd except quarantined shards. Never rejects:
1550
- * any failure is logged as a warning so it can never hold up dispatch.
1551
- * SM_EPIC_STATE_WATCH_DISABLE=1 turns it off. `deps` is a test seam.
1552
- * @param {any} state
1553
- * @param {{ watch?: (o: { cwds: string[], jobs: any }) => Promise<unknown>, listCwds?: () => string[] }} [deps]
1554
- * @returns {Promise<void>}
1555
- */
1556
- async function runEpicStateWatchForTick(state, deps = {}) {
1557
- if (process.env.SM_EPIC_STATE_WATCH_DISABLE === '1') return;
1558
- try {
1559
- const watch = deps.watch ?? require('./lib/epic/epicStateWatcher.cjs').runEpicStateWatch;
1560
- const listCwds = deps.listCwds ?? allProjectCwds;
1561
- const quarantined = quarantinedCwdSet(state);
1562
- const cwds = listCwds().filter((c) => !quarantined.has(c));
1563
- await watch({ cwds, jobs: state?.jobs });
1564
- } catch (e) {
1565
- console.warn('[scheduler] epic state watch failed', /** @type {any} */ (e)?.message);
1566
- }
1567
- }
1568
-
1569
1884
  /**
1570
1885
  * Atomically mint a brand-new parallel-group NN for a PRD about to be
1571
1886
  * authored under the given project's own PRDs dir (falls back to
@@ -1817,7 +2132,7 @@ async function reconcilePass(state) {
1817
2132
  try { roots.add(resolveProjectRoot(c)); } catch { /* ephemeral/invalid cwd */ }
1818
2133
  }
1819
2134
  for (const r of roots) {
1820
- try { ensureRuntimeIgnores(r); } catch { /* best-effort */ }
2135
+ try { ensureRuntimeIgnores(r); } catch (e) { console.warn('[scheduler] runtime self-ignore failed for', r, e && e.message); }
1821
2136
  }
1822
2137
  } catch { /* best-effort */ }
1823
2138
  phaseMs.flatPrdSweep = Date.now() - phaseStartMs;
@@ -1971,6 +2286,7 @@ async function reconcilePass(state) {
1971
2286
  deliverable: p.deliverable ?? job.deliverable ?? null,
1972
2287
  artifactPaths: p.artifactPaths ?? job.artifactPaths ?? null,
1973
2288
  effort: p.effort ?? job.effort ?? null,
2289
+ voiceId: p.voiceId ?? job.voiceId ?? null,
1974
2290
  preflight: p.preflight ?? null,
1975
2291
  };
1976
2292
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
@@ -2099,6 +2415,7 @@ async function reconcilePass(state) {
2099
2415
  deliverable: p.deliverable ?? inv.row?.deliverable ?? null,
2100
2416
  artifactPaths: p.artifactPaths ?? inv.row?.artifactPaths ?? null,
2101
2417
  effort: p.effort ?? inv.row?.effort ?? null,
2418
+ voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2102
2419
  preflight: p.preflight ?? null,
2103
2420
  };
2104
2421
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
@@ -2255,6 +2572,7 @@ async function reconcilePass(state) {
2255
2572
  deliverable: p.deliverable ?? null,
2256
2573
  artifactPaths: p.artifactPaths ?? null,
2257
2574
  effort: p.effort ?? null,
2575
+ voiceId: p.voiceId ?? null,
2258
2576
  preflight: p.preflight ?? null,
2259
2577
  status: 'pending',
2260
2578
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
@@ -2344,6 +2662,9 @@ async function reconcilePass(state) {
2344
2662
  }
2345
2663
  } catch { /* stat is best-effort reporting only */ }
2346
2664
  next.push(entry);
2665
+ // The Epic's event log records every queue-row insert (summary only);
2666
+ // fire-and-forget — a failed append is logged, never blocks reconcile.
2667
+ emitJobEvent(entry, { kind: 'job.queued', slug, agentType: entry.agentType ?? null });
2347
2668
  }
2348
2669
  if (uncovered.size > 0) {
2349
2670
  queueStore.bustCwdCache();
@@ -2427,9 +2748,25 @@ async function reconcilePass(state) {
2427
2748
  let cachedNextReset = null; // bare ISO string or null
2428
2749
  let cachedUtilization = null; // binding-window utilization %, 0–100, or null if unknown
2429
2750
  let cachedBindingWindowName = null; // name/kind of the window cachedUtilization reads (e.g. 'five_hour', 'weekly_all')
2430
- // Non-null while maybeLaunchWhenAvailable is holding the queue on the
2431
- // utilization gate: { window, percent, threshold, resetsAt }. Snapshot-level.
2751
+ // true when cachedUtilization is a real reading (poll, fresh/stale meter cache,
2752
+ // no-meter 0, restored number); false for the 100% "no reading ever" placeholder.
2753
+ let cachedUtilizationKnown = false;
2754
+ // Window list restored from scheduler-state.json — read by utilizationReading()
2755
+ // only while no payload is held (after a restart). Never updated per poll.
2756
+ let restoredUsageWindows = null;
2757
+ // Non-null while tickBody is holding automatic dispatch on the utilization
2758
+ // rule (autoDispatchHold): { window, percent, threshold, resetsAt }. Snapshot-level.
2432
2759
  let utilizationHold = null;
2760
+ // `${reason}|${window}|${percent}` of the hold last logged — the hold line is
2761
+ // written when the hold starts or changes, not on every 30 s tick.
2762
+ let lastAutoDispatchHoldKey = null;
2763
+ // The auto-dispatch hold currently open in audit-log.jsonl (one
2764
+ // auto_dispatch_hold_started written, its _ended not yet): { holdKey, reason,
2765
+ // window, threshold, resetsAt, startedAt, maxPercent, heldTicks, restored? },
2766
+ // keyed by utilizationHold.holdIdentityKey so percent changes and reset jitter
2767
+ // write nothing. Persisted in scheduler-state.json so a restart neither
2768
+ // re-opens nor loses it (the heartbeat log keeps only ~18-37 h).
2769
+ let openAutoDispatchHold = null;
2433
2770
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2434
2771
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2435
2772
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -2487,14 +2824,115 @@ function computeDegradedBudget() {
2487
2824
  */
2488
2825
  function applyDegradedBudget() {
2489
2826
  const budget = computeDegradedBudget();
2490
- cachedUtilization = budget.utilization;
2491
- cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2827
+ if (lastGoodUsagePayload) {
2828
+ cachedUtilization = budget.utilization;
2829
+ cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2830
+ cachedUtilizationKnown = true;
2831
+ } else if (!(cachedUtilizationKnown && Number.isFinite(cachedUtilization))) {
2832
+ // No payload and no real reading ever: the conservative placeholder.
2833
+ cachedUtilization = budget.utilization;
2834
+ cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2835
+ cachedUtilizationKnown = false;
2836
+ }
2837
+ // else: no payload held (e.g. after a restart) but a known reading was
2838
+ // restored — keep it rather than replacing it with the 100 placeholder.
2492
2839
  degradedConcurrencyCapValue = budget.concurrencyCap;
2493
2840
  return budget;
2494
2841
  }
2495
2842
 
2496
- /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2497
- async function refreshNextReset() {
2843
+ /**
2844
+ * The current utilization reading and its provenance. `windows` is derived on
2845
+ * each call: every unscoped window of the held payload, else the list
2846
+ * restored from scheduler-state.json, else null.
2847
+ */
2848
+ /**
2849
+ * The auto-dispatch hold in force right now for `config` (or DEFAULT_CONFIG's
2850
+ * values where config omits them), read over every window of the last real
2851
+ * reading. null = automatic ticks may dispatch.
2852
+ */
2853
+ function currentAutoDispatchHold(config) {
2854
+ const cfg = config || {};
2855
+ return autoDispatchHold.evaluateAutoDispatchHold({
2856
+ firePolicy: cfg.firePolicy ?? DEFAULT_CONFIG.firePolicy,
2857
+ threshold: cfg.utilizationThreshold ?? DEFAULT_CONFIG.utilizationThreshold,
2858
+ reading: utilizationReading(),
2859
+ now: Date.now(),
2860
+ });
2861
+ }
2862
+
2863
+ /**
2864
+ * The saved 'pause above' threshold (config.utilizationThreshold), read from
2865
+ * the machine-runtime scheduler state file only — never every project's queue
2866
+ * shard — so timers and routes can call it cheaply. DEFAULT_CONFIG's value
2867
+ * when unset, non-finite or unreadable.
2868
+ */
2869
+ function usageHoldThreshold() {
2870
+ try {
2871
+ const t = queueStore.readMachineConfigSync().utilizationThreshold;
2872
+ return typeof t === 'number' && Number.isFinite(t) ? t : DEFAULT_CONFIG.utilizationThreshold;
2873
+ } catch {
2874
+ return DEFAULT_CONFIG.utilizationThreshold;
2875
+ }
2876
+ }
2877
+
2878
+ /**
2879
+ * The usage hold in force right now for claude -p runs started OUTSIDE the PRD
2880
+ * queue: Tasks (POST /admin/tasks), their timers, and outside readers. Applies
2881
+ * the same utilization rule as currentAutoDispatchHold over the last real
2882
+ * reading at usageHoldThreshold(), but never firePolicy — firePolicy is the PRD
2883
+ * queue's own setting. null, or { reason: 'utilization-held', window, percent,
2884
+ * threshold, resetsAt, detail }; never 'manual-fire-policy'.
2885
+ */
2886
+ function currentUsageHold() {
2887
+ return autoDispatchHold.evaluateAutoDispatchHold({
2888
+ firePolicy: null,
2889
+ threshold: usageHoldThreshold(),
2890
+ reading: utilizationReading(),
2891
+ now: Date.now(),
2892
+ });
2893
+ }
2894
+
2895
+ /**
2896
+ * The auto-fix investigation probe is an automatic `claude -p` too, but it is
2897
+ * launched from spawnJob's failure path and the periodic auto-fix pass, never
2898
+ * through tickBody — so it checks the same hold itself. Returns the hold (and
2899
+ * appends one 'investigation_held' audit event per row per hold) or null.
2900
+ * A deferral stamps nothing on the row: it stays eligible for the periodic
2901
+ * auto-fix pass (selectAutoFixTargets), which launches it once the hold clears.
2902
+ */
2903
+ function investigationHold(slug, config) {
2904
+ const hold = currentAutoDispatchHold(config);
2905
+ if (!hold) {
2906
+ // No hold: the row launches now, so a later hold audits it once again.
2907
+ investigationHeldKeys.delete(slug);
2908
+ return null;
2909
+ }
2910
+ if (noteHeldOnce(investigationHeldKeys, slug, hold)) {
2911
+ console.log(`[scheduler] investigation held for ${slug}: ${hold.reason} — ${hold.detail ?? ''}`);
2912
+ appendAuditEvent('investigation_held', { slug, reason: hold.reason });
2913
+ }
2914
+ return hold;
2915
+ }
2916
+
2917
+ function utilizationReading() {
2918
+ const windows = lastGoodUsagePayload
2919
+ ? usageWindows(lastGoodUsagePayload).map((w) => ({ window: w.name, percent: w.utilization, resetsAt: w.resets_at }))
2920
+ : restoredUsageWindows;
2921
+ return {
2922
+ percent: cachedUtilization,
2923
+ window: cachedBindingWindowName,
2924
+ resetsAt: cachedNextReset,
2925
+ known: cachedUtilizationKnown,
2926
+ windows,
2927
+ };
2928
+ }
2929
+
2930
+ /**
2931
+ * Fetches latest usage from billing API and returns its binding window as one
2932
+ * paired reading ({ window, resetsAt }). Throws on any error — callers handle it.
2933
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
2934
+ */
2935
+ async function refreshBindingReading() {
2498
2936
  const r = await billing.fetchUsage();
2499
2937
  if (r.kind !== 'ok') throw new Error(`usage fetch failed (${r.kind}): ${r.message ?? ''}`);
2500
2938
  const window = bindingWindow(r.data?.usage);
@@ -2506,8 +2944,14 @@ async function refreshNextReset() {
2506
2944
  recordObservedReset(window.resets_at ?? null);
2507
2945
  cachedUtilization = window.utilization;
2508
2946
  cachedBindingWindowName = window.name;
2947
+ cachedUtilizationKnown = true;
2509
2948
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
2510
- return cachedNextReset;
2949
+ return { window: window.name ?? null, resetsAt: cachedNextReset };
2950
+ }
2951
+
2952
+ /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2953
+ async function refreshNextReset() {
2954
+ return (await refreshBindingReading()).resetsAt;
2511
2955
  }
2512
2956
 
2513
2957
  /**
@@ -2542,6 +2986,41 @@ function resolveRateLimitPauseReset(logPath, billingResetIso, nowMs = Date.now()
2542
2986
  return null;
2543
2987
  }
2544
2988
 
2989
+ /**
2990
+ * The 'pause above' a rate_limit pause compares the billing binding window
2991
+ * with: the same pro-rated threshold the auto-dispatch hold uses
2992
+ * (utilizationHold.proRatedThreshold) for THAT window and its reset, so a
2993
+ * weekly window in its last days is not read as over a flat cap the hold
2994
+ * itself has already raised. Window name and reset come from the SAME
2995
+ * reading (the caller's refreshed billing reading) — pairing a cached name
2996
+ * with a fresh reset pro-rates against the wrong window length. The cached
2997
+ * pair is used only when no reading is passed. Non-numeric base passes
2998
+ * through unchanged.
2999
+ * @param {unknown} base
3000
+ * @param {{ window?: string | null, resetsAt?: string | null } | null | undefined} reading
3001
+ * @param {number} nowMs
3002
+ */
3003
+ function bindingWindowPauseThreshold(base, reading, nowMs) {
3004
+ if (typeof base !== 'number' || !Number.isFinite(base)) return base;
3005
+ const pair = reading ?? { window: cachedBindingWindowName, resetsAt: cachedNextReset };
3006
+ return autoDispatchHold.proRatedThreshold({ base, window: pair.window ?? null, resetsAt: pair.resetsAt ?? null, now: nowMs });
3007
+ }
3008
+
3009
+ /**
3010
+ * Effective 'pause above' for the binding window of the last known reading
3011
+ * (renderer snapshot field effectiveUtilizationThreshold); null with no known
3012
+ * reading or no numeric base.
3013
+ * @param {unknown} base
3014
+ * @param {number} [nowMs]
3015
+ * @returns {number | null}
3016
+ */
3017
+ function effectiveUtilizationThreshold(base, nowMs = Date.now()) {
3018
+ if (typeof base !== 'number' || !Number.isFinite(base)) return null;
3019
+ const reading = utilizationReading();
3020
+ if (reading.known !== true || typeof reading.percent !== 'number' || !Number.isFinite(reading.percent)) return null;
3021
+ return autoDispatchHold.proRatedThreshold({ base, window: reading.window, resetsAt: reading.resetsAt, now: nowMs });
3022
+ }
3023
+
2545
3024
  /** Logs when a fresh billing reset was discarded because its reading is under threshold. */
2546
3025
  function logBillingResetRejected(billingResetIso, billingUtilization, threshold) {
2547
3026
  if (!billingResetIso || !Number.isFinite(threshold)) return;
@@ -2559,8 +3038,19 @@ function logBillingResetRejected(billingResetIso, billingUtilization, threshold)
2559
3038
  * itself still rejects that cached value if it has since gone stale).
2560
3039
  */
2561
3040
  async function billingResetForPause() {
2562
- if (billing.usageCircuit.state() === 'open') return cachedNextReset;
2563
- return refreshNextReset().catch(() => cachedNextReset);
3041
+ return (await billingReadingForPause()).resetsAt;
3042
+ }
3043
+
3044
+ /**
3045
+ * billingResetForPause's reading with its binding window name kept beside the
3046
+ * reset ({ window, resetsAt }), so both come from one reading — the refreshed
3047
+ * one, or the cached pair when the circuit is open or the refresh fails.
3048
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
3049
+ */
3050
+ async function billingReadingForPause() {
3051
+ const cached = () => ({ window: cachedBindingWindowName ?? null, resetsAt: cachedNextReset });
3052
+ if (billing.usageCircuit.state() === 'open') return cached();
3053
+ return refreshBindingReading().catch(cached);
2564
3054
  }
2565
3055
 
2566
3056
  // ---------- health / poll state ----------
@@ -2773,6 +3263,40 @@ function drainDeferredInvestigation() {
2773
3263
  return;
2774
3264
  }
2775
3265
  }
3266
+
3267
+ /**
3268
+ * drainHeldSchedulerTurns(deps?) → Promise<Array<{ tabId, delivered, dropped }>>
3269
+ *
3270
+ * Deliver the scheduler chat turns the usage hold kept (heldSchedulerTurns.cjs)
3271
+ * once no hold is in force — each tab's held messages as one turn. An
3272
+ * auto-start follow-up is dropped when its session no longer needs a plan.
3273
+ * Every tab the drain touched is audited. Single-flight lives in the store.
3274
+ * Never rejects. Deps are injectable for tests.
3275
+ */
3276
+ async function drainHeldSchedulerTurns(deps = {}) {
3277
+ const hold = deps.hold ?? (() => currentAutoDispatchHold(lastSeenConfig));
3278
+ const send = deps.send ?? enqueueExternalPrompt;
3279
+ const needsPlan = deps.needsPlan ?? autoStartedSession.autoStartNeedsPlan;
3280
+ const audit = deps.audit ?? appendAuditEvent;
3281
+ try {
3282
+ if (hold()) return [];
3283
+ if (heldSchedulerTurns.summary().count <= 0) return [];
3284
+ const isStillNeeded = (entry) => (entry && entry.kind === 'auto-start-follow-up'
3285
+ ? needsPlan(entry.cwd, entry.sessionId)
3286
+ : true);
3287
+ const results = await heldSchedulerTurns.drain({ send, isStillNeeded });
3288
+ for (const r of results || []) {
3289
+ try {
3290
+ audit('scheduler_turns_delivered', { tabId: r.tabId, delivered: r.delivered, dropped: r.dropped });
3291
+ } catch { /* audit must not break the drain */ }
3292
+ }
3293
+ return results || [];
3294
+ } catch (e) {
3295
+ console.error('[scheduler] drainHeldSchedulerTurns error', e?.message ?? e);
3296
+ return [];
3297
+ }
3298
+ }
3299
+
2776
3300
  let cancelToken = { cancelled: false };
2777
3301
  // Last memory-gate observation; included in snapshot for renderer visibility.
2778
3302
  let lastMemGate = null;
@@ -2784,6 +3308,10 @@ function _setLoadGateForTests(gate) { loadGate = gate; }
2784
3308
  // without forking a real child job (whose completion tick races the next test).
2785
3309
  let dispatchSpawnJob = (...args) => spawnJob(...args);
2786
3310
  function _setSpawnJobForTests(fn) { dispatchSpawnJob = fn || ((...args) => spawnJob(...args)); }
3311
+ // The periodic auto-fix pass launches investigations through this indirection
3312
+ // so a test can record them without forking a real probe child.
3313
+ let dispatchSpawnInvestigation = (...args) => spawnInvestigation(...args);
3314
+ function _setSpawnInvestigationForTests(fn) { dispatchSpawnInvestigation = fn || ((...args) => spawnInvestigation(...args)); }
2787
3315
 
2788
3316
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2789
3317
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2839,26 +3367,15 @@ function applyPauseCleared(wasPaused, token) {
2839
3367
  return token;
2840
3368
  }
2841
3369
 
2842
- /**
2843
- * Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
2844
- * to the renderer via lastTick.detail. Names the gate, the measured ratio,
2845
- * the threshold and how long this gate itself has held a batch that slots and
2846
- * memory admitted (heldMs). Pure so it's unit-testable without driving tickQueue's full
2847
- * fs/worktree machinery.
2848
- */
2849
- function formatLoadGateDetail(load) {
2850
- const heldMinutes = Math.round(load.heldMs / 60_000);
2851
- const cpu = load.cpuBusy == null
2852
- ? 'no CPU sample yet'
2853
- : `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
2854
- return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
2855
- }
3370
+ // formatLoadGateDetail (the load-deferred tick's lastTick.detail) lives in
3371
+ // lib/scheduler/loadGate.cjs beside the fields it reads.
2856
3372
 
2857
3373
  function loadGateAuditFields(load) {
2858
3374
  return {
2859
3375
  loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2860
- // cpuBusy is the decision value: net of the app's own process tree (PRD 3495).
3376
+ // cpuBusy is the decision value: net of the app's own process tree (PRD 3495) and nice-19 processes (PRD 4021).
2861
3377
  cpuBusy: load.cpuBusy, cpuBusyRaw: load.cpuBusyRaw, cpuBusyNet: load.cpuBusyNet, cpuOwnBusy: load.cpuOwnBusy,
3378
+ cpuIdleNice: load.cpuIdleNice,
2862
3379
  cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2863
3380
  };
2864
3381
  }
@@ -2878,7 +3395,12 @@ function attachWindow(w) { mainWindow = w; }
2878
3395
  function buildScheduleStatePayload(state) {
2879
3396
  const payload = {
2880
3397
  config: state.config,
2881
- jobs: state.jobs,
3398
+ // Cancelled rows ship as shallow copies marked `cancelled: true` (the one
3399
+ // rule in lib/scheduler/cancelledRow.cjs) so the renderer never re-derives
3400
+ // it. Copies only — the live rows (and so queue.json) never carry the key.
3401
+ jobs: Array.isArray(state.jobs)
3402
+ ? state.jobs.map((j) => (isCancelledRow(j) ? { ...j, cancelled: true } : j))
3403
+ : state.jobs,
2882
3404
  lastRunAt: state.lastRunAt,
2883
3405
  // Distinct from lastRunAt (only stamped when a batch actually launches):
2884
3406
  // stamped every time tickQueue reaches the picker at all. See
@@ -2895,6 +3417,8 @@ function buildScheduleStatePayload(state) {
2895
3417
  utilization: cachedUtilization,
2896
3418
  utilizationWindow: cachedBindingWindowName,
2897
3419
  utilizationHold,
3420
+ // Pro-rated 'pause above' for the binding window (utilizationHold.proRatedThreshold).
3421
+ effectiveUtilizationThreshold: effectiveUtilizationThreshold(state.config?.utilizationThreshold),
2898
3422
  pollHealth: {
2899
3423
  lastPollAt,
2900
3424
  lastPollOk,
@@ -3216,14 +3740,17 @@ function resetJobFields(job, errorMsg, opts = {}) {
3216
3740
  if ((job.status === 'completed' || job.status === 'skipped') && opts.force !== true) return false;
3217
3741
  // Durable cancel (2026-10-19 git-viewer incident): a human-cancelled row is
3218
3742
  // revived only by an explicit human reset, never by an automated pass.
3219
- if (reviewLadder.isCancelledJob(job) && opts.source !== 'remote:resetJob' && opts.source !== 'ipc:schedule:reset-job') return false;
3743
+ if (isCancelledRow(job) && opts.source !== 'remote:resetJob' && opts.source !== 'ipc:schedule:reset-job') return false;
3220
3744
  // Reset means "re-check the precondition now": the hold is dropped even
3221
3745
  // when the row is already pending (pending→pending is not a transition).
3222
3746
  delete job.preflightHold;
3223
3747
  if (job.status === 'pending' && typeof job.heldReason === 'string' && job.heldReason.startsWith('waiting on precondition:')) delete job.heldReason;
3748
+ if (job.interrupted && typeof job.heldReason === 'string' && job.heldReason.startsWith('interrupted by a human')) delete job.heldReason;
3224
3749
  if (!transitionJob(job, 'pending', { reason: errorMsg ?? 'reset to pending', source: opts.source ?? 'resetJobFields' })) return false;
3225
3750
  delete job.cancelledAt;
3226
3751
  delete job.cancelledRunId;
3752
+ // A reset restarts from scratch: an interrupted session is not resumed.
3753
+ delete job.interrupted;
3227
3754
  job.runId = null;
3228
3755
  job.startedAt = null;
3229
3756
  job.finishedAt = null;
@@ -3499,6 +4026,31 @@ function applyOrphanOutcomeInner(job, outcome, killNote, confirmedLandedCommit,
3499
4026
  }
3500
4027
  }
3501
4028
 
4029
+ /**
4030
+ * Write the structured outcome record for a just-finalized job and append its
4031
+ * outcome.recorded Epic event (lib/scheduler/prdOutcomeRecord.cjs). Commits =
4032
+ * the landed commit plus any stranded worktree commits; files = the union of
4033
+ * files those commits touch. No Epic id → nothing to record. Never throws.
4034
+ * @param {any} row the finalized job row snapshot
4035
+ * @param {{ verifyResult?: any, landedCommit?: string|null, strandedCommits?: string[], fallbackCwd?: string }} run
4036
+ */
4037
+ async function writeJobOutcomeRecord(row, { verifyResult = null, landedCommit = null, strandedCommits = [], fallbackCwd = DEFAULT_PROJECT_CWD } = {}) {
4038
+ const epicId = row && (row.epicId || row.sourcePromptId);
4039
+ if (!epicId) return;
4040
+ try {
4041
+ const cwd = row.cwd || fallbackCwd;
4042
+ const commits = [...new Set([landedCommit, ...strandedCommits].filter((x) => typeof x === 'string' && x))];
4043
+ const files = await prdOutcomeRecord.listCommitFiles(cwd, commits);
4044
+ const built = prdOutcomeRecord.buildOutcomeFromJob({ job: row, verifyResult, commits, files });
4045
+ await prdOutcomeRecord.writeOutcomeRecord({
4046
+ cwd, epicId, slug: row.slug, ...built,
4047
+ extra: { runId: row.runId ?? null, exitCode: row.exitCode ?? null, terminalReason: row.terminalReason ?? null, finishedAt: row.finishedAt ?? null },
4048
+ });
4049
+ } catch (e) {
4050
+ console.error('[scheduler] outcome record write failed', row && row.slug, e && e.message ? e.message : e);
4051
+ }
4052
+ }
4053
+
3502
4054
  /**
3503
4055
  * isNotifiableTerminalStatus(effectiveStatus) → boolean
3504
4056
  *
@@ -3685,6 +4237,117 @@ async function resolveValidatorEstimate(job, { readGateMs = readValidatorGateMs
3685
4237
  }
3686
4238
  }
3687
4239
 
4240
+ /**
4241
+ * Stored mechanical check results of one judged PRD: the `checks` of its
4242
+ * outcome record (prdOutcomeRecord.cjs), exact slug first, then a bare-slug
4243
+ * match in the Epic's outcomes/ folder. [] when none. Never rejects.
4244
+ */
4245
+ async function readStoredCriteriaChecks(cwd, epicId, slug) {
4246
+ try {
4247
+ const exact = await readJsonOr(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug), null);
4248
+ if (exact && Array.isArray(exact.checks)) return exact.checks;
4249
+ const dir = path.dirname(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug));
4250
+ const want = bareSlug(slug);
4251
+ const names = (await fsp.readdir(dir).catch(() => [])).filter((n) => n.endsWith('.json')).sort().reverse();
4252
+ for (const n of names) {
4253
+ const s = n.slice(0, -'.json'.length);
4254
+ if (s === slug || bareSlug(s) !== want) continue;
4255
+ const rec = await readJsonOr(path.join(dir, n), null);
4256
+ if (rec && Array.isArray(rec.checks)) return rec.checks;
4257
+ }
4258
+ } catch { /* unsafe id / unreadable → no stored checks */ }
4259
+ return [];
4260
+ }
4261
+
4262
+ /**
4263
+ * runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry }?) → merged checks.
4264
+ * Runs the PRD's http + file criteria fresh in `cwd` (outside the job
4265
+ * sandbox, whose Bash cannot reach host loopback), never command or manual
4266
+ * ones. A failed http check is retried (default HTTP_RETRY_ATTEMPTS,
4267
+ * HTTP_RETRY_DELAY_MS apart; `httpRetry` overrides, tests only) because a
4268
+ * local dev server may be mid-reload just after a landing; each http row
4269
+ * keeps its `attempts`. http bodies go to a sidecar file (writeCheckBody); the row keeps
4270
+ * only bodyPath/bodyBytes/truncated. Fresh rows replace stored ones by id;
4271
+ * the exact-slug outcome record (when one exists) is updated in place.
4272
+ * Falls back to `stored` on any error. Never rejects.
4273
+ */
4274
+ async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry } = {}) {
4275
+ try {
4276
+ const subset = criteria.filter((c) => c && c.check && (c.check.kind === 'http' || c.check.kind === 'file'));
4277
+ if (!subset.length) return stored;
4278
+ const ranAt = new Date().toISOString();
4279
+ const rows = await runCriteriaChecks({
4280
+ criteria: subset,
4281
+ cwd,
4282
+ keepBody: true,
4283
+ httpRetry: httpRetry || { attempts: HTTP_RETRY_ATTEMPTS, delayMs: HTTP_RETRY_DELAY_MS },
4284
+ });
4285
+ const fresh = [];
4286
+ for (const r of rows) {
4287
+ const { body, ...rest } = r;
4288
+ /** @type {Record<string, unknown>} */
4289
+ const row = { ...rest, ranAt, stage: 'validator-dispatch' };
4290
+ if (typeof body === 'string') {
4291
+ const bodyPath = await prdOutcomeRecord.writeCheckBody({ cwd, epicId, slug, id: r.id, body });
4292
+ if (bodyPath) row.bodyPath = bodyPath;
4293
+ }
4294
+ fresh.push(row);
4295
+ }
4296
+ const freshIds = new Set(fresh.map((c) => c.id));
4297
+ const merged = [...(Array.isArray(stored) ? stored : []).filter((c) => !(c && freshIds.has(c.id))), ...fresh];
4298
+ let exactExists = false;
4299
+ try { exactExists = !!(await readJsonOr(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug), null)); } catch { exactExists = false; }
4300
+ if (exactExists) await prdOutcomeRecord.mergeOutcomeChecks({ cwd, epicId, slug, checks: fresh });
4301
+ return merged;
4302
+ } catch (e) {
4303
+ console.error('[scheduler] runDispatchCriteriaChecks error', slug, e && e.message ? e.message : e);
4304
+ return stored;
4305
+ }
4306
+ }
4307
+
4308
+ /**
4309
+ * loadValidatorCriteriaContext(job) → { expected, section } for a validator
4310
+ * job: per judged PRD (job.dependsOn) with frontmatter `criteria`, the
4311
+ * { ids, failedIds } parseValidatorVerdict cross-checks against, and the
4312
+ * prompt section listing each criterion's check result — http + file checks
4313
+ * run fresh here at dispatch (runDispatchCriteriaChecks), command results as
4314
+ * stored. Empty when
4315
+ * nothing is structured. Never rejects. With `runChecks: false` (the notify
4316
+ * fallback for a row without a dispatch-time stamp) it reads the stored
4317
+ * checks only: no http request, no outcome record or body file write.
4318
+ * `httpRetry` overrides the dispatch retry defaults (tests only).
4319
+ * @param {any} job
4320
+ * @param {{ runChecks?: boolean, httpRetry?: { attempts?: number, delayMs?: number } }} [opts]
4321
+ * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
4322
+ */
4323
+ async function loadValidatorCriteriaContext(job, { runChecks = true, httpRetry } = {}) {
4324
+ /** @type {Record<string, { ids: string[], failedIds: string[] }>} */
4325
+ const expected = {};
4326
+ try {
4327
+ if (!job || job.agentType !== 'validator' || !Array.isArray(job.dependsOn) || !job.dependsOn.length) return { expected, section: '' };
4328
+ const epicId = job.epicId || job.sourcePromptId;
4329
+ if (!job.cwd || !isSafeEpicId(epicId)) return { expected, section: '' };
4330
+ const texts = await prdPaths.readEpicPrdTexts(job.cwd, epicId, job.dependsOn);
4331
+ const prds = [];
4332
+ for (const slug of job.dependsOn) {
4333
+ const text = texts.get(slug);
4334
+ if (typeof text !== 'string') continue;
4335
+ let criteria = null;
4336
+ try { criteria = parsePrdFile(text).frontmatter.criteria; } catch { criteria = null; }
4337
+ if (!Array.isArray(criteria) || !criteria.length) continue;
4338
+ const stored = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4339
+ const checks = runChecks ? await runDispatchCriteriaChecks(job.cwd, epicId, slug, criteria, stored, { httpRetry }) : stored;
4340
+ const exp = expectedFromCriteria(criteria, checks);
4341
+ if (exp) expected[slug] = exp;
4342
+ prds.push({ slug, criteria, checks });
4343
+ }
4344
+ return { expected, section: formatCriteriaChecksSection(prds) };
4345
+ } catch (e) {
4346
+ console.error('[scheduler] loadValidatorCriteriaContext error', job && job.slug, e && e.message ? e.message : e);
4347
+ return { expected, section: '' };
4348
+ }
4349
+ }
4350
+
3688
4351
  function defaultScheduleSettle({ cwd, epicId }) {
3689
4352
  const deps = {
3690
4353
  loadJobs: async () => (await readQueue()).jobs || [],
@@ -3701,7 +4364,7 @@ function defaultScheduleSettle({ cwd, epicId }) {
3701
4364
  },
3702
4365
  readGateMs: readValidatorGateMs,
3703
4366
  jobBudget: { factor: budget.JOB_BUDGET_FACTOR, ceilingMs: budget.JOB_BUDGET_CEILING_MS },
3704
- sendPrompt: (tabId, prompt) => enqueueExternalPrompt(tabId, prompt, { origin: 'scheduler' }),
4367
+ sendPrompt: (tabId, prompt, extra) => enqueueExternalPrompt(tabId, prompt, { ...(extra || {}), origin: 'scheduler' }),
3705
4368
  appendResponseEvent: appendResponseEventIfKnown,
3706
4369
  };
3707
4370
  epicValidationHook.scheduleEpicSettle({ cwd, epicId }, (args) => epicValidationHook.runEpicSettle(args, deps));
@@ -3885,6 +4548,7 @@ async function notifyOriginatingTab(job, {
3885
4548
  readStructuredFromLog = extractStructuredOutputFromLog,
3886
4549
  writeVerdictsFile = writeJsonAtomic,
3887
4550
  scheduleSettle = defaultScheduleSettle,
4551
+ loadValidatorCriteria = loadValidatorCriteriaContext,
3888
4552
  } = {}) {
3889
4553
  try {
3890
4554
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -3979,7 +4643,22 @@ async function notifyOriginatingTab(job, {
3979
4643
  } catch (e) {
3980
4644
  console.error('[scheduler] notifyOriginatingTab readStructuredFromLog error', job?.slug, e);
3981
4645
  }
3982
- const checked = parseValidatorVerdict(structured);
4646
+ // Cross-check per-criterion entries against the judged PRDs' frontmatter
4647
+ // criteria + stored check results: a missing id or met-on-failed-check
4648
+ // refuses the whole verdict.
4649
+ // The dispatch-time stamp (job.validatorCriteriaExpected) is what the
4650
+ // validator was shown; re-running the http/file checks here would judge
4651
+ // it against results it never saw and overwrite the outcome record.
4652
+ let expected = null;
4653
+ try {
4654
+ const stamp = job && job.validatorCriteriaExpected;
4655
+ const isPlain = !!stamp && typeof stamp === 'object' && !Array.isArray(stamp);
4656
+ const ctx = isPlain ? { expected: stamp } : await loadValidatorCriteria(job, { runChecks: false });
4657
+ if (ctx && ctx.expected && Object.keys(ctx.expected).length) expected = ctx.expected;
4658
+ } catch (e) {
4659
+ console.error('[scheduler] notifyOriginatingTab loadValidatorCriteria error', job?.slug, e);
4660
+ }
4661
+ const checked = parseValidatorVerdict(structured, { expected });
3983
4662
  if (checked.ok) {
3984
4663
  checkedVerdict = checked.value;
3985
4664
  verdicts = verdictRowsFromStructured(checked.value);
@@ -4032,14 +4711,19 @@ async function notifyOriginatingTab(job, {
4032
4711
  } else if (epicId && checkedVerdict && job.cwd) {
4033
4712
  // PRD 3614: keep the checked object beside the Markdown plan record.
4034
4713
  try {
4035
- const file = opsPath(job.cwd, 'plan-records', epicId, `${bareSlug(job.slug)}.verdicts.json`);
4036
- assertOpsWrite(file, 'scheduler');
4037
- await writeVerdictsFile(file, {
4038
- validator: job.slug,
4039
- runId: job.runId || null,
4040
- at: new Date().toISOString(),
4041
- schedulerVerdict: checkedVerdict.schedulerVerdict,
4042
- verdicts: checkedVerdict.verdicts,
4714
+ // Writes the file, then appends validator.verdict to the Epic's event log.
4715
+ await saveValidatorVerdicts({
4716
+ cwd: job.cwd,
4717
+ epicId,
4718
+ validateSlug: bareSlug(job.slug),
4719
+ write: writeVerdictsFile,
4720
+ record: {
4721
+ validator: job.slug,
4722
+ runId: job.runId || null,
4723
+ at: new Date().toISOString(),
4724
+ schedulerVerdict: checkedVerdict.schedulerVerdict,
4725
+ verdicts: checkedVerdict.verdicts,
4726
+ },
4043
4727
  });
4044
4728
  } catch (e) {
4045
4729
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
@@ -4096,7 +4780,7 @@ async function notifyOriginatingTab(job, {
4096
4780
  return;
4097
4781
  }
4098
4782
 
4099
- sendPrompt(targetTabId, message, { origin: 'scheduler' });
4783
+ sendPrompt(targetTabId, message, { origin: 'scheduler', heldKind: 'job-notice' });
4100
4784
  } catch (e) {
4101
4785
  console.error('[scheduler] notifyOriginatingTab error', job?.slug, e);
4102
4786
  }
@@ -4646,6 +5330,40 @@ async function requeueForeignWipBlockedJobs(jobs, { getDirtyPaths = gitTreeGuard
4646
5330
  * exact paths recorded on the parked job row so the resumed run can verify
4647
5331
  * them on disk before trusting them, rather than re-deriving them itself.
4648
5332
  */
5333
+ /**
5334
+ * Prompt for a session resumed after the owner approved a tool-risk 'confirm'
5335
+ * request (toolClearance.cjs). The session already holds its PRD; this only
5336
+ * says that ONE exact call (same arguments) is now cleared, once.
5337
+ */
5338
+ function buildConfirmationResumePreamble({ tool, summary }) {
5339
+ const what = summary && summary !== tool ? `${tool}: ${summary}` : tool;
5340
+ return `CONFIRMATION APPROVED: the owner approved the call your previous run in this same session was refused as 'pending confirmation' — \`${what}\`. This is a continuation of that same session, not a new task.
5341
+
5342
+ Run that call again now with EXACTLY the same arguments: it is cleared for ONE use only. A call with any different argument is refused again, and a second use is refused too. Then finish the rest of the work and follow the SCHEDULER FINISH PROTOCOL from your original prompt (verify, commit your own paths, end with the SCHEDULER_VERDICT line).
5343
+ `;
5344
+ }
5345
+
5346
+ /**
5347
+ * Prompt for a session continued after a human interrupt (remote.interruptJob
5348
+ * → remote.continueJob). The session already holds its PRD and everything it
5349
+ * did before the stop; this only says it was paused, not failed.
5350
+ * @param {{ dirtyPaths?: string[], salvagePatch?: string | null, message?: string | null }} args
5351
+ */
5352
+ function buildInterruptContinuePreamble({ dirtyPaths, salvagePatch, message } = {}) {
5353
+ const paths = Array.isArray(dirtyPaths) ? dirtyPaths : [];
5354
+ const pathBlock = paths.length
5355
+ ? `\nThese path(s) were uncommitted when the run stopped:\n${paths.map((p) => `- ${p}`).join('\n')}\n`
5356
+ : '';
5357
+ const salvageLine = salvagePatch
5358
+ ? `A patch of that uncommitted work was saved at: ${salvagePatch} — apply it if any of those paths are missing from the working tree.\n`
5359
+ : '';
5360
+ const note = typeof message === 'string' && message.trim() ? `\nThe owner adds: ${message.trim()}\n` : '';
5361
+ return `CONTINUE AFTER INTERRUPT: the owner stopped your previous run in this same session and has now asked you to continue. This is the same session and the same task, not a new one — do not restart from scratch.
5362
+ ${pathBlock}${salvageLine}${note}
5363
+ Run \`git status\` first and check what is already on disk, then finish the remaining work and follow the SCHEDULER FINISH PROTOCOL from your original prompt (verify, commit your own paths, end with the SCHEDULER_VERDICT line).
5364
+ `;
5365
+ }
5366
+
4649
5367
  function buildResumeRecoveryPreamble({ dirtyPaths, salvagePatch }) {
4650
5368
  const pathList = dirtyPaths.map((p) => `- ${p}`).join('\n');
4651
5369
  const salvageLine = salvagePatch
@@ -5094,7 +5812,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5094
5812
  return out;
5095
5813
  }
5096
5814
 
5097
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5815
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5098
5816
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5099
5817
  let riskArgs = [];
5100
5818
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5107,7 +5825,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5107
5825
  '--model', model,
5108
5826
  ...effortArgs(effort),
5109
5827
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5110
- ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
5828
+ // Always strict: exactly the persona's resolved servers (dispatch already
5829
+ // parked any job whose set names an unknown server — capability_unknown).
5830
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers(), declaredServers: mcpServerNames }).args,
5111
5831
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5112
5832
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5113
5833
  ...riskArgs,
@@ -5200,6 +5920,162 @@ function ensureTimeoutShimOnce() {
5200
5920
  return timeoutShimEnsured;
5201
5921
  }
5202
5922
 
5923
+ /**
5924
+ * Resolve the persona a job spawns as, via its AgentSnapshot.
5925
+ * Stamped row (job.agentSnapshotId) → readAgentSnapshot; null (missing or
5926
+ * tampered) → refusal agent_snapshot_missing. Unstamped → buildAgentSnapshot
5927
+ * (persona refusals pass through unchanged), writeAgentSnapshot, and stamp
5928
+ * job.agentSnapshotId in memory (spawnJob's onPid mutate persists it).
5929
+ * A store write failure is logged and the job spawns unpinned. Never throws.
5930
+ * Declared capabilities (ma-persona-declared-capabilities): an unpinned build
5931
+ * records the RESOLVED set in the snapshot — mcpServers = the persona's
5932
+ * `mcpServers:` plus its tool-named servers, packs = the Epic's packs plus the
5933
+ * persona's `packs:` — and every spawn (pinned or not) loads exactly the
5934
+ * snapshot's set.
5935
+ * @param {any} job
5936
+ * @param {string} cwd
5937
+ * @param {string[]|undefined} packs
5938
+ * @returns {Promise<{ refusal: null|{ code: string, detail: string }, systemPrompt?: string|null, model?: string, tools?: string[]|null, mcpServers?: string[], packs?: string[], personaPath?: string|null, agentSnapshotId?: string|null, pinned?: boolean }>}
5939
+ */
5940
+ async function resolveJobAgentSnapshot(job, cwd, packs) {
5941
+ if (typeof job.agentSnapshotId === 'string' && job.agentSnapshotId) {
5942
+ const snap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
5943
+ if (!snap) {
5944
+ return { refusal: { code: 'agent_snapshot_missing', detail: `pinned agent snapshot ${job.agentSnapshotId} is missing or does not match its id` } };
5945
+ }
5946
+ return {
5947
+ refusal: null,
5948
+ systemPrompt: snap.body || null,
5949
+ model: snap.model || agentModelResolve.FALLBACK_MODEL,
5950
+ tools: Array.isArray(snap.tools) ? snap.tools : null,
5951
+ mcpServers: Array.isArray(snap.mcpServers) ? snap.mcpServers.map(String) : [],
5952
+ packs: Array.isArray(snap.packs) ? snap.packs.map(String) : [],
5953
+ personaPath: null,
5954
+ agentSnapshotId: job.agentSnapshotId,
5955
+ pinned: true,
5956
+ };
5957
+ }
5958
+ let built;
5959
+ try {
5960
+ built = await agentSnapshot.buildAgentSnapshot({ cwd, agentType: job.agentType, packs });
5961
+ } catch (err) {
5962
+ console.error(`[scheduler] agent snapshot build failed for ${job.slug}: ${err?.message ?? err}`);
5963
+ return { refusal: { code: 'persona_invalid', detail: `agent snapshot build failed: ${err?.message ?? err}` } };
5964
+ }
5965
+ if (built.refusal) return { refusal: built.refusal };
5966
+ const declared = readPersonaDeclaredCapabilities(cwd, job.agentType);
5967
+ const resolvedPacks = [];
5968
+ for (const p of [...(Array.isArray(built.snapshot.packs) ? built.snapshot.packs : []), ...declared.packs]) {
5969
+ if (!resolvedPacks.includes(String(p))) resolvedPacks.push(String(p));
5970
+ }
5971
+ const snap = {
5972
+ ...built.snapshot,
5973
+ mcpServers: resolvedMcpServerNames(built.snapshot.tools, [...(built.snapshot.mcpServers || []), ...declared.mcpServers]),
5974
+ packs: resolvedPacks,
5975
+ };
5976
+ let id = null;
5977
+ try {
5978
+ id = (await agentSnapshot.writeAgentSnapshot(cwd, snap)).id;
5979
+ job.agentSnapshotId = id;
5980
+ } catch (err) {
5981
+ console.error(`[scheduler] agent snapshot write failed for ${job.slug} (spawning unpinned): ${err?.message ?? err}`);
5982
+ }
5983
+ return {
5984
+ refusal: null,
5985
+ systemPrompt: snap.body || null,
5986
+ model: snap.model || agentModelResolve.FALLBACK_MODEL,
5987
+ tools: snap.tools,
5988
+ mcpServers: snap.mcpServers,
5989
+ packs: snap.packs,
5990
+ personaPath: null,
5991
+ agentSnapshotId: id,
5992
+ pinned: false,
5993
+ };
5994
+ }
5995
+
5996
+ /**
5997
+ * The persona's declared `mcpServers:` / `packs:` (agentLibrary.cjs's
5998
+ * parseCapabilityList), via the same overlay-aware reader the snapshot uses.
5999
+ * A missing/unreadable persona → both empty (the snapshot build already
6000
+ * refused that case). Never throws.
6001
+ * @param {string} cwd
6002
+ * @param {string|null|undefined} agentType
6003
+ * @returns {{ mcpServers: string[], packs: string[] }}
6004
+ */
6005
+ function readPersonaDeclaredCapabilities(cwd, agentType) {
6006
+ try {
6007
+ const persona = agentModelResolve.readOverlayAwarePersona(agentType || agentModelResolve.DEFAULT_PRD_AGENT_TYPE, { cwd });
6008
+ const fm = (persona && persona.fm) || {};
6009
+ const { parseCapabilityList } = require('./agentLibrary.cjs');
6010
+ return { mcpServers: parseCapabilityList(fm.mcpServers), packs: parseCapabilityList(fm.packs) };
6011
+ } catch {
6012
+ return { mcpServers: [], packs: [] };
6013
+ }
6014
+ }
6015
+
6016
+ /**
6017
+ * The environment profile a job's sandbox is derived from: the persona's
6018
+ * declared `environment:` frontmatter, else jobSandboxPolicy's legacy
6019
+ * persona default (validator → validator-readonly, dev-lead →
6020
+ * headless-default), else null (tool rules). A declared name that does not
6021
+ * resolve is logged and falls back to null — the unpinned snapshot build
6022
+ * already refuses it, so this only matters for pinned rows. Never throws.
6023
+ * @param {string} cwd
6024
+ * @param {string} agentType
6025
+ * @param {(line: string) => void} [log]
6026
+ * @returns {{ id: string, profile: any }|null}
6027
+ */
6028
+ function resolveJobEnvironment(cwd, agentType, log) {
6029
+ let declared = null;
6030
+ try {
6031
+ const persona = agentModelResolve.readOverlayAwarePersona(agentType || agentModelResolve.DEFAULT_PRD_AGENT_TYPE, { cwd });
6032
+ const fm = (persona && persona.fm) || {};
6033
+ if (typeof fm.environment === 'string' && fm.environment.trim()) declared = fm.environment.trim();
6034
+ } catch { /* no persona file → legacy default */ }
6035
+ const name = jobEnvironmentName({ agentType, declared });
6036
+ if (!name) return null;
6037
+ try {
6038
+ const env = loadEnvironment({ cwd, name });
6039
+ if ('code' in env) {
6040
+ if (log) log(`[scheduler] environment ${name}: ${env.code}; sandbox falls back to tool rules\n`);
6041
+ return null;
6042
+ }
6043
+ return { id: env.id, profile: env.profile };
6044
+ } catch (e) {
6045
+ if (log) log(`[scheduler] environment ${name} load failed (${(e && e.message) || e}); tool rules\n`);
6046
+ return null;
6047
+ }
6048
+ }
6049
+
6050
+ /**
6051
+ * Parks one queue row whose persona was refused at dispatch (agentModelResolve.cjs's
6052
+ * resolvePrdPersonaForSpawn `refusal`) — needs_review via transitionJob with
6053
+ * reason '<code>: <detail>'. The job never spawned, so there is no verify
6054
+ * pass, commit guard or transcript. Returns transitionJob's result.
6055
+ * @param {any} row
6056
+ * @param {{ code: string, detail: string }} refusal
6057
+ * @returns {boolean}
6058
+ */
6059
+ function applyPersonaRefusalPark(row, refusal) {
6060
+ const reason = `${refusal.code}: ${refusal.detail}`;
6061
+ if (!transitionJob(row, 'needs_review', { reason, source: 'executeJob:persona-refusal' })) return false;
6062
+ row.finishedAt = new Date().toISOString();
6063
+ row.exitCode = -1;
6064
+ row.error = reason;
6065
+ row.terminalReason = refusal.code;
6066
+ delete row.runtime;
6067
+ return true;
6068
+ }
6069
+
6070
+ /** Persists applyPersonaRefusalPark for `job`'s queue row, then broadcasts. */
6071
+ async function parkPersonaRefusal(job, refusal) {
6072
+ await mutate((s) => {
6073
+ const idx = s.jobs.findIndex((x) => x.slug === job.slug);
6074
+ if (idx >= 0) applyPersonaRefusalPark(s.jobs[idx], refusal);
6075
+ });
6076
+ await broadcast({ flush: true });
6077
+ }
6078
+
5203
6079
  /**
5204
6080
  * Execute a single PRD job. Writes stdout/stderr to a log file and a meta
5205
6081
  * JSON sidecar. Accepts an optional onPid(pid) callback called synchronously
@@ -5285,7 +6161,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5285
6161
  // session already has that in its own conversation history via
5286
6162
  // --resume, and re-embedding it here would just contradict whatever
5287
6163
  // state the session actually left on disk.
5288
- prompt = buildResumeRecoveryPreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch });
6164
+ prompt = resumeTarget.confirmation
6165
+ ? buildConfirmationResumePreamble(resumeTarget.confirmation)
6166
+ : resumeTarget.interrupt
6167
+ ? buildInterruptContinuePreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch, message: resumeTarget.message })
6168
+ : buildResumeRecoveryPreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch });
5289
6169
  } else {
5290
6170
  // Read full PRD body fresh from disk (queue stored only the preview).
5291
6171
  // Resolve through findPrdDirForJob's full candidate search (legacy flat
@@ -5451,6 +6331,16 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5451
6331
  isArtifactOnly = false;
5452
6332
  }
5453
6333
  }
6334
+ // Validator: list each judged PRD's structured criteria with their
6335
+ // mechanical check results (http + file run fresh here, outside the sandbox), so its per-criterion verdict entries use the
6336
+ // same ids and never mark a failed check met (parseValidatorVerdict refuses that).
6337
+ if (job.agentType === 'validator') {
6338
+ const { section, expected } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6339
+ // Stamped onto the queue row (spawnJob onPid) so notifyOriginatingTab
6340
+ // cross-checks the verdict against exactly these results.
6341
+ job.validatorCriteriaExpected = expected;
6342
+ if (section) prompt = `${prompt}\n\n${section}`;
6343
+ }
5454
6344
  prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
5455
6345
 
5456
6346
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
@@ -5477,10 +6367,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5477
6367
  // PRD agentType → persona + model (PRD 1115): resolved for both fresh and
5478
6368
  // resume dispatches, keyed off job.agentType (persisted on the queue row
5479
6369
  // by reconcile()) rather than re-reading the PRD file — a resumed session
5480
- // must keep launching as the SAME persona it started as. Never throws;
5481
- // a dangling/absent agentType falls back to no persona + FALLBACK_MODEL
5482
- // and is logged once by resolvePrdPersonaForSpawn itself.
5483
- const personaResolution = await agentModelResolve.resolvePrdPersonaForSpawn({ cwd, agentType: job.agentType });
6370
+ // must keep launching as the SAME persona it started as. Never throws.
6371
+ // An absent agentType resolves as 'dev-lead'; a persona that is missing,
6372
+ // unreadable or fails its frontmatter schema is a REFUSAL — the job is
6373
+ // never spawned, and the caller parks it needs_review with the reason.
6374
+ // AgentSnapshot pin (ma-agent-snapshot-pin-dispatch): the persona body,
6375
+ // model and tools come from an immutable, content-addressed snapshot
6376
+ // (agentSnapshot.cjs). A row already stamped with agentSnapshotId (a
6377
+ // resume, or any later dispatch of the same row) re-runs exactly that
6378
+ // snapshot — never the live persona file, which may have been edited since.
6379
+ // An unstamped row builds one (same persona resolution + refusal as
6380
+ // before), writes it once, and stamps job.agentSnapshotId (persisted on the
6381
+ // queue row by spawnJob's onPid mutate). A pinned snapshot that is missing
6382
+ // or tampered (readAgentSnapshot → null) parks agent_snapshot_missing.
6383
+ const packEpicId = job.epicId || job.sourcePromptId;
6384
+ let packEpic = null;
6385
+ try { packEpic = packEpicId ? agentModelResolve.findEpicById(cwd, packEpicId) : null; } catch { packEpic = null; }
6386
+ const personaResolution = await resolveJobAgentSnapshot(job, cwd, packEpic?.packs);
6387
+ if (personaResolution.refusal) {
6388
+ const { code, detail } = personaResolution.refusal;
6389
+ const refusalError = `${code}: ${detail}`;
6390
+ safeLog(`[scheduler] persona refused for ${job.slug} — not spawned: ${refusalError}\n`);
6391
+ closeFd();
6392
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: refusalError, personaRefusal: { code, detail }, startedAt, finishedAt: Date.now(), durationMs: 0, ...SCHEDULER_META_IDENTITY, ...setupMeta });
6393
+ return { exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } };
6394
+ }
5484
6395
  if (resumeTarget) {
5485
6396
  try {
5486
6397
  const dir = await prdPaths.findPrdDirForJob(job);
@@ -5510,21 +6421,47 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5510
6421
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5511
6422
  // capped) persona body — the persona cap never applies to laws. Fresh and
5512
6423
  // resume spawns alike; no Epic / no packs / an error = today's argv.
6424
+ // Persona-declared packs (`packs:`, recorded in the snapshot) load with the
6425
+ // Epic's. An unknown persona-declared pack parks the job (below); an
6426
+ // unknown Epic pack keeps being skipped (it was picked by a human at mint).
6427
+ const epicPackIds = Array.isArray(packEpic?.packs) ? packEpic.packs.map(String) : [];
6428
+ const personaPackIds = (personaResolution.packs || []).filter((p) => !epicPackIds.includes(p));
6429
+ const jobPackIds = [...epicPackIds, ...personaPackIds];
5513
6430
  let packArgs = { pluginDirArgs: [], laws: '' };
6431
+ /** @type {string[]|null} null = catalog unavailable (no pack refusal) */
6432
+ let unknownPacks = null;
5514
6433
  try {
5515
- const packEpicId = job.epicId || job.sourcePromptId;
5516
- const packEpic = packEpicId ? agentModelResolve.findEpicById(cwd, packEpicId) : null;
5517
- const composed = packSpawnArgs.composePackSpawnArgs({ packIds: packEpic?.packs });
6434
+ const composed = packSpawnArgs.composePackSpawnArgs({ packIds: jobPackIds.length ? jobPackIds : packEpic?.packs });
5518
6435
  if (composed && Array.isArray(composed.pluginDirArgs)) {
5519
6436
  packArgs = { pluginDirArgs: composed.pluginDirArgs, laws: typeof composed.laws === 'string' ? composed.laws : '' };
6437
+ unknownPacks = Array.isArray(composed.unknown) ? composed.unknown.map(String) : [];
5520
6438
  }
5521
6439
  } catch (err) {
5522
6440
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
5523
6441
  }
6442
+ // Declared capabilities, fail-closed: an MCP server (declared or tool-named)
6443
+ // missing from knownMcpServers(), or an unknown persona-declared pack,
6444
+ // parks the job needs_review 'capability_unknown: <name>' — never spawned
6445
+ // with a widened (every-server) config.
6446
+ const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6447
+ mcpServers: knownMcpServers(),
6448
+ declaredServers: personaResolution.mcpServers || [],
6449
+ packs: unknownPacks ? personaPackIds : [],
6450
+ knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6451
+ });
6452
+ if (capabilityCheck.refusal) {
6453
+ const code = capabilityCheck.refusal.code;
6454
+ const detail = capabilityCheck.refusal.name;
6455
+ const refusalError = `${code}: ${detail}`;
6456
+ safeLog(`[scheduler] capability refused for ${job.slug} — not spawned: ${refusalError}\n`);
6457
+ closeFd();
6458
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: refusalError, personaRefusal: { code, detail }, startedAt, finishedAt: Date.now(), durationMs: 0, ...SCHEDULER_META_IDENTITY, ...setupMeta, agentSnapshotId: personaResolution.agentSnapshotId || null });
6459
+ return { exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } };
6460
+ }
5524
6461
  const jobSystemPrompt = packArgs.laws
5525
6462
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
5526
6463
  : personaResolution.systemPrompt;
5527
- safeLog(`[scheduler] agentType=${job.agentType || '(none)'} persona=${personaResolution.personaPath || '(fallback — no persona applied)'} model=${personaResolution.model}${personaEffort ? ` effort=${personaEffort}${effortResolution.source === 'prd' ? ' (prd)' : ''}` : ''} ${personaToolScope ? `tools=${personaToolScope.tools.length} scoped` : 'tools=unscoped'}\n`);
6464
+ safeLog(`[scheduler] agentType=${job.agentType || '(none)'} agentSnapshot=${personaResolution.agentSnapshotId || '(unpinned)'}${personaResolution.pinned ? ' (pinned)' : ''} persona=${personaResolution.personaPath || '(from snapshot)'} model=${personaResolution.model}${personaEffort ? ` effort=${personaEffort}${effortResolution.source === 'prd' ? ' (prd)' : ''}` : ''} ${personaToolScope ? `tools=${personaToolScope.tools.length} scoped` : 'tools=unscoped'}\n`);
5528
6465
 
5529
6466
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
5530
6467
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -5557,6 +6494,18 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5557
6494
  // `launchEnv` is the launch circuit breaker's degraded-mode env (e.g.
5558
6495
  // MAX_THINKING_TOKENS=0 while an outdated CLI's thinking parameter is
5559
6496
  // being rejected — lib/scheduler/launchFailure.cjs); applied last so it wins.
6497
+ // Wall-clock budget, computed once: the budget watchdog below reads these
6498
+ // same values, and SM_SCHEDULER_JOB_DEADLINE_MS hands the child the epoch
6499
+ // ms at which that watchdog stops the job, so a tool it runs (e.g. a
6500
+ // batch voice render) can stop cleanly first. budgetExempt → no deadline.
6501
+ const budgetEstimate = budget.resolveBudgetEstimate({
6502
+ estimateMinutes: job.estimateMinutes,
6503
+ validatorEstimate,
6504
+ personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
6505
+ });
6506
+ const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
6507
+ const budgetExempt = budget.isJobBudgetExempt(job);
6508
+ const jobVoiceId = (typeof job.voiceId === 'string' && VOICE_ID_RE.test(job.voiceId)) ? job.voiceId : null;
5560
6509
  const childEnv = cleanChildEnv({
5561
6510
  PATH: withTimeoutShimOnPath(pathWithUserBins()),
5562
6511
  SM_PROJECT_ROOT: cwd,
@@ -5564,10 +6513,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5564
6513
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5565
6514
  ...personaToolScopeEnv(personaToolScope),
5566
6515
  SM_SCHEDULER_JOB_RISK_TOOLS: JSON.stringify(jobRiskTools),
6516
+ // Names the Epic a tool-risk 'confirm' request belongs to (guard-tool-risk-policy.cjs).
6517
+ ...((job.epicId || job.sourcePromptId) ? { SM_SCHEDULER_JOB_EPIC_ID: job.epicId || job.sourcePromptId } : {}),
5567
6518
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5568
6519
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
6520
+ ...(budgetExempt ? {} : { SM_SCHEDULER_JOB_DEADLINE_MS: String(Date.now() + jobBudgetMs) }),
6521
+ // The PRD's library voice (frontmatter voiceId) for a voiced tool the job runs; only a valid id, never otherwise.
6522
+ ...(jobVoiceId ? { SM_VOICE_ID: jobVoiceId } : {}),
5569
6523
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
5570
6524
  });
6525
+ // cleanChildEnv inherits process.env; a job without a valid voiceId must never carry one.
6526
+ if (!jobVoiceId) delete childEnv.SM_VOICE_ID;
5571
6527
  // Set AFTER cleanChildEnv returns, never inside the object passed to it:
5572
6528
  // cleanChildEnv strips every CLAUDE_CODE_*-prefixed key from its own
5573
6529
  // merged result (see cleanEnv.cjs), so setting it there would delete its
@@ -5575,6 +6531,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5575
6531
  // it starts has nothing to report back to — same stall as a tool that
5576
6532
  // waits for one.
5577
6533
  childEnv.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = '1';
6534
+ // This run's artifact staging folder; harvestJobArtifacts ingests it
6535
+ // into the Artifacts store before the worktree is removed.
6536
+ try {
6537
+ childEnv.SM_ARTIFACTS_DIR = artifactStore.stagingDirFor({ runId: jobArtifactRunId(job, path.basename(runDir)) });
6538
+ } catch (e) {
6539
+ safeLog(`[scheduler] ${job.slug}: SM_ARTIFACTS_DIR not set — ${e && e.message ? e.message : e}\n`);
6540
+ }
5578
6541
  if (launchEnv && Object.keys(launchEnv).length) {
5579
6542
  safeLog(`[scheduler] launch mitigation env applied: ${Object.entries(launchEnv).map(([k, v]) => `${k}=${v}`).join(' ')}\n`);
5580
6543
  }
@@ -5683,13 +6646,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5683
6646
  // is calibrated against). Only a PRD with an
5684
6647
  // explicit `budgetExempt: true` opts out entirely — logged once here so
5685
6648
  // an unbounded job is never silently unbounded.
5686
- const budgetEstimate = budget.resolveBudgetEstimate({
5687
- estimateMinutes: job.estimateMinutes,
5688
- validatorEstimate,
5689
- personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
5690
- });
5691
- const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
5692
- const budgetExempt = budget.isJobBudgetExempt(job);
6649
+ // budgetEstimate / jobBudgetMs / budgetExempt are computed once above,
6650
+ // before childEnv, so SM_SCHEDULER_JOB_DEADLINE_MS matches this watchdog.
5693
6651
  if (budgetExempt) {
5694
6652
  safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
5695
6653
  `(budgetExempt) — no wall-clock kill ceiling this run\n`);
@@ -5741,9 +6699,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5741
6699
  // never move it under the run directory.
5742
6700
  const sandboxDeps = resolveJobSandboxDeps();
5743
6701
  const sandboxAgentType = job.agentType || 'dev-lead';
6702
+ const jobEnvironment = resolveJobEnvironment(cwd, sandboxAgentType, safeLog);
6703
+ const enforcementMode = environmentEnforcement();
5744
6704
  /** @type {string|null} */
5745
6705
  let sandboxTmpDir = null;
5746
- if (sandboxDeps.available && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, sandboxAgentType)) {
6706
+ if (sandboxDeps.available && jobEnvironment && jobEnvironment.profile.osSandboxRequired) {
5747
6707
  try {
5748
6708
  sandboxTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smj-'));
5749
6709
  } catch (e) {
@@ -5757,16 +6717,50 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5757
6717
  };
5758
6718
  const sandboxPolicy = buildJobSandboxSettings({
5759
6719
  agentType: sandboxAgentType,
6720
+ environment: jobEnvironment,
5760
6721
  worktreeDir: spawnCwd,
5761
6722
  projectRoot: cwd,
5762
6723
  homeDir: os.homedir(),
5763
6724
  tmpDir: sandboxTmpDir || os.tmpdir(),
5764
6725
  deps: sandboxDeps,
6726
+ mode: enforcementMode,
5765
6727
  });
6728
+ // Enforce mode: an environment that needs the OS sandbox and cannot get it
6729
+ // is never downgraded to tool rules — the job is not spawned and
6730
+ // spawnJob parks it needs_review 'environment_unavailable: <missing deps>'
6731
+ // through the personaRefusal path (parkPersonaRefusal → transitionJob).
6732
+ if (sandboxPolicy.refusal) {
6733
+ const { code, detail } = sandboxPolicy.refusal;
6734
+ const refusalError = `${code}: ${detail}`;
6735
+ try {
6736
+ appendAuditEvent('environment_would_block', wouldBlockRecord({
6737
+ slug: job.slug, persona: sandboxAgentType, environment: jobEnvironment ? jobEnvironment.id : null,
6738
+ what: 'os_sandbox_unavailable', detail: sandboxPolicy.summary.reason, mode: enforcementMode,
6739
+ }));
6740
+ } catch { /* audit must not break dispatch */ }
6741
+ safeLog(`[scheduler] environment ${jobEnvironment ? jobEnvironment.id : '(none)'} refused for ${job.slug} — not spawned: ${refusalError}\n`);
6742
+ closeFd();
6743
+ removeSandboxTmp();
6744
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: refusalError, personaRefusal: { code, detail }, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: { ...sandboxPolicy.summary, tmpDir: null, enforcement: enforcementMode }, ...SCHEDULER_META_IDENTITY, ...setupMeta, agentSnapshotId: personaResolution.agentSnapshotId || null });
6745
+ resolve({ exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } });
6746
+ return;
6747
+ }
5766
6748
  // childEnv was built (and cleanChildEnv already ran) above.
5767
6749
  Object.assign(childEnv, sandboxChildEnv(sandboxPolicy, sandboxTmpDir || os.tmpdir()));
5768
- const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir };
5769
- safeLog(`[scheduler] sandbox: level=${sandboxMeta.level} profile=${sandboxMeta.profile ?? 'none'} ` +
6750
+ // guard-tool-risk reads these to deny (enforce) or report (report mode)
6751
+ // the WebFetch/WebSearch calls the environment disallows.
6752
+ Object.assign(childEnv, environmentHookEnv({ environment: jobEnvironment, mode: enforcementMode, agentType: sandboxAgentType }));
6753
+ for (const wb of sandboxPolicy.wouldBlock) {
6754
+ try {
6755
+ appendAuditEvent('environment_would_block', wouldBlockRecord({
6756
+ slug: job.slug, persona: sandboxAgentType, environment: jobEnvironment ? jobEnvironment.id : null,
6757
+ what: wb.what, detail: wb.detail, mode: enforcementMode,
6758
+ }));
6759
+ } catch { /* audit must not break dispatch */ }
6760
+ safeLog(`[scheduler] environment would block (report mode, not blocked): ${wb.what} — ${wb.detail}\n`);
6761
+ }
6762
+ const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir, enforcement: enforcementMode };
6763
+ safeLog(`[scheduler] sandbox: level=${sandboxMeta.level} environment=${sandboxMeta.environment ?? 'none'} profile=${sandboxMeta.profile ?? 'none'} ` +
5770
6764
  `network=${sandboxMeta.network ? (sandboxMeta.network.join(',') || 'none') : 'unrestricted'} reason=${sandboxMeta.reason ?? 'none'} ` +
5771
6765
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
5772
6766
  const jobArgs = buildClaudeSpawnArgs({
@@ -5777,28 +6771,56 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5777
6771
  resume: !!resumeTarget,
5778
6772
  systemPrompt: jobSystemPrompt,
5779
6773
  toolScope: personaToolScope,
6774
+ mcpServerNames: personaResolution.mcpServers || [],
5780
6775
  pluginDirArgs: packArgs.pluginDirArgs,
5781
6776
  jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5782
6777
  riskGuardSettingsPath,
5783
6778
  });
5784
6779
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5785
6780
 
6781
+ // Spawn-time credential assertion: the FINAL env (after every
6782
+ // Object.assign above) must carry no SECRET_KEY_RE key. Refuse, never spawn.
6783
+ try {
6784
+ assertNoCredentials(childEnv, { site: 'scheduler-job' });
6785
+ } catch (credErr) {
6786
+ const errMsg = String((credErr && credErr.message) || credErr);
6787
+ safeLog(`[scheduler] ${errMsg}\n`);
6788
+ closeFd();
6789
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, agentSnapshotId: personaResolution.agentSnapshotId || null });
6790
+ removeSandboxTmp();
6791
+ resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'credentials_in_env', sessionId });
6792
+ return;
6793
+ }
6794
+
5786
6795
  // Pre-spawn argv guard: one oversized argument makes spawn throw E2BIG.
5787
6796
  const oversized = launchFailure.findOversizedArg(jobSpawn.args || jobArgs);
5788
6797
  if (oversized) {
5789
6798
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5790
6799
  safeLog(`[scheduler] ${errMsg}\n`);
5791
6800
  closeFd();
5792
- config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta });
6801
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, agentSnapshotId: personaResolution.agentSnapshotId || null });
5793
6802
  removeSandboxTmp();
5794
6803
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5795
6804
  return;
5796
6805
  }
5797
6806
 
5798
6807
  const scopePlan = planJobScope({ jobSpawn, jobArgs, slug: job.slug, startedAt });
5799
- const scopeState = { unit: scopePlan.unit, pid: null, cgroupDir: null, finalized: false };
6808
+ const scopeState = { unit: scopePlan.unit, runId: path.basename(runDir), pid: null, cgroupDir: null, finalized: false, memoryMaxMb: scopePlan.memoryMaxMb, agentType: job.agentType || 'dev-lead' };
5800
6809
  const launchSpawn = scopePlan.spawn;
5801
6810
 
6811
+ // Epic event log: job.tool_use per tool_use block in the job's stream-json
6812
+ // log (summary only, ≤200 chars, secrets redacted). Polled alongside the
6813
+ // other watchdogs (never fires), flushed once more on exit.
6814
+ const toolUseEmitter = createJobToolUseEmitter({
6815
+ job, logPath, appendEvent: epicEventLog.appendEpicEvent, logError: (msg) => console.error(msg),
6816
+ });
6817
+ const toolUseWatchdog = toolUseEmitter ? {
6818
+ label: 'tool-use-events',
6819
+ intervalMs: RESULT_TAIL_POLL_MS,
6820
+ shouldFire() { try { toolUseEmitter.poll(); } catch { /* never throws */ } return false; },
6821
+ action() {},
6822
+ } : null;
6823
+
5802
6824
  const { child } = withChildAndLog({
5803
6825
  fd,
5804
6826
  logPath,
@@ -5824,8 +6846,9 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5824
6846
  ...detachedSpawnOpts(),
5825
6847
  },
5826
6848
  },
5827
- watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
6849
+ watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog, ...(toolUseWatchdog ? [toolUseWatchdog] : [])],
5828
6850
  onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
6851
+ if (toolUseEmitter) { try { toolUseEmitter.flush(); } catch { /* never breaks the exit path */ } }
5829
6852
  const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
5830
6853
  const durationMs = Date.now() - startedAt;
5831
6854
  finalizeJobScope(scopeState, sl);
@@ -5842,7 +6865,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5842
6865
  sl(`\n[scheduler] ${errMsg}\n`);
5843
6866
  // Sync write: inside a Promise executor callback; must flush meta
5844
6867
  // before resolve() so the spawnJob mutate() that follows sees it.
5845
- config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, originSessionId, contextDigestApplied });
6868
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, originSessionId, contextDigestApplied, agentSnapshotId: personaResolution.agentSnapshotId || null });
5846
6869
  removeSandboxTmp();
5847
6870
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5848
6871
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
@@ -5870,6 +6893,14 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5870
6893
  }
5871
6894
  sl(`\n[scheduler] exit code=${effectiveCode} (raw code=${exitCode} signal=${signal}) ` +
5872
6895
  `duration=${Math.round(durationMs / 1000)}s\n`);
6896
+ // The scope's own OOM killer fired: name the cap instead of a generic exit.
6897
+ const memoryCapReason = memoryCapFailureReason(scopeState, effectiveCode);
6898
+ if (memoryCapReason) sl(`\n[scheduler] ${memoryCapReason}\n`);
6899
+ // Post any tool-risk 'confirm' requests the guard recorded (this job's, and
6900
+ // any a crashed run left behind) as Needs-you items. Fire-and-forget: never throws.
6901
+ needsYouStore.drainConfirmationRequests().then((r) => {
6902
+ if (r.created > 0 && mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {});
6903
+ }, () => {});
5873
6904
  const rateLimited = effectiveCode !== 0 && detectRateLimitInLog(logPath);
5874
6905
  const networkError = effectiveCode !== 0 && !rateLimited && detectNetworkErrorInLog(logPath);
5875
6906
  // Non-run detection (issue #11 lists A1–A3): the harness's `result`
@@ -5906,14 +6937,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5906
6937
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5907
6938
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5908
6939
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6940
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapKill: { oomKills: scopeState.oomKills, memoryMaxMb: scopeState.memoryMaxMb ?? null } } : {}),
5909
6941
  sandbox: sandboxMeta,
5910
6942
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5911
6943
  originSessionId, contextDigestApplied,
6944
+ agentSnapshotId: personaResolution.agentSnapshotId || null,
5912
6945
  });
5913
6946
  removeSandboxTmp();
5914
6947
  resolve({
5915
6948
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5916
6949
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6950
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
5917
6951
  });
5918
6952
  },
5919
6953
  });
@@ -6009,7 +7043,7 @@ function isPromotableOriginal(status) {
6009
7043
  */
6010
7044
  function healTargetForFix(fixSlug, jobs) {
6011
7045
  const originalSlug = fixSlug.replace(/^(\d+)-fix-/, '$1-');
6012
- return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !reviewLadder.isCancelledJob(x)) || null;
7046
+ return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !isCancelledRow(x)) || null;
6013
7047
  }
6014
7048
 
6015
7049
  /**
@@ -6017,7 +7051,7 @@ function healTargetForFix(fixSlug, jobs) {
6017
7051
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
6018
7052
  * spawnInvestigation computes.
6019
7053
  */
6020
- function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild = null, recordPath = null, recordIgnored = true }) {
7054
+ function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, deadChild = null, recordPath = null, recordIgnored = true }) {
6021
7055
  const runtimePaths = RUNTIME_NAMESPACES.map((ns) => `session-manager-operations/${ns}/`).join(', ');
6022
7056
  const recordRule = (recordPath && !recordIgnored)
6023
7057
  ? `- The only allowed record location is ${recordPath}. If the fix plan asks for a record file, it must be exactly this path.
@@ -6133,7 +7167,6 @@ ${logTail}
6133
7167
  ---
6134
7168
  title: Fix: <short summary of the fix>
6135
7169
  cwd: ${cwd}
6136
- parallelGroup: ${group}
6137
7170
  estimateMinutes: <your time estimate>
6138
7171
  isFixPlan: true
6139
7172
  ---
@@ -6146,6 +7179,7 @@ ${logTail}
6146
7179
  not that repo (e.g. a scratch dir like \`/tmp\`), set \`cwd:\` to the correct repo root instead —
6147
7180
  the scheduler's commit guard and post-run verifier read git state from this path, and a
6148
7181
  non-repo cwd parks even a fully green, committed run in \`needs_review\`.
7182
+ List each file under \`# Files\` as \`- <repo-relative path>\` with nothing else on the line; put any note about a file in the Implementation notes, never on its path line.
6149
7183
  6. The PRD body MUST be self-contained — \`claude -p\` runs it on a fresh Sonnet session with NO conversation context. Include:
6150
7184
  - Root-cause analysis (what went wrong and why)
6151
7185
  - Concrete fix steps (specific files / commands / edits)
@@ -6221,6 +7255,18 @@ function readRunOutcomeSidecars(runDir, slug) {
6221
7255
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
6222
7256
 
6223
7257
  async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {}) {
7258
+ // Auto-dispatch hold first — before anything below can spawn a process
7259
+ // (probeClaudeVersion included). A held needs_review row stays eligible for
7260
+ // the periodic auto-fix pass; a plain 'failed' row (never a
7261
+ // selectAutoFixTargets target) waits in deferredInvestigations, which that
7262
+ // same pass drains once the hold clears.
7263
+ const queueState = await readQueue().catch(() => null);
7264
+ if (investigationHold(failedJob.slug, queueState?.config)) {
7265
+ if (failedJob.status !== 'needs_review' && !deferredInvestigations.has(failedJob.slug)) {
7266
+ deferredInvestigations.set(failedJob.slug, { failedJob, runDir });
7267
+ }
7268
+ return { deferred: true, held: true };
7269
+ }
6224
7270
  // A row waiting on its own red preflight spends nothing on the model
6225
7271
  // ladder: the precondition is the cause, not the work.
6226
7272
  if (reviewLadder.hasActivePreflightHold(failedJob)) {
@@ -6232,7 +7278,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6232
7278
  // B1: probes e4f82da2/d374e6bf died on the same HTTP 400 as the runs
6233
7279
  // they were investigating) there is nothing to diagnose — skip, loudly.
6234
7280
  {
6235
- const state = await readQueue().catch(() => null);
7281
+ const state = queueState;
6236
7282
  const block = state?.launchBlocks?.[INVESTIGATION_LAUNCH_KEY];
6237
7283
  const jobBlock = state?.launchBlocks?.[launchFailure.launchBlockKeyFor(failedJob)];
6238
7284
  const gate = launchFailure.evaluateLaunchGate(block || jobBlock, { now: Date.now(), claudeVersion: await probeClaudeVersion() });
@@ -6318,7 +7364,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6318
7364
  // archived twin (archivedPrdPathForJob) is deliberately NOT used for the
6319
7365
  // write dir, only for reading originalBody below.
6320
7366
  let originalBody = '';
6321
- const { fixPath, fixSlug, group, livePrdDir } = await resolveFixPlanPath(failedJob);
7367
+ const { fixPath, fixSlug, livePrdDir } = await resolveFixPlanPath(failedJob);
6322
7368
  try {
6323
7369
  const originalPath = livePrdDir ? path.join(livePrdDir, `${failedJob.slug}.md`) : prdPaths.archivedPrdPathForJob(failedJob);
6324
7370
  originalBody = (await parsePrd(originalPath)).body;
@@ -6372,7 +7418,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6372
7418
  } catch (err) {
6373
7419
  recordIgnored = !(err && err.code === 1);
6374
7420
  }
6375
- const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild, recordPath, recordIgnored });
7421
+ const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, deadChild, recordPath, recordIgnored });
6376
7422
 
6377
7423
  // Phase 1: open log fd for pre-spawn diagnostics.
6378
7424
  const { fd, safeLog, closeFd } = openLog(investigationLogPath);
@@ -6404,7 +7450,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6404
7450
  await mutate((s) => {
6405
7451
  const j = s.jobs.find((x) => x.slug === failedJob.slug);
6406
7452
  if (!j) return;
6407
- const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !reviewLadder.isCancelledJob(j) && !reviewLadder.hasActivePreflightHold(j);
7453
+ const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !isCancelledRow(j) && !reviewLadder.hasActivePreflightHold(j);
6408
7454
  const transitioned = statusEligible && transitionJob(j, 'investigating', { reason: 'spawning investigation probe', source: 'spawnInvestigation:start' });
6409
7455
  liveCheck = { ok: statusEligible && transitioned, status: j.status };
6410
7456
  });
@@ -6824,6 +7870,9 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6824
7870
  appendAuditEvent('job_cancel_integration_skipped', { slug: job.slug, runId, branch: worktree.branch });
6825
7871
  await pinUnlanded();
6826
7872
  await cleanup({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
7873
+ // An interrupted run is continued later in the same session: record
7874
+ // what it left uncommitted so the continue prompt can name it.
7875
+ await recordInterruptLeftovers(job.slug, runId, { dirtyPaths: worktreeLeftoverDirty, salvagePatch });
6827
7876
  return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead, uncommittedSnapshot };
6828
7877
  }
6829
7878
  if (worktreeHead.action === 'diverged') {
@@ -6879,7 +7928,12 @@ async function isRunCancelled(slug, runId) {
6879
7928
  try {
6880
7929
  const state = await readQueue();
6881
7930
  const row = state.jobs.find((j) => j.slug === slug);
6882
- return !!(row && row.cancelledAt && (row.cancelledRunId ?? null) === (runId ?? null));
7931
+ if (!row) return false;
7932
+ if (row.cancelledAt && (row.cancelledRunId ?? null) === (runId ?? null)) return true;
7933
+ // A human interrupt (remote.interruptJob) stops the run without ending
7934
+ // the job: its work stays on the job branch, never integrated, until
7935
+ // remote.continueJob resumes the same session.
7936
+ return !!(row.interrupted && (row.interrupted.runId ?? null) === (runId ?? null));
6883
7937
  } catch {
6884
7938
  return false;
6885
7939
  }
@@ -6918,6 +7972,42 @@ function guardedTick(fn, label) {
6918
7972
  * (and they never shadow a pickable sibling) while a dependent of a held
6919
7973
  * row still sees it as a blocking dep.
6920
7974
  */
7975
+ /**
7976
+ * Pending rows stopped by a human interrupt (remote.interruptJob) → Map<slug,
7977
+ * heldReason>. They wait for remote.continueJob and are never auto-dispatched
7978
+ * (a fresh dispatch would mint a new session instead of resuming).
7979
+ * @param {any[]} jobs
7980
+ * @returns {Map<string, string>}
7981
+ */
7982
+ function computeInterruptHolds(jobs) {
7983
+ const held = new Map();
7984
+ for (const j of jobs || []) {
7985
+ if (!j || j.status !== 'pending' || !j.interrupted) continue;
7986
+ held.set(j.slug, j.heldReason || 'interrupted by a human — waiting for continue');
7987
+ }
7988
+ return held;
7989
+ }
7990
+
7991
+ /**
7992
+ * Stamps an interrupted run's leftovers onto its row's `interrupted` record.
7993
+ * Only for the same run that was interrupted; never throws.
7994
+ * @param {string} slug
7995
+ * @param {string | null} runId
7996
+ * @param {{ dirtyPaths?: string[], salvagePatch?: string | null }} leftovers
7997
+ */
7998
+ async function recordInterruptLeftovers(slug, runId, { dirtyPaths, salvagePatch }) {
7999
+ try {
8000
+ await mutate((s) => {
8001
+ const row = s.jobs.find((x) => x.slug === slug);
8002
+ if (!row || !row.interrupted || (row.interrupted.runId ?? null) !== (runId ?? null)) return;
8003
+ row.interrupted.dirtyPaths = Array.isArray(dirtyPaths) ? dirtyPaths.slice(0, 200) : [];
8004
+ row.interrupted.salvagePatch = salvagePatch || null;
8005
+ });
8006
+ } catch (e) {
8007
+ console.warn(`[scheduler] ${slug}: could not record interrupt leftovers`, e?.message);
8008
+ }
8009
+ }
8010
+
6921
8011
  function computePreflightHolds(jobs, now = Date.now()) {
6922
8012
  const held = new Map();
6923
8013
  for (const j of jobs || []) {
@@ -7276,14 +8366,16 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7276
8366
  source: 'spawnJob:dispatch',
7277
8367
  });
7278
8368
  delete s.jobs[idx].heldReason;
7279
- // A fresh dispatch means any gateShadow, looksDone, or
7280
- // evidenceScannedAt on this row was computed for an earlier
7281
- // runId/startedAt — never let any of them linger and read as this
7282
- // run's result (looksDone stale here would let rung 6 complete this
7283
- // run on the PREVIOUS run's evidence).
8369
+ // A fresh dispatch means any gateShadow, looksDone,
8370
+ // evidenceScannedAt, or artifactEvidence on this row was computed for
8371
+ // an earlier runId/startedAt — never let any of them linger and read
8372
+ // as this run's result (looksDone stale here would let rung 6
8373
+ // complete this run on the PREVIOUS run's evidence; a running row
8374
+ // must never carry another run's artifactEvidence).
7284
8375
  delete s.jobs[idx].gateShadow;
7285
8376
  delete s.jobs[idx].looksDone;
7286
8377
  delete s.jobs[idx].evidenceScannedAt;
8378
+ delete s.jobs[idx].artifactEvidence;
7287
8379
  s.jobs[idx].runId = runId;
7288
8380
  s.jobs[idx].startedAt = new Date().toISOString();
7289
8381
  // Dispatch-phase breadcrumb (PRD: dispatch-region diagnostic
@@ -7480,6 +8572,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7480
8572
  // shape for the whole run). Named generically (not "worktree...") because
7481
8573
  // an in-place run salvages one too (PRD 1098).
7482
8574
  let salvagePatch = null;
8575
+ // Artifact evidence for a declared artifact-only PRD, captured while the
8576
+ // job worktree still exists (finalizeJobWorktree deletes it before
8577
+ // verifyRun runs). Null for in-place runs and undeclared PRDs.
8578
+ let artifactEvidence = null;
7483
8579
  let uncommittedSnapshot = null;
7484
8580
  // Which foreign-WIP shape applies to THIS run: an isolated worktree only
7485
8581
  // ever needs to disclose carriedPaths (its checkout starts clean apart
@@ -7494,6 +8590,8 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7494
8590
  const idx = s.jobs.findIndex((x) => x.slug === job.slug);
7495
8591
  if (idx >= 0) {
7496
8592
  s.jobs[idx].sessionId = sessionId;
8593
+ if (job.agentSnapshotId) s.jobs[idx].agentSnapshotId = job.agentSnapshotId;
8594
+ if (job.validatorCriteriaExpected) s.jobs[idx].validatorCriteriaExpected = job.validatorCriteriaExpected;
7497
8595
  s.jobs[idx].runtime = { pid, runId, startedAt: s.jobs[idx].startedAt, sessionId, cwd };
7498
8596
  s.jobs[idx].dispatchPhase = 'spawned';
7499
8597
  s.jobs[idx].dispatchPhaseAt = new Date().toISOString();
@@ -7514,7 +8612,22 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7514
8612
  // Plan records are written in the worktree and never committed; copy
7515
8613
  // them to the main checkout before verify and before the checkout is
7516
8614
  // removed. Never throws (planRecordHarvest.cjs).
7517
- harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8615
+ await harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8616
+ // Capture artifact evidence before the worktree is removed: a
8617
+ // git-ignored artifact may live only here. Never breaks teardown.
8618
+ try {
8619
+ const evidencePrdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
8620
+ artifactEvidence = captureArtifactEvidence({
8621
+ prdPath: evidencePrdPath,
8622
+ roots: [job.cwd || defaultCwd, worktree.dir],
8623
+ startedAt: dispatchStartedAt,
8624
+ });
8625
+ } catch {
8626
+ artifactEvidence = null;
8627
+ }
8628
+ // Same point for the Artifacts store: declared artifactPaths + the
8629
+ // job's SM_ARTIFACTS_DIR staging folder. Never throws.
8630
+ await harvestJobArtifacts(job, worktree.dir, job.cwd || defaultCwd, { runId });
7518
8631
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
7519
8632
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
7520
8633
  } else {
@@ -7578,6 +8691,14 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7578
8691
  // a sibling); an in-place run on the baseline delta.
7579
8692
  const jobDirt = worktree.ok ? stripAppOwnedChurn(worktreeLeftoverDirty) : newlyDirtyAll;
7580
8693
 
8694
+ // Persona refusal (persona_missing / persona_invalid): executeJob never
8695
+ // spawned. Park needs_review with '<code>: <detail>' — running ->
8696
+ // needs_review is a legal edge — instead of the old silent
8697
+ // 'no persona + sonnet' fallback.
8698
+ if (res.personaRefusal) {
8699
+ await parkPersonaRefusal(job, res.personaRefusal);
8700
+ return;
8701
+ }
7581
8702
  if (res.launchFailure) {
7582
8703
  await handleLaunchFailure({ job, res, runId, runDir, launchKey, launchEnv, claudeVersion: claudeVersionNow });
7583
8704
  return;
@@ -7615,9 +8736,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7615
8736
  // poller's own reads).
7616
8737
  billing.usageCircuit.recordFailure('executor_429');
7617
8738
  const logPath = path.join(runDir, `${job.slug}.log`);
7618
- const billingResetIso = await billingResetForPause();
8739
+ const billingReading = await billingReadingForPause();
8740
+ const billingResetIso = billingReading.resetsAt;
7619
8741
  const pauseState = await readQueue().catch(() => null);
7620
- const pauseThreshold = pauseState?.config?.utilizationThreshold;
8742
+ const pauseThreshold = bindingWindowPauseThreshold(pauseState?.config?.utilizationThreshold, billingReading, Date.now());
7621
8743
  const resetIso = resolveRateLimitPauseReset(logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
7622
8744
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
7623
8745
  const observedAt = dispatchStartedAtMs;
@@ -7761,7 +8883,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7761
8883
  priorLandedCommit,
7762
8884
  jobLandedCommitThisRun,
7763
8885
  exitCode: res.exitCode,
7764
- worktreeDir: worktree.ok ? worktree.dir : null,
8886
+ artifactEvidence,
7765
8887
  }).catch((e) => ({
7766
8888
  verdict: 'verify_unavailable',
7767
8889
  reason: `verifier threw: ${e?.message ?? String(e)}`,
@@ -8018,6 +9140,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8018
9140
  let investigationJobSnapshot = null;
8019
9141
  let investigationDeadChildSnapshot = null;
8020
9142
  let needsReviewRcaSnapshot = null;
9143
+ let outcomeRecordSnapshot = null; // every completed/failed/needs_review finalize (prdOutcomeRecord.cjs)
8021
9144
  let resumeRecoveryJob = null;
8022
9145
  let resumeRecoveryTarget = null;
8023
9146
  let quarantineJob = null;
@@ -8233,6 +9356,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8233
9356
  // is ALSO set (e.g. a real exit failure whose branch also failed
8234
9357
  // to integrate must show both, not just the first one).
8235
9358
  : [res.error, worktreeIntegrationFailure ? verifyResult.reason : null].filter(Boolean).join('; ') || null;
9359
+ // A scope OOM kill names the cap on every non-completed outcome
9360
+ // (failed rows already carry it via res.error above).
9361
+ if (res.memoryCapReason && effectiveStatus !== 'completed' && !String(s.jobs[i2].error || '').includes(res.memoryCapReason)) {
9362
+ s.jobs[i2].error = [res.memoryCapReason, s.jobs[i2].error].filter(Boolean).join('; ');
9363
+ }
8236
9364
  // Persist the commit THIS run landed (if HEAD advanced) so a later
8237
9365
  // re-fire of the same slug can prove its own no-op re-run is
8238
9366
  // truthful via the pass_no_commit_prior_run_verified exemption.
@@ -8274,6 +9402,21 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8274
9402
  } else {
8275
9403
  delete s.jobs[i2].uncommittedSnapshot;
8276
9404
  }
9405
+ // Persist this run's artifact evidence, bound to its runId, so the
9406
+ // stale needs_review rescan (reverifyNeedsReview) can verify a
9407
+ // worktree-only artifact after the worktree is gone. Cleared when
9408
+ // this run captured none so an older run's evidence never leaks.
9409
+ if (artifactEvidence) {
9410
+ s.jobs[i2].artifactEvidence = {
9411
+ runId,
9412
+ ok: artifactEvidence.ok,
9413
+ verified: artifactEvidence.verified,
9414
+ paths: artifactEvidence.paths,
9415
+ capturedAt: artifactEvidence.capturedAt,
9416
+ };
9417
+ } else {
9418
+ delete s.jobs[i2].artifactEvidence;
9419
+ }
8277
9420
  // Closed-set outcome taxonomy (issue #11 list A2) so a queue row
8278
9421
  // says WHY it ended without anyone opening the transcript.
8279
9422
  s.jobs[i2].terminalReason = launchFailure.deriveTerminalReason({
@@ -8351,6 +9494,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8351
9494
  // attribute" via its Array.isArray guard, same as an empty array.
8352
9495
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
8353
9496
 
9497
+ if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9498
+ outcomeRecordSnapshot = { ...s.jobs[i2] };
9499
+ }
8354
9500
  if (isNotifiableTerminalStatus(effectiveStatus)) {
8355
9501
  terminalNotifySnapshot = { ...s.jobs[i2] };
8356
9502
  }
@@ -8419,7 +9565,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8419
9565
  const fixSlugExists = (slug) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${slug}.md`)));
8420
9566
  if (
8421
9567
  process.env.SM_AUTOFIX_DISABLE !== '1' &&
8422
- reviewLadder.isEligibleForImmediateAutoFix(s.jobs[i2], s.jobs, fixSlugExists)
9568
+ reviewLadder.isEligibleForImmediateAutoFix(s.jobs[i2], s.jobs, fixSlugExists) &&
9569
+ // Under the auto-dispatch hold: stamp nothing, leave the row
9570
+ // eligible for the periodic auto-fix pass once the hold clears.
9571
+ !investigationHold(s.jobs[i2].slug, s.config)
8423
9572
  ) {
8424
9573
  const isRetryAttempt = s.jobs[i2].autoFixAttempted === true;
8425
9574
  const isDeadFixPlanReopen = reviewLadder.isFixPlanDead(s.jobs[i2], s.jobs);
@@ -8491,6 +9640,17 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8491
9640
  strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
8492
9641
  });
8493
9642
 
9643
+ // Structured per-PRD outcome record + outcome.recorded Epic event
9644
+ // (prdOutcomeRecord.cjs). Never blocks or fails the finalize.
9645
+ if (outcomeRecordSnapshot) {
9646
+ await writeJobOutcomeRecord(outcomeRecordSnapshot, {
9647
+ verifyResult,
9648
+ landedCommit: jobLandedCommitThisRun ?? null,
9649
+ strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
9650
+ fallbackCwd: defaultCwd,
9651
+ });
9652
+ }
9653
+
8494
9654
  if (terminalNotifySnapshot) {
8495
9655
  notifyOriginatingTab(terminalNotifySnapshot).catch((e) => {
8496
9656
  console.error('[scheduler] notifyOriginatingTab error', job.slug, e);
@@ -8754,12 +9914,260 @@ async function reclaimTerminalJobOrphansThrottled(state) {
8754
9914
  * with the 'running' transition).
8755
9915
  */
8756
9916
  async function spawnResumeRecovery(job, resumeTarget) {
8757
- const { runId, dir: runDir } = pickRunDir();
8758
9917
  // No queue rows in scope here (unlike tickQueue's own dispatch loop) — read
8759
9918
  // once, before delegating to spawnJob, so hasDownstreamValidator still
8760
- // never runs inside executeJob itself.
9919
+ // never runs inside executeJob itself. Its config also feeds the hold below.
9920
+ const state = await readQueue().catch(() => ({ jobs: [], config: undefined }));
9921
+ // A `--resume` run is an automatic `claude -p` that never passes through
9922
+ // tickBody, so it obeys the same auto-dispatch hold itself. A deferral
9923
+ // stamps nothing (spawnJob stamps resumeRecoveryAttempted only when it
9924
+ // runs): the row stays needs_review and the periodic reverifyNeedsReview
9925
+ // pass (selectResumeRecoveryBatch) resumes it once the hold clears.
9926
+ // One 'resume_recovery_held' line per row per hold (resumeRecoveryHeldKeys).
9927
+ const hold = currentAutoDispatchHold(state.config);
9928
+ if (hold) {
9929
+ if (noteHeldOnce(resumeRecoveryHeldKeys, job.slug, hold)) {
9930
+ console.log(`[scheduler] resume-recovery held for ${job.slug}: ${hold.reason} — ${hold.detail ?? ''}`);
9931
+ appendAuditEvent('resume_recovery_held', { slug: job.slug, reason: hold.reason });
9932
+ }
9933
+ return;
9934
+ }
9935
+ resumeRecoveryHeldKeys.delete(job.slug);
9936
+ const { runId, dir: runDir } = pickRunDir();
9937
+ const siblingJobs = state.jobs || [];
9938
+ await dispatchSpawnJob(job, runId, runDir, job.cwd || DEFAULT_PROJECT_CWD, resumeTarget, siblingJobs);
9939
+ }
9940
+
9941
+ const CONFIRM_APPROVE = 'Approve';
9942
+ const CONFIRM_BUSY = new Set(['running', 'investigating']);
9943
+ // record key -> hold key (autoDispatchHoldKey) under which its
9944
+ // 'tool_confirmation_resume_held' audit event was already appended (one event
9945
+ // per record per hold). Pruned to the pending records every pass and cleared
9946
+ // when no hold is in force (processToolConfirmationAnswers).
9947
+ const toolConfirmationHeldKeys = new Map();
9948
+ // slug -> hold key under which its 'investigation_held' / 'resume_recovery_held'
9949
+ // audit event was already appended (one event per row per hold). A row's key
9950
+ // is removed when no hold is in force for it (it launches), so a later hold
9951
+ // audits it once again; every tick also clears both Maps when no hold is in
9952
+ // force and drops slugs no longer in the queue (pruneRowHeldKeys).
9953
+ const investigationHeldKeys = new Map();
9954
+ const resumeRecoveryHeldKeys = new Map();
9955
+
9956
+ /**
9957
+ * Identity of one auto-dispatch hold: reason + window + reset rounded to the
9958
+ * minute (utilizationHold.holdIdentityKey — the usage API jitters resets_at
9959
+ * by about ±0.5 s from fetch to fetch).
9960
+ */
9961
+ function autoDispatchHoldKey(hold) {
9962
+ return autoDispatchHold.holdIdentityKey(hold);
9963
+ }
9964
+
9965
+ /** The audited fields of one auto-dispatch hold (null when none is in force). */
9966
+ function holdAuditFields(hold) {
9967
+ if (!hold) return null;
9968
+ return {
9969
+ reason: hold.reason,
9970
+ window: hold.window ?? null,
9971
+ percent: hold.percent ?? null,
9972
+ threshold: hold.threshold ?? null,
9973
+ baseThreshold: hold.baseThreshold ?? null,
9974
+ resetsAt: hold.resetsAt ?? null,
9975
+ holdKey: autoDispatchHold.holdIdentityKey(hold),
9976
+ };
9977
+ }
9978
+
9979
+ /**
9980
+ * One 'scheduler_human_press' audit event for a Run now / Fire next batch now
9981
+ * press, naming the auto-dispatch hold in force at press time (null = none),
9982
+ * so a human launch under a usage hold is told apart from a leak. Never throws.
9983
+ * @param {'run-now' | 'force-tick'} press
9984
+ */
9985
+ async function auditHumanPress(press) {
9986
+ try {
9987
+ let config = lastSeenConfig;
9988
+ try { config = (await readQueue()).config; } catch { /* last seen config */ }
9989
+ appendAuditEvent('scheduler_human_press', { press, hold: holdAuditFields(currentAutoDispatchHold(config)) });
9990
+ } catch (e) {
9991
+ console.error('[scheduler] human press audit failed', e?.message ?? String(e));
9992
+ }
9993
+ }
9994
+
9995
+ /**
9996
+ * One 'auto_dispatch_hold_bypassed' audit event for a human tick that passed
9997
+ * through `hold`, naming the slugs of the batch it launches. Never throws.
9998
+ */
9999
+ function auditHoldBypassed(hold, batch) {
10000
+ try {
10001
+ appendAuditEvent('auto_dispatch_hold_bypassed', {
10002
+ ...holdAuditFields(hold),
10003
+ dispatched: (batch || []).map((j) => j.slug),
10004
+ });
10005
+ } catch (e) {
10006
+ console.error('[scheduler] hold bypass audit failed', e?.message ?? String(e));
10007
+ }
10008
+ }
10009
+
10010
+ /**
10011
+ * Tick-level bound on the per-row held-key Maps. No hold in force → clear
10012
+ * both (a later hold audits every row once again); a hold in force → drop
10013
+ * slugs that are no longer a queue row (cancelled or archived while held).
10014
+ * `rawHold` is the tick's own hold decision, before any human bypass.
10015
+ * @param {any[] | undefined} jobs
10016
+ * @param {any} rawHold
10017
+ */
10018
+ function pruneRowHeldKeys(jobs, rawHold) {
10019
+ if (!rawHold) {
10020
+ investigationHeldKeys.clear();
10021
+ resumeRecoveryHeldKeys.clear();
10022
+ return;
10023
+ }
10024
+ const liveSlugs = new Set((jobs || []).map((j) => j.slug));
10025
+ for (const keys of [investigationHeldKeys, resumeRecoveryHeldKeys]) {
10026
+ for (const slug of keys.keys()) {
10027
+ if (!liveSlugs.has(slug)) keys.delete(slug);
10028
+ }
10029
+ }
10030
+ }
10031
+
10032
+ /**
10033
+ * Record `hold` as `slug`'s current hold in `keys`. true = this is a new hold
10034
+ * for the row (audit it); false = already audited under this same hold.
10035
+ */
10036
+ function noteHeldOnce(keys, slug, hold) {
10037
+ const key = autoDispatchHoldKey(hold);
10038
+ if (keys.get(slug) === key) return false;
10039
+ keys.set(slug, key);
10040
+ return true;
10041
+ }
10042
+
10043
+ /**
10044
+ * Apply answered tool-risk confirmation items (needsYouStore app 'tool-risk')
10045
+ * to the jobs that asked, via toolClearance.answerConfirmation:
10046
+ * - Approve → human.tool_confirmation { approved: true }, one clearance bound
10047
+ * to the args digest, and the job is re-dispatched with
10048
+ * `--resume <the same session id>` (in place, like resume recovery).
10049
+ * - Deny (or a withdrawn item) → human.tool_confirmation { approved: false },
10050
+ * the row is parked needs_review with verifierVerdict 'confirmation_denied'.
10051
+ * A record whose job is still running is left for a later tick; a request
10052
+ * recorded after the item was answered is never auto-applied (it waits for a
10053
+ * fresh item). Never throws.
10054
+ * Under the auto-dispatch hold (automatic ticks only) an approval is left
10055
+ * pending — one 'tool_confirmation_resume_held' audit event per record per hold.
10056
+ * @param {{ jobs?: any[], config?: any }} state
10057
+ * @param {{ human?: boolean }} [opts] the running tick's `human` flag
10058
+ */
10059
+ async function processToolConfirmationAnswers(state, { human = false } = {}) {
10060
+ try {
10061
+ const pending = toolClearance.listPendingConfirmations();
10062
+ // Bound the Map by construction: a record that vanished without a take
10063
+ // (deleted, or unreadable so the list skips it) drops its key here.
10064
+ const liveKeys = new Set(pending.map((rec) => rec.key));
10065
+ for (const key of toolConfirmationHeldKeys.keys()) {
10066
+ if (!liveKeys.has(key)) toolConfirmationHeldKeys.delete(key);
10067
+ }
10068
+ // No hold in force: a later hold audits every record once again. A human
10069
+ // tick that bypasses a hold in force does not count as the hold clearing.
10070
+ const rawHold = currentAutoDispatchHold(state.config);
10071
+ if (!rawHold) toolConfirmationHeldKeys.clear();
10072
+ // Same bound for the per-row investigation / resume-recovery held keys.
10073
+ pruneRowHeldKeys(state.jobs, rawHold);
10074
+ if (!pending.length) return;
10075
+ // Same hold decision as the tick running this pass: an approval starts a
10076
+ // `claude -p --resume`, so an automatic tick under the hold leaves it
10077
+ // pending for a later tick. A denial starts nothing and is applied anyway.
10078
+ const hold = human ? null : rawHold;
10079
+ toolClearance.pruneExpired();
10080
+ const items = await needsYouStore.listNeedsYou({ app: needsYouStore.CONFIRM_APP });
10081
+ const rowOf = (slug) => (state.jobs || []).find((j) => j.slug === slug) || null;
10082
+ for (const rec of pending) {
10083
+ const item = items.find((it) => it.id === needsYouStore.confirmationItemId(rec.tool, rec.argsDigest));
10084
+ if (!item || item.status === 'open') continue;
10085
+ const answeredAtMs = Date.parse(item.answeredAt || item.updatedAt || '') || 0;
10086
+ if (rec.requests.some((r) => CONFIRM_BUSY.has(rowOf(r.jobSlug)?.status) || runningSet.has(r.jobSlug))) continue;
10087
+ const approved = item.status === 'answered' && item.answer === CONFIRM_APPROVE;
10088
+ if (approved && hold) {
10089
+ if (noteHeldOnce(toolConfirmationHeldKeys, rec.key, hold)) {
10090
+ for (const r of rec.requests) appendAuditEvent('tool_confirmation_resume_held', { slug: r.jobSlug, reason: hold.reason });
10091
+ }
10092
+ continue;
10093
+ }
10094
+ if (approved && rec.requests.some((r) => (r.requestedAt || 0) <= answeredAtMs) && sessionSlots.availableFor('job') < 1) continue;
10095
+ const taken = toolClearance.takePendingConfirmation(rec.key);
10096
+ if (!taken) continue;
10097
+ toolConfirmationHeldKeys.delete(rec.key);
10098
+ for (const request of taken.requests) {
10099
+ if ((request.requestedAt || 0) > answeredAtMs) {
10100
+ console.warn(`[scheduler] ${request.jobSlug}: confirmation request for ${request.tool} postdates the answer — not applied`);
10101
+ continue;
10102
+ }
10103
+ await applyToolConfirmationAnswer(request, approved, rowOf(request.jobSlug));
10104
+ }
10105
+ }
10106
+ } catch (e) {
10107
+ console.warn('[scheduler] tool confirmation answers failed', e?.message);
10108
+ }
10109
+ }
10110
+
10111
+ /** One job's answer: emit, then resume (approve) or park (deny). */
10112
+ async function applyToolConfirmationAnswer(request, approved, row) {
10113
+ if (!row) {
10114
+ console.warn(`[scheduler] ${request.jobSlug}: confirmation answered but the job row is gone`);
10115
+ return;
10116
+ }
10117
+ const req = { ...request, sessionId: request.sessionId || row.sessionId || null };
10118
+ const eventTarget = { slug: row.slug, epicId: row.epicId || row.sourcePromptId || req.epicId, cwd: row.cwd || req.cwd };
10119
+ let resume = null;
10120
+ let park = null;
10121
+ toolClearance.answerConfirmation({ request: req, approved }, {
10122
+ emit: (event) => {
10123
+ emitJobEvent(eventTarget, event);
10124
+ appendAuditEvent('tool_confirmation_answered', { slug: row.slug, tool: event.tool, argsDigest: event.argsDigest, approved: event.approved });
10125
+ },
10126
+ resume: (r) => { resume = r; },
10127
+ park: (p) => { park = p; },
10128
+ });
10129
+ if (park) {
10130
+ await mutate((s) => {
10131
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
10132
+ if (!j) return;
10133
+ j.confirmationDenied = { tool: req.tool, argsDigest: req.argsDigest, at: new Date().toISOString(), reason: park.reason };
10134
+ if (j.status === 'failed' || j.status === 'needs_review') {
10135
+ transitionJob(j, 'needs_review', { reason: park.reason, source: 'processToolConfirmationAnswers' });
10136
+ j.verifierVerdict = park.reason;
10137
+ }
10138
+ });
10139
+ await broadcast({ flush: true });
10140
+ return;
10141
+ }
10142
+ if (!resume) return;
10143
+ const priorStatus = row.status;
10144
+ // needs_review and pending dispatch straight to 'running'; a finished row
10145
+ // takes the legal edge back to 'pending' first.
10146
+ if (priorStatus === 'completed' || priorStatus === 'failed' || priorStatus === 'skipped') {
10147
+ await mutate((s) => {
10148
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
10149
+ if (j) transitionJob(j, 'pending', { reason: 'tool confirmation approved: resuming the same session', source: 'processToolConfirmationAnswers' });
10150
+ });
10151
+ }
10152
+ const target = { sessionId: resume.sessionId, confirmation: { tool: req.tool, summary: req.summary || null, argsDigest: req.argsDigest } };
10153
+ const { runId, dir: runDir } = pickRunDir();
8761
10154
  const siblingJobs = (await readQueue().catch(() => ({ jobs: [] }))).jobs || [];
8762
- await spawnJob(job, runId, runDir, job.cwd || DEFAULT_PROJECT_CWD, resumeTarget, siblingJobs);
10155
+ const fresh = siblingJobs.find((x) => x.slug === row.slug) || row;
10156
+ // Not awaited: spawnJob runs the whole job. Its synchronous prefix takes
10157
+ // the session slot and adds the slug to runningSet before returning.
10158
+ Promise.resolve(dispatchSpawnJob(fresh, runId, runDir, fresh.cwd || DEFAULT_PROJECT_CWD, target, siblingJobs))
10159
+ .catch((e) => reportSchedulerError('tool confirmation resume failed', row.slug, e));
10160
+ if (!runningSet.has(row.slug)) {
10161
+ // No slot after all: restore the row and keep the request for a later tick.
10162
+ if (priorStatus === 'completed' || priorStatus === 'failed' || priorStatus === 'skipped') {
10163
+ const back = priorStatus;
10164
+ await mutate((s) => {
10165
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
10166
+ if (j && j.status === 'pending') transitionJob(j, back, { reason: 'tool confirmation resume deferred: no session slot', source: 'processToolConfirmationAnswers' });
10167
+ });
10168
+ }
10169
+ toolClearance.recordPendingConfirmation(request, { now: request.requestedAt || 0 });
10170
+ }
8763
10171
  }
8764
10172
 
8765
10173
  // Serialized ticker: prevents two concurrent tickQueue() calls from racing
@@ -8814,11 +10222,14 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
8814
10222
  }
8815
10223
  }
8816
10224
 
8817
- function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
10225
+ // `human` is set only by the 'schedule:force-tick' and 'schedule:run-now' IPC
10226
+ // handlers (via runDueJobs): those ticks bypass the auto-dispatch hold. Every
10227
+ // automatic tick — the starvation watchdog included — honors it.
10228
+ function tickQueue({ bypassLoadGate = false, lastResort = false, human = false } = {}) {
8818
10229
  const budgetMs = tickWatchdogMs();
8819
10230
  const next = tickTail.then(() => {
8820
10231
  const gen = tickGeneration;
8821
- return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
10232
+ return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort, human }), budgetMs, () => {
8822
10233
  tickGeneration++; // fence the abandoned body
8823
10234
  console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
8824
10235
  if (!tickWedgeLatched) {
@@ -8841,10 +10252,13 @@ function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
8841
10252
  // The stale sentinel a fenced body returns: never recorded, never acted on.
8842
10253
  const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
8843
10254
 
8844
- async function tickBody(gen, { bypassLoadGate, lastResort }) {
10255
+ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
8845
10256
  const tickStartedAt = Date.now();
8846
10257
  // evaluate() only runs once slots and memory admit a batch, so the CPU sampler
8847
10258
  // needs every tick to keep a reference reading about a minute old.
10259
+ // Leftover chat/aux tool processes (their turn's claude gone) drop to nice 19
10260
+ // first, so the sample sees them as idle-priority load (PRD 4022). Never throws.
10261
+ if (process.platform === 'linux') reniceLeftovers();
8848
10262
  loadGate.observe();
8849
10263
  {
8850
10264
  const stale = () => gen !== tickGeneration;
@@ -8902,12 +10316,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8902
10316
  reclaimTerminalJobOrphansThrottled(state).catch((e) => {
8903
10317
  console.warn('[scheduler] terminal job-worktree orphan reclaim failed', e?.message);
8904
10318
  });
8905
- // Emit epic_state_changed audit rows for Epics whose outside-facing state
8906
- // moved since the last tick. Best-effort and fire-and-forget: never awaited,
8907
- // must never hold up dispatch.
8908
- runEpicStateWatchForTick(state).catch((e) => {
8909
- console.warn('[scheduler] epic state watch failed', e?.message);
8910
- });
10319
+ // Owner answers to tool-risk 'confirm' requests: approve resumes the SAME
10320
+ // session with a single-use clearance, deny parks confirmation_denied.
10321
+ // Awaited (not fire-and-forget) so a resumed row is in runningSet before
10322
+ // the picker below runs; never throws.
10323
+ await processToolConfirmationAnswers(state, { human });
10324
+ if (stale()) return STALE_TICK;
8911
10325
  // Session-Manager's machine-wide slot pool is the ONLY concurrency limit
8912
10326
  // the picker answers to (plus the memory gate below). The scheduler used
8913
10327
  // to also carry a private `concurrencyCap` of 3 — the exact per-consumer
@@ -8919,11 +10333,50 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8919
10333
  // second pool: the row count admitted this tick simply can't exceed the
8920
10334
  // degraded cap minus what's already running.
8921
10335
  runReservationExpiryPass(state.jobs, tickStartedAt);
10336
+ // Auto-dispatch hold (scheduler/utilizationHold.cjs): every automatic
10337
+ // tick — job finish, 30 s loop, freed slot, reaper, billing poll,
10338
+ // watchdog, boot/resume runDueJobs — holds at or above the threshold on
10339
+ // ANY live window of the last real reading, and under firePolicy
10340
+ // 'manual'. Only a human Run now / Fire next batch now passes through.
10341
+ // bypassedHold = the hold a human tick passed through (audited after the picker).
10342
+ let bypassedHold = null;
10343
+ {
10344
+ const hold = currentAutoDispatchHold(state.config);
10345
+ const nextHold = hold && hold.reason === 'utilization-held'
10346
+ ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt }
10347
+ : null;
10348
+ const holdKey = hold ? `${hold.reason}|${hold.window ?? ''}|${String(hold.percent)}` : null;
10349
+ const holdChanged = holdKey !== lastAutoDispatchHoldKey;
10350
+ utilizationHold = nextHold;
10351
+ lastAutoDispatchHoldKey = holdKey;
10352
+ const pendingCount = hold || openAutoDispatchHold
10353
+ ? state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length
10354
+ : 0;
10355
+ if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount);
10356
+ if (hold) {
10357
+ if (human) {
10358
+ bypassedHold = hold;
10359
+ console.log(`[scheduler] ${hold.reason}: ${hold.detail} — human run bypassed the hold`);
10360
+ } else {
10361
+ if (holdChanged) {
10362
+ console.log(`[scheduler] ${hold.reason}: ${hold.detail} — holding ${pendingCount} pending job(s)`);
10363
+ await broadcast();
10364
+ if (stale()) return STALE_TICK;
10365
+ }
10366
+ loadGate.endHold();
10367
+ return recordTick({ fired: false, reason: hold.reason, deferredCount: pendingCount }, { detail: hold.detail });
10368
+ }
10369
+ } else if (holdChanged) {
10370
+ await broadcast();
10371
+ if (stale()) return STALE_TICK;
10372
+ }
10373
+ }
8922
10374
  const freeSlots = degradedConcurrencyCapValue != null
8923
10375
  ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8924
10376
  : sessionSlots.availableFor('job');
8925
10377
  const heldSlugs = await computeLaunchHolds(state);
8926
10378
  for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10379
+ for (const [slug, why] of computeInterruptHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
8927
10380
  if (stale()) return STALE_TICK;
8928
10381
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8929
10382
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -8935,6 +10388,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8935
10388
  heldSlugs,
8936
10389
  satisfiedSlugsByCwd,
8937
10390
  });
10391
+ if (bypassedHold) auditHoldBypassed(bypassedHold, batch);
8938
10392
  if (batch.length === 0 && freeSlots === 0) {
8939
10393
  const snap = sessionSlots.snapshot();
8940
10394
  const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
@@ -8991,28 +10445,39 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8991
10445
  const jobBudgetMb = availableForJobs(availableMb, RESERVED_HOST_MB);
8992
10446
  // The slot pool already bounded `batch` (it was passed as freeSlots to
8993
10447
  // pickNextBatch above), so only the memory gate can narrow it further.
8994
- // Credit each running job's already-resident RSS (capped at its reservation)
8995
- // — MemAvailable is already net of it. Unknown pid / 0 MB read = no credit.
8996
- let consumedMb = 0;
10448
+ // Measured reservations (PRD 4019, loadGate.measuredMemoryGate): each running
10449
+ // job keeps only max(0, its agentType's p50 peak − its current RSS) — its RSS
10450
+ // is already out of MemAvailable — each new job reserves its agentType's p75,
10451
+ // plus one shared spike buffer. Too few samples = the old flat 2.5 GB/job rule.
10452
+ // Unknown pid / 0 MB read = no RSS credit.
10453
+ const runningForGate = [];
8997
10454
  if (availableMb !== Infinity) {
8998
10455
  for (const j of state.jobs) {
8999
10456
  if (!runningSet.has(j.slug)) continue;
9000
10457
  const pid = j.runtime?.pid ?? j.pid;
9001
- if (!Number.isInteger(pid) || pid <= 0) continue;
9002
- consumedMb += Math.min(processGroupRssMb(pid), MIN_FREE_MB_PER_JOB);
9003
- }
9004
- consumedMb = Math.min(consumedMb, MIN_FREE_MB_PER_JOB * runningSet.size);
9005
- }
9006
- const allowed = memoryLimitedBatchSize(
9007
- jobBudgetMb, MIN_FREE_MB_PER_JOB, runningSet.size, batch.length, consumedMb,
9008
- );
10458
+ const rssMb = Number.isInteger(pid) && pid > 0 ? processGroupRssMb(pid) : 0;
10459
+ runningForGate.push({ agentType: j.agentType, rssMb });
10460
+ }
10461
+ // A running slug without a queue row still holds memory: count it at 0 RSS.
10462
+ for (let k = runningForGate.length; k < runningSet.size; k++) runningForGate.push({ agentType: null, rssMb: 0 });
10463
+ }
10464
+ const memGate = measuredMemoryGate({ jobBudgetMb, running: runningForGate, batch, stats: jobMemoryStats });
10465
+ const allowed = memGate.allowed;
10466
+ const consumedMb = memGate.consumedMb;
10467
+ const memGateTerms = {
10468
+ reservationMb: memGate.reservationMb,
10469
+ spikeBufferMb: memGate.spikeBufferMb,
10470
+ runningGrowthMb: memGate.growthMb,
10471
+ measured: memGate.measured,
10472
+ };
9009
10473
  if (allowed === 0) {
9010
- const threshold = RESERVED_HOST_MB + MIN_FREE_MB_PER_JOB * (runningSet.size + 1) - consumedMb;
9011
- console.log(`[scheduler] memory gate: available=${availableMb} MB < threshold=${threshold} MB (host reserve ${RESERVED_HOST_MB} + ${MIN_FREE_MB_PER_JOB}/job × ${runningSet.size + 1} - consumed=${consumedMb} MB) — deferring ${batch.length} job(s)`);
9012
- lastMemGate = { availableMb, threshold, consumedMb, deferred: true, at: new Date().toISOString() };
10474
+ const threshold = RESERVED_HOST_MB + memGate.needMb;
10475
+ const detail = formatMemoryGateDetail({ availableMb, threshold, reservedHostMb: RESERVED_HOST_MB, gate: memGate });
10476
+ console.log(`[scheduler] ${detail} — deferring ${batch.length} job(s) (${runningSet.size} running)`);
10477
+ lastMemGate = { availableMb, threshold, consumedMb, ...memGateTerms, deferred: true, at: new Date().toISOString() };
9013
10478
  return recordTick(
9014
- { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, threshold, consumedMb },
9015
- { detail: `memory gate: ${availableMb} MB free, need ${threshold} MB (consumed=${consumedMb} MB credited)`, holds },
10479
+ { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, threshold, consumedMb, ...memGateTerms },
10480
+ { detail, holds },
9016
10481
  );
9017
10482
  }
9018
10483
  const swapAllowed = swapLimitedBatchSize(memInfo, runningSet.size, allowed);
@@ -9032,8 +10497,9 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
9032
10497
  }
9033
10498
  const gatedBatch = batch.slice(0, swapAllowed);
9034
10499
  if (gatedBatch.length < batch.length) {
9035
- console.log(`[scheduler] memory gate: available=${availableMb} MB — clamped batch ${batch.length} → ${gatedBatch.length} (host reserve ${RESERVED_HOST_MB} + ${MIN_FREE_MB_PER_JOB}/job, consumed=${consumedMb} MB)`);
9036
- lastMemGate = { availableMb, threshold: RESERVED_HOST_MB + MIN_FREE_MB_PER_JOB * (runningSet.size + gatedBatch.length) - consumedMb, consumedMb, deferred: false, clamped: true, at: new Date().toISOString() };
10500
+ const threshold = RESERVED_HOST_MB + memGate.needMb;
10501
+ console.log(`[scheduler] memory gate: available=${availableMb} MB — clamped batch ${batch.length} → ${gatedBatch.length} (${formatMemoryGateDetail({ availableMb, threshold, reservedHostMb: RESERVED_HOST_MB, gate: memGate })})`);
10502
+ lastMemGate = { availableMb, threshold, consumedMb, ...memGateTerms, deferred: false, clamped: true, at: new Date().toISOString() };
9037
10503
  } else {
9038
10504
  // Ungated full batch: clear stale gate snapshot so status doesn't show
9039
10505
  // a stale deferral from a previous tick.
@@ -9174,7 +10640,7 @@ function forceTickOutcome(result) {
9174
10640
  }
9175
10641
  }
9176
10642
 
9177
- async function runDueJobs({ bypassLoadGate = false } = {}) {
10643
+ async function runDueJobs({ bypassLoadGate = false, human = false } = {}) {
9178
10644
  const state = await readQueue();
9179
10645
  if (state.unreadable) {
9180
10646
  console.error('[scheduler] runDueJobs skipped: queue.json unreadable');
@@ -9185,31 +10651,21 @@ async function runDueJobs({ bypassLoadGate = false } = {}) {
9185
10651
  return { fired: false, reason: 'paused' };
9186
10652
  }
9187
10653
  cancelToken = { cancelled: false };
9188
- const result = await tickQueue({ bypassLoadGate });
10654
+ const result = await tickQueue({ bypassLoadGate, human });
9189
10655
  await broadcast();
9190
10656
  return result;
9191
10657
  }
9192
10658
 
9193
10659
  // ---------- when-available launch logic ----------
9194
10660
 
10661
+ // The utilization hold lives in tickBody (autoDispatchHold), so this ticks
10662
+ // and the tick itself holds — the same rule for every automatic caller.
9195
10663
  async function maybeLaunchWhenAvailable(state) {
9196
- utilizationHold = null;
9197
10664
  if (state.config.firePolicy !== 'when-available') return;
9198
10665
  if (state.paused) return;
9199
10666
  const pending = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug));
9200
10667
  if (pending.length === 0) return;
9201
10668
  if (cachedUtilization === null || cachedUtilization === undefined) return;
9202
- if (cachedUtilization >= state.config.utilizationThreshold) {
9203
- utilizationHold = {
9204
- window: cachedBindingWindowName,
9205
- percent: cachedUtilization,
9206
- threshold: state.config.utilizationThreshold,
9207
- resetsAt: cachedNextReset,
9208
- };
9209
- console.log(`[scheduler] when-available: utilization-held — ${cachedBindingWindowName ?? 'unknown'} window at ${cachedUtilization}% ≥ ${state.config.utilizationThreshold}%, resets ${cachedNextReset ?? 'unknown'}, ${pending.length} pending — holding, not ticking`);
9210
- await broadcast();
9211
- return;
9212
- }
9213
10669
  console.log(`[scheduler] when-available: util=${cachedUtilization}%, ${pending.length} pending, ${runningSet.size} running — ticking`);
9214
10670
  tickQueue().catch((e) => console.error('[scheduler] tickQueue error', e));
9215
10671
  }
@@ -9233,6 +10689,9 @@ async function runQueueStarvationWatchdog(state, {
9233
10689
  now = Date.now(), thresholdMs = starvation.QUEUE_STARVATION_MS,
9234
10690
  bootedAtMs = Date.parse(SCHEDULER_BOOTED_AT), pauseClearedAtMs = lastPauseClearedAt,
9235
10691
  } = {}) {
10692
+ // Under the auto-dispatch hold an idle queue is the intended outcome, not
10693
+ // starvation: no warning, no audit, no forced tick.
10694
+ if (currentAutoDispatchHold(state?.config)) return null;
9236
10695
  // The idle clock is launch-keyed (dispatchIdleMs): NOT lastDispatchAttemptAt,
9237
10696
  // which tickQueue stamps before every gate — a queue whose 30 s loop ticks
9238
10697
  // and launches nothing would refresh it forever and the watchdog would
@@ -9397,7 +10856,7 @@ function rootBlockerPhrase(root) {
9397
10856
  * project_starved WARN + audit (each naming the root blocker), then the
9398
10857
  * bounded escalation. A known wait (starveRootFor) is skipped by both.
9399
10858
  */
9400
- function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}) {
10859
+ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}, config = undefined) {
9401
10860
  for (const sp of starvedProjects) {
9402
10861
  const { root, knownWait } = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
9403
10862
  if (knownWait) continue;
@@ -9416,10 +10875,12 @@ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}) {
9416
10875
  // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
9417
10876
  // a subset of the rows already reported above — same verdict, no
9418
10877
  // re-derivation.
9419
- runStarveEscalationSweep(starvedProjects, jobs, launchBlocks);
10878
+ runStarveEscalationSweep(starvedProjects, jobs, launchBlocks, config);
9420
10879
  }
9421
10880
 
9422
- function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
10881
+ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}, config = undefined) {
10882
+ // The auto-dispatch hold is why nothing dispatches — not a starve to escalate.
10883
+ if (currentAutoDispatchHold(config)) return;
9423
10884
  const rootByCwd = new Map();
9424
10885
  const reportable = starvedProjects.filter((sp) => {
9425
10886
  const r = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
@@ -9833,8 +11294,9 @@ async function reapDeadRunningJobs() {
9833
11294
  // observed 429 as a live one, and must open the same shared circuit.
9834
11295
  billing.usageCircuit.recordFailure('executor_429');
9835
11296
  const triggering = dead.find((d) => d.outcome === 'rate_limited');
9836
- const billingResetIso = await billingResetForPause();
9837
- const pauseThreshold = state.config?.utilizationThreshold;
11297
+ const billingReading = await billingReadingForPause();
11298
+ const billingResetIso = billingReading.resetsAt;
11299
+ const pauseThreshold = bindingWindowPauseThreshold(state.config?.utilizationThreshold, billingReading, Date.now());
9838
11300
  const resetIso = resolveRateLimitPauseReset(triggering.logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
9839
11301
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
9840
11302
  const triggeringRow = triggering ? state.jobs.find((x) => x.slug === triggering.slug) : null;
@@ -10336,6 +11798,11 @@ async function pollLoop() {
10336
11798
  // YELLOW/RED forever even though nothing is actually degraded.
10337
11799
  if (billing.usageCircuit.state() !== 'closed') billing.usageCircuit.recordSuccess({});
10338
11800
  cachedUtilization = NO_METER_UTILIZATION;
11801
+ cachedUtilizationKnown = true;
11802
+ // A reading left from an earlier consumer login must never hold a
11803
+ // machine that has no meter.
11804
+ lastGoodUsagePayload = null;
11805
+ restoredUsageWindows = null;
10339
11806
  degradedConcurrencyCapValue = null;
10340
11807
  consecutiveFailures = 0;
10341
11808
  backoffMs = 0;
@@ -10400,6 +11867,7 @@ async function pollLoop() {
10400
11867
  recordObservedReset(window.resets_at ?? null);
10401
11868
  cachedUtilization = window.utilization;
10402
11869
  cachedBindingWindowName = window.name;
11870
+ cachedUtilizationKnown = true;
10403
11871
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
10404
11872
  degradedConcurrencyCapValue = null;
10405
11873
  consecutiveFailures = 0;
@@ -10445,8 +11913,12 @@ async function pollLoop() {
10445
11913
  lastGoodUsagePayload = r.cached;
10446
11914
  cachedUtilization = cachedBudget.utilization;
10447
11915
  cachedBindingWindowName = cachedBudget.name;
11916
+ cachedUtilizationKnown = true;
10448
11917
  degradedConcurrencyCapValue = null;
10449
11918
  } else {
11919
+ // A stale cache is still the last real reading: carry it (cap 2)
11920
+ // rather than the 100% placeholder.
11921
+ if (r.cached) lastGoodUsagePayload = r.cached;
10450
11922
  applyDegradedBudget();
10451
11923
  }
10452
11924
  console.log(`[scheduler] billing meter rate-limited (HTTP 429) — firing on ${cachedBudget ? 'cached' : 'degraded'} budget (util=${cachedUtilization}%, cap=${degradedConcurrencyCapValue}) (failure #${consecutiveFailures}); retry in ${backoffMs / 1000}s`);
@@ -10589,11 +12061,12 @@ function selectHistoryJobs(jobs, limit, historyEntries = []) {
10589
12061
  * guard-parked row was never "exhausted auto-fix" and must never claim to be.
10590
12062
  */
10591
12063
  function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10592
- if (!j || j.status !== 'needs_review' || reviewLadder.isCancelledJob(j) || !reviewLadder.isEligibleForNeedsReviewAutoResolve(j, jobsInProject)) return null;
12064
+ if (!j || j.status !== 'needs_review' || isCancelledRow(j) || !reviewLadder.isEligibleForNeedsReviewAutoResolve(j, jobsInProject)) return null;
10593
12065
  if ((j.exhaustedResolveAttempts ?? 0) > reviewLadder.NEEDS_REVIEW_RESOLVE_CAP) return null;
10594
12066
  const originIsGuardParked = !reviewLadder.isExhaustedAutoFix(j) && reviewLadder.isGuardParkedWithoutAutoFix(j);
10595
12067
 
10596
- if (j.looksDone) {
12068
+ // A looksDone stamped before PRD 4500 must never complete a FAIL row.
12069
+ if (j.looksDone && j.verifierVerdict !== 'sentinel_fail') {
10597
12070
  const attempt = j.exhaustedResolveAttempts ?? 0;
10598
12071
  const reason = originIsGuardParked
10599
12072
  ? `needs_review auto-resolve: guard verdict '${j.verifierVerdict}' with landed commit and looksDone evidence (${j.looksDone.rule}) — `
@@ -10640,7 +12113,7 @@ function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10640
12113
  * 'skipped', or null when the race guard rejects it.
10641
12114
  */
10642
12115
  function applyStuckFailedAutoSkip(j, ageMs = 0) {
10643
- if (!j || j.status !== 'failed' || reviewLadder.isCancelledJob(j)) return null;
12116
+ if (!j || j.status !== 'failed' || isCancelledRow(j)) return null;
10644
12117
  if ((j.failedAutoResetAttempts ?? 0) < reviewLadder.FAILED_AUTORESET_CAP) return null;
10645
12118
  const cap = reviewLadder.FAILED_AUTORESET_CAP;
10646
12119
  j.needsReviewAutoResolvedSkip = true;
@@ -10804,6 +12277,10 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
10804
12277
  * @returns {Promise<{commits: string[], paths: string[], detectedAt: string, rule: string} | null>}
10805
12278
  */
10806
12279
  async function computeLooksDone(job, fetchedCwds) {
12280
+ // An explicit executor FAIL is authoritative: the run said the work is not
12281
+ // done, so its own commits (often just a record of the blocker) are never
12282
+ // evidence that it is (PRD 4500; starry-night-2 863-fix, eac6e7e).
12283
+ if (job?.verifierVerdict === 'sentinel_fail') return null;
10807
12284
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
10808
12285
  const paths = declaredPathsForPrd(prdPath);
10809
12286
  if (!paths.length) return null;
@@ -10910,6 +12387,20 @@ async function runGateShadow(job) {
10910
12387
  const definitive = headStable && cleanOk && (outcome.status === 'green' || outcome.status === 'red');
10911
12388
  const gateShadow = { ...outcome, head: headBefore, source: gate.source, ranAt: new Date().toISOString(), definitive, ...(mainDeps ? { mainDeps } : {}) };
10912
12389
 
12390
+ // Structured criteria (prdCriteria.cjs): after the gate re-run, run each
12391
+ // criterion's mechanical check in the same tree and keep the observed
12392
+ // results for the run record and the validator. Runs after headAfter/
12393
+ // dirtAfter are taken so a check can never sway the gate's own judgement.
12394
+ let criteriaFm = null;
12395
+ try { criteriaFm = parsePrdFile(prdText).frontmatter.criteria; } catch { criteriaFm = null; }
12396
+ if (Array.isArray(criteriaFm) && criteriaFm.length) {
12397
+ try {
12398
+ gateShadow.criteriaChecks = await runCriteriaChecks({ criteria: criteriaFm, cwd: job.cwd });
12399
+ } catch (e) {
12400
+ console.warn('[scheduler] criteria checks error', job.slug, e && e.message ? e.message : e);
12401
+ }
12402
+ }
12403
+
10913
12404
  // Gate authority: a green re-run may complete the row outright, but only
10914
12405
  // for transcript-noise verdicts with a landed commit — every other park
10915
12406
  // (including no verdict at all) falls through to the plain observe-only
@@ -11002,7 +12493,8 @@ async function runGateShadow(job) {
11002
12493
  if (fs.existsSync(path.dirname(verdictsPath))) {
11003
12494
  let existing = {};
11004
12495
  try { existing = JSON.parse(fs.readFileSync(verdictsPath, 'utf8')) || {}; } catch { /* absent/unparseable → fresh */ }
11005
- try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow }); } catch { /* best-effort */ }
12496
+ const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
12497
+ try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
11006
12498
  }
11007
12499
  }
11008
12500
 
@@ -11201,6 +12693,24 @@ const PARK_ERRORS = Object.freeze({
11201
12693
  autofix_plan_unqueued: 'auto-fix investigation produced a fix plan that never reached the queue — parked',
11202
12694
  });
11203
12695
 
12696
+ /**
12697
+ * The artifact evidence persisted on a job row by spawnJob's finalize, but only
12698
+ * when it was captured for `runId` — the run the rescan is re-verifying.
12699
+ * Never throws.
12700
+ * @param {object} job
12701
+ * @param {string} runId
12702
+ * @returns {object|null}
12703
+ */
12704
+ function rescanArtifactEvidence(job, runId) {
12705
+ try {
12706
+ const ev = job?.artifactEvidence;
12707
+ if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return null;
12708
+ return ev.runId === runId ? ev : null;
12709
+ } catch {
12710
+ return null;
12711
+ }
12712
+ }
12713
+
11204
12714
  async function reverifyNeedsReview() {
11205
12715
  const snap = await readQueue();
11206
12716
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -11267,7 +12777,8 @@ async function reverifyNeedsReview() {
11267
12777
  }
11268
12778
  continue;
11269
12779
  }
11270
- const runDir = path.join(schedulerPaths.runsDir(), job.runId || reviewLadder.resolveRunId(job));
12780
+ const rescanRunId = job.runId || reviewLadder.resolveRunId(job);
12781
+ const runDir = path.join(schedulerPaths.runsDir(), rescanRunId);
11271
12782
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
11272
12783
  // Derive committedDuringRun from the recorded run window. The live
11273
12784
  // commit-guard uses gitTreeGuard.gitHead() (before/after HEAD diff); here the run is
@@ -11290,6 +12801,9 @@ async function reverifyNeedsReview() {
11290
12801
  committedDuringRun,
11291
12802
  allowPreSentinelHeal: true,
11292
12803
  priorLandedCommit,
12804
+ // Evidence captured before this run's worktree was removed — only
12805
+ // when it belongs to the run being re-verified.
12806
+ artifactEvidence: rescanArtifactEvidence(job, rescanRunId),
11293
12807
  // job.landedCommit is THIS row's own last-run attribution (stamped by
11294
12808
  // spawnJob's finalize, survives resetJobFields) — the same
11295
12809
  // ground-truth-outranks-heuristics evidence spawnJob passes live,
@@ -11603,7 +13117,13 @@ async function reverifyNeedsReview() {
11603
13117
  const targets = reviewLadder.selectAutoFixTargets(queueForResumeAndAutofix.jobs, {
11604
13118
  fixSlugExists: (s) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${s}.md`))),
11605
13119
  }).filter((job) => job.slug !== gateShadowSlug);
13120
+ // Hold clear: start any investigation a hold deferred for a plain
13121
+ // 'failed' row (spawnInvestigation parked it in deferredInvestigations).
13122
+ if (!currentAutoDispatchHold(queueForResumeAndAutofix.config)) drainDeferredInvestigation();
11606
13123
  for (const job of targets) {
13124
+ // Auto-dispatch hold: check BEFORE the attempt stamp below so a held
13125
+ // row is left un-attempted and this pass picks it up once it clears.
13126
+ if (investigationHold(job.slug, queueForResumeAndAutofix.config)) continue;
11607
13127
  const runId = job.runId || reviewLadder.resolveRunId(job);
11608
13128
  const runDir = path.join(schedulerPaths.runsDir(), runId);
11609
13129
  const isRetryAttempt = job.autoFixAttempted === true;
@@ -11630,7 +13150,7 @@ async function reverifyNeedsReview() {
11630
13150
  }
11631
13151
  });
11632
13152
  console.log(`[scheduler] auto-fix: needs_review ${job.slug} → authoring fix-plan (${isRetryAttempt ? 'retry' : '1/1'}${isDeadFixPlanReopen ? ', dead fix-plan child reopen' : ''})`);
11633
- spawnInvestigation(job, runDir, { deadChild }).catch((e) => {
13153
+ dispatchSpawnInvestigation(job, runDir, { deadChild }).catch((e) => {
11634
13154
  console.error('[scheduler] auto-fix spawnInvestigation error', job.slug, e);
11635
13155
  });
11636
13156
  }
@@ -11794,11 +13314,12 @@ function registerScheduleHandlers() {
11794
13314
  });
11795
13315
 
11796
13316
  ipcMain.handle('schedule:force-tick', async () => {
13317
+ await auditHumanPress('force-tick');
11797
13318
  // Bypass the billing-poll gate entirely — fire pending jobs immediately regardless of meter state.
11798
13319
  // Clears any existing pause first (same semantics as run-now).
11799
13320
  await clearPause('run-now');
11800
13321
  try {
11801
- const result = await runDueJobs({ bypassLoadGate: true });
13322
+ const result = await runDueJobs({ bypassLoadGate: true, human: true });
11802
13323
  return forceTickOutcome(result);
11803
13324
  } catch (e) {
11804
13325
  logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (force-tick)', meta: { error: e?.message } });
@@ -11890,9 +13411,10 @@ function registerScheduleHandlers() {
11890
13411
  }));
11891
13412
 
11892
13413
  ipcMain.handle('schedule:run-now', async () => {
13414
+ await auditHumanPress('run-now');
11893
13415
  // Manual run-now overrides any auto-pause. Clear it first.
11894
13416
  await clearPause('run-now');
11895
- runDueJobs({ bypassLoadGate: true }).catch((e) => logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (run-now)', meta: { error: e?.message } }));
13417
+ runDueJobs({ bypassLoadGate: true, human: true }).catch((e) => logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (run-now)', meta: { error: e?.message } }));
11896
13418
  return { ok: true };
11897
13419
  });
11898
13420
 
@@ -12057,6 +13579,7 @@ function stopDispatchLoop() {
12057
13579
  /** Shutdown path: stop the timers this module owns. */
12058
13580
  function stop() {
12059
13581
  stopDispatchLoop();
13582
+ cancelMemoryBackfill();
12060
13583
  }
12061
13584
 
12062
13585
  // Body of the 10-minute maintenance interval (self-heal, escalations, restores).
@@ -12168,7 +13691,7 @@ function rescheduleIntervalTick() {
12168
13691
  // Escalation only, same shape as the quarantine/overrun warnings above.
12169
13692
  const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
12170
13693
  // Each event names the root blocker; a known preflight wait is skipped.
12171
- reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks);
13694
+ reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks, s.config);
12172
13695
 
12173
13696
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
12174
13697
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -12205,7 +13728,7 @@ function rescheduleIntervalTick() {
12205
13728
  mutate(async (ms) => {
12206
13729
  for (const target of autoResetTargets) {
12207
13730
  const j = ms.jobs.find((x) => x.slug === target.slug);
12208
- if (!j || j.status !== 'failed' || reviewLadder.isCancelledJob(j) || (j.failedAutoResetAttempts ?? 0) >= reviewLadder.FAILED_AUTORESET_CAP) continue; // race guard
13731
+ if (!j || j.status !== 'failed' || isCancelledRow(j) || (j.failedAutoResetAttempts ?? 0) >= reviewLadder.FAILED_AUTORESET_CAP) continue; // race guard
12209
13732
  const attempt = (j.failedAutoResetAttempts ?? 0) + 1;
12210
13733
  j.failedAutoResetAttempts = attempt;
12211
13734
  const reason = `auto-reset after ${Math.round(reviewLadder.FAILED_AUTORESET_MS / 60_000)}m failed (attempt ${attempt}/${reviewLadder.FAILED_AUTORESET_CAP})`;
@@ -12284,6 +13807,9 @@ function _setPeriodicReverifyEnabledForTests(enabled) {
12284
13807
 
12285
13808
  async function init() {
12286
13809
  ensureDirs();
13810
+ // Held scheduler turns (heldSchedulerTurns.cjs) consult the same auto-dispatch
13811
+ // hold tickBody applies — registered before boot reconcile can finish a job.
13812
+ heldSchedulerTurns.setHoldProvider(() => currentAutoDispatchHold(lastSeenConfig));
12287
13813
  // Boot phase — reconciliation, migrations, self-heal, first reset probe.
12288
13814
  // Guarded as a unit: everything below installs the timers that ARE the
12289
13815
  // running scheduler (poll loop, heartbeat, supervisor). A throw in here
@@ -12306,6 +13832,9 @@ async function init() {
12306
13832
  // Hydrate cached state from the sidecar before any scheduling decisions.
12307
13833
  loadSchedulerState();
12308
13834
  bootedAt = Date.now();
13835
+ // Seed the measured memory reservations from the runs folder ~60 s after start,
13836
+ // off the boot path (async batched reads; no-op at ≥ 30 samples).
13837
+ scheduleMemoryBackfill();
12309
13838
 
12310
13839
  // Boot reconciliation: finalize any job that was 'running' when the app died.
12311
13840
  // Check the run log first — a job that emitted result/success before the crash
@@ -12476,6 +14005,10 @@ async function init() {
12476
14005
  });
12477
14006
 
12478
14007
  await rescheduleTimer();
14008
+
14009
+ // Once after boot reconciliation: deliver any turns held across a restart
14010
+ // whose hold has since cleared (never rejects).
14011
+ drainHeldSchedulerTurns();
12479
14012
  } catch (e) {
12480
14013
  console.error('[scheduler] boot phase failed — starting timers anyway:', e?.message);
12481
14014
  try {
@@ -12564,6 +14097,9 @@ function toCompactPrdEntry(entry) {
12564
14097
  // Only when set, so the compact page stays small.
12565
14098
  if (entry.heldReason) out.heldReason = entry.heldReason;
12566
14099
  if (entry.waitingOn) out.waitingOn = entry.waitingOn;
14100
+ // A human-cancelled row keeps status failed/needs_review; the marker is
14101
+ // what tells it apart from a real failure (lib/scheduler/cancelledRow.cjs).
14102
+ if (entry.cancelled === true) out.cancelled = true;
12567
14103
  return out;
12568
14104
  }
12569
14105
 
@@ -12636,6 +14172,7 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12636
14172
  deliverable: parsed.deliverable ?? null,
12637
14173
  artifactPaths: parsed.artifactPaths ?? null,
12638
14174
  effort: parsed.effort ?? null,
14175
+ voiceId: parsed.voiceId ?? null,
12639
14176
  disposition: parsed.disposition ?? null,
12640
14177
  planId: parsed.planId ?? null,
12641
14178
  mtimeMs: stat.mtimeMs,
@@ -12719,6 +14256,9 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12719
14256
  entry.archivedStatus = flatString(prdPaths.resolveArchivedPrdStatus(entry.slug, liveStatusBySlug, histBySlug));
12720
14257
  entry.status = entry.archivedStatus;
12721
14258
  }
14259
+ // Cancelled marker from the shared predicate — only when true, so a real
14260
+ // failure carries no cancelled key at all. No new status.
14261
+ if (isCancelledRow(liveRowBySlug.get(entry.slug))) entry.cancelled = true;
12722
14262
  }
12723
14263
 
12724
14264
  out.sort((a, b) => a.slug.localeCompare(b.slug, undefined, { numeric: true }));
@@ -12934,9 +14474,28 @@ const remote = {
12934
14474
  agentType: j.agentType ?? null,
12935
14475
  epicId: j.epicId ?? null,
12936
14476
  sourcePromptId: j.sourcePromptId ?? null,
14477
+ phase: phaseOfJob(j),
14478
+ ...(isCancelledRow(j) ? { cancelled: true } : {}),
12937
14479
  }));
12938
14480
  },
12939
14481
 
14482
+ // Full queue rows for computeEpicOutsideState (lib/epic/epicOutsideState.cjs
14483
+ // reads cancelledAt, statusHistory, error, finishedAt, reviewNotice). GET
14484
+ // /admin/epic(s) must read the same rows as the tick (full state.jobs), or a cancelled row paints an Epic
14485
+ // 'blocked'. Deep copy, never the live objects — and never project here.
14486
+ async listJobRows() {
14487
+ const state = await readQueue();
14488
+ return JSON.parse(JSON.stringify(Array.isArray(state?.jobs) ? state.jobs : []));
14489
+ },
14490
+
14491
+ // listJobRows after any in-flight mutate() has written queue.json. A mutate
14492
+ // body appends job.status_changed BEFORE writeQueue, so the epic-state
14493
+ // emitter's recompute must wait for the write. Never calls mutate().
14494
+ async listJobRowsSettled() {
14495
+ try { await mutateTail; } catch { /* chain errors are not ours */ }
14496
+ return remote.listJobRows();
14497
+ },
14498
+
12940
14499
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
12941
14500
  // the admin GET /admin/scheduler/prds?slug= route (PRD 1024).
12942
14501
  async getJob(slug) {
@@ -12954,7 +14513,15 @@ const remote = {
12954
14513
  // long as the underlying PRD set doesn't change mid-page.
12955
14514
  async listPrds(filter = {}) {
12956
14515
  const filterCwd = normalizeListCwd(filter.cwd);
12957
- const all = await listPrdsShared({ cwd: filterCwd });
14516
+ // fresh: true (strictly the boolean) skips the single-flight and scans
14517
+ // now. It exists for the PRD-create cross-Epic guard, which reads under a
14518
+ // per-project lock and must never reuse a scan that began before another
14519
+ // create's write (2026-11-24: Bilko PRD 2005 duplicated 2001). In-process
14520
+ // callers only — the admin route never forwards it, since outside callers
14521
+ // piling up full scans is the 2026-11-08 heap incident the single-flight fixed.
14522
+ const all = filter.fresh === true
14523
+ ? await listPrdsInternal({ cwd: filterCwd })
14524
+ : await listPrdsShared({ cwd: filterCwd });
12958
14525
  const filtered = all.filter((entry) => {
12959
14526
  if (filterCwd && entry.cwd !== filterCwd) return false;
12960
14527
  if (filter.epicId && entry.epicId !== filter.epicId) return false;
@@ -13150,9 +14717,11 @@ const remote = {
13150
14717
  let newBody = body !== undefined ? body : origBody;
13151
14718
  let patchWarnings = [];
13152
14719
  if (hasStructured) {
13153
- const patched = applyStructuredPrdPatch(origBody, structured);
14720
+ const patched = applyStructuredPrdPatch(origBody, { ...structured, previousCriteria: fm.criteria });
13154
14721
  if (!patched.ok) return { ok: false, error: patched.error };
13155
14722
  newBody = patched.body;
14723
+ // Structured criteria (prdCriteria.cjs): frontmatter `criteria` follows the re-rendered list.
14724
+ if (patched.criteria) fm.criteria = patched.criteria;
13156
14725
  patchWarnings = patched.warnings || [];
13157
14726
  }
13158
14727
  const newRaw = serializePrdFile(fm, newBody);
@@ -13224,6 +14793,9 @@ const remote = {
13224
14793
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
13225
14794
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
13226
14795
  }
14796
+ // `interrupt: true` asks for a stop that keeps the session resumable
14797
+ // (human.interrupt) instead of a terminal cancel.
14798
+ if (opts.interrupt === true && job.status === 'running') return this.interruptJob(slug, opts);
13227
14799
  // Dependents choice (PRD 3499): cancelling a row that pending PRDs depend
13228
14800
  // on would strand them behind a dead row (Self stall, 2026-11-22). Refuse
13229
14801
  // unless the caller says what happens to them; apply that choice BEFORE
@@ -13315,6 +14887,8 @@ const remote = {
13315
14887
  j.error = cancelReason;
13316
14888
  j.cancelledAt = cancelledAt;
13317
14889
  if (wasRunning) j.cancelledRunId = job.runId ?? null;
14890
+ // A cancel ends an interrupted row for good: it is no longer continuable.
14891
+ delete j.interrupted;
13318
14892
  j.finishedAt = new Date().toISOString();
13319
14893
  j.exitCode = j.exitCode ?? null;
13320
14894
  if (confirmedLandedCommit) j.verifierVerdict = 'cancelled_with_landed_commit';
@@ -13357,6 +14931,107 @@ const remote = {
13357
14931
  return result;
13358
14932
  },
13359
14933
 
14934
+ // Human interrupt (Managed Agents `human.interrupt`): stops a RUNNING job's
14935
+ // process but does not end the job. The row goes back to 'pending' (phase
14936
+ // idle) with an `interrupted` record holding the run's own CLI session id
14937
+ // (row.sessionId — not row.claudeSessionId, which is the ORIGIN Epic's
14938
+ // session), and is held off the picker (computeInterruptHolds) until
14939
+ // continueJob resumes that same session with `--resume <id>`. The run's
14940
+ // worktree work stays on its job branch, never integrated (isRunCancelled).
14941
+ async interruptJob(slug, opts = {}) {
14942
+ if (!SCHEDULE_SLUG_RE.test(slug)) return { ok: false, error: 'invalid slug' };
14943
+ const state = await readQueue();
14944
+ const job = state.jobs.find((j) => j.slug === slug && (!opts.cwd || j.cwd === opts.cwd));
14945
+ if (!job) return { ok: false, error: `unknown slug "${slug}": no queued job with that name${opts.cwd ? ` in cwd ${opts.cwd}` : ''}` };
14946
+ if (job.status !== 'running') {
14947
+ return { ok: false, error: `job status is "${job.status}" — only a running job can be interrupted (use scheduler_cancel_job to drop a queued one)` };
14948
+ }
14949
+ const sessionId = job.runtime?.sessionId || job.sessionId || null;
14950
+ if (!sessionId) return { ok: false, error: 'job has no session id yet (still launching) — try again in a moment, or cancel it' };
14951
+ const pid = job.runtime?.pid;
14952
+ const runId = job.runId ?? null;
14953
+ const interruptedAt = new Date().toISOString();
14954
+ const reason = 'interrupted by a human — waiting for continue';
14955
+ let applied = false;
14956
+ await mutate((s) => {
14957
+ const j = s.jobs.find((x) => x.slug === slug && x.cwd === job.cwd);
14958
+ if (!j || j.status !== 'running' || (j.runId ?? null) !== runId) return;
14959
+ if (!transitionJob(j, 'pending', { reason, source: 'remote:interruptJob' })) return;
14960
+ j.sessionId = sessionId;
14961
+ j.interrupted = { at: interruptedAt, runId, sessionId };
14962
+ j.heldReason = reason;
14963
+ delete j.runtime;
14964
+ applied = true;
14965
+ });
14966
+ if (!applied) return { ok: false, error: 'job changed state while interrupting — re-read it and try again' };
14967
+ // Stamped before SIGTERM so finalizeJobWorktree (run on executor exit)
14968
+ // keeps the work on the job branch instead of integrating it.
14969
+ if (pid) killOrphanClaudePid(pid);
14970
+ emitJobEvent({ ...job, epicId: job.epicId || job.sourcePromptId }, {
14971
+ kind: 'human.interrupt',
14972
+ slug,
14973
+ runId,
14974
+ sessionId,
14975
+ source: typeof opts.source === 'string' ? opts.source : 'scheduler',
14976
+ });
14977
+ appendAuditEvent('job_interrupted', { slug, cwd: job.cwd ?? null, runId, sessionId });
14978
+ await broadcast({ flush: true });
14979
+ return { ok: true, slug, status: 'pending', phase: 'idle', sessionId, interruptedAt, cwd: job.cwd ?? null };
14980
+ },
14981
+
14982
+ // Continue an interrupted job: dispatch the SAME session via
14983
+ // `--resume <interrupted.sessionId>` (spawnJob with a resumeTarget, like
14984
+ // resume recovery and tool-confirmation resumes). Refused while the old
14985
+ // process is still exiting, when no session slot is free, or while the
14986
+ // auto-dispatch hold (usage threshold / firePolicy 'manual') is in force.
14987
+ // No human bypass: the only caller is the loopback admin route, which any
14988
+ // local process holding the admin token can hit, so it cannot prove a
14989
+ // human pressed anything. A refusal leaves the row interrupted, so the same
14990
+ // call succeeds once the hold clears.
14991
+ async continueJob(slug, opts = {}) {
14992
+ if (!SCHEDULE_SLUG_RE.test(slug)) return { ok: false, error: 'invalid slug' };
14993
+ const state = await readQueue();
14994
+ const job = state.jobs.find((j) => j.slug === slug && (!opts.cwd || j.cwd === opts.cwd));
14995
+ if (!job) return { ok: false, error: `unknown slug "${slug}": no queued job with that name${opts.cwd ? ` in cwd ${opts.cwd}` : ''}` };
14996
+ if (job.status !== 'pending' || !job.interrupted) {
14997
+ return { ok: false, error: `job is not interrupted (status: "${job.status}") — nothing to continue` };
14998
+ }
14999
+ const sessionId = job.interrupted.sessionId || job.sessionId || null;
15000
+ if (!sessionId) return { ok: false, error: 'interrupted job has no session id to resume' };
15001
+ if (runningSet.has(slug)) return { ok: false, error: 'the interrupted run is still shutting down — try again in a moment' };
15002
+ if (sessionSlots.availableFor('job') < 1) return { ok: false, error: 'no session slot free right now — try again when a job finishes' };
15003
+ const hold = currentAutoDispatchHold(state.config);
15004
+ if (hold) {
15005
+ appendAuditEvent('job_continue_held', { slug, reason: hold.reason });
15006
+ return {
15007
+ ok: false,
15008
+ error: `usage hold in force: ${hold.detail} - continue again once it clears`,
15009
+ hold: { reason: hold.reason, window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt },
15010
+ };
15011
+ }
15012
+ const target = {
15013
+ sessionId,
15014
+ interrupt: true,
15015
+ dirtyPaths: Array.isArray(job.interrupted.dirtyPaths) ? job.interrupted.dirtyPaths : [],
15016
+ salvagePatch: job.interrupted.salvagePatch || null,
15017
+ message: typeof opts.message === 'string' ? opts.message : null,
15018
+ };
15019
+ await mutate((s) => {
15020
+ const j = s.jobs.find((x) => x.slug === slug && x.cwd === job.cwd);
15021
+ if (!j) return;
15022
+ delete j.interrupted;
15023
+ delete j.heldReason;
15024
+ });
15025
+ appendAuditEvent('job_continued', { slug, cwd: job.cwd ?? null, sessionId });
15026
+ const { runId, dir: runDir } = pickRunDir();
15027
+ const siblingJobs = (await readQueue().catch(() => ({ jobs: [] }))).jobs || [];
15028
+ const fresh = siblingJobs.find((x) => x.slug === slug && x.cwd === job.cwd) || job;
15029
+ // Not awaited: spawnJob runs the whole job (same as tool-confirmation resumes).
15030
+ Promise.resolve(dispatchSpawnJob(fresh, runId, runDir, fresh.cwd || DEFAULT_PROJECT_CWD, target, siblingJobs))
15031
+ .catch((e) => reportSchedulerError('continue after interrupt failed', slug, e));
15032
+ return { ok: true, slug, sessionId, resume: true };
15033
+ },
15034
+
13360
15035
  // Exposes the module-level allocateParallelGroup (PRD 548) to callers that
13361
15036
  // only hold the `remote` object (lib/prd/prdCreate.cjs's create-prd route) —
13362
15037
  // reuses the same allocator the file-based /develop authoring path relies
@@ -13417,6 +15092,29 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
13417
15092
  const result = await remoteObj.resetJob(slug, { force, cwd });
13418
15093
  sendJson(res, 200, result);
13419
15094
  });
15095
+
15096
+ // Interrupt / continue (human.interrupt): stop a running job keeping its
15097
+ // session, then resume that same session with --resume.
15098
+ for (const [route, method] of [['/admin/scheduler/interrupt-job', 'interruptJob'], ['/admin/scheduler/continue-job', 'continueJob']]) {
15099
+ adminHttp.registerRoute('POST', route, async (req, res) => {
15100
+ const raw = await readBody(req);
15101
+ let parsed;
15102
+ try {
15103
+ parsed = raw ? JSON.parse(raw) : {};
15104
+ } catch {
15105
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
15106
+ return;
15107
+ }
15108
+ const slug = parsed && typeof parsed.slug === 'string' ? parsed.slug : null;
15109
+ if (!slug) {
15110
+ sendJson(res, 400, { ok: false, error: 'missing slug' });
15111
+ return;
15112
+ }
15113
+ const cwd = typeof parsed.cwd === 'string' ? parsed.cwd : undefined;
15114
+ const message = typeof parsed.message === 'string' ? parsed.message : undefined;
15115
+ sendJson(res, 200, await remoteObj[method](slug, { cwd, message, source: 'admin-api' }));
15116
+ });
15117
+ }
13420
15118
  }
13421
15119
 
13422
15120
  // queueOps.dismissCancelled needs the serialized queue writer; queueOps
@@ -13431,12 +15129,22 @@ queueOps.bindQueueAccess({
13431
15129
 
13432
15130
  module.exports = {
13433
15131
  PARK_ERRORS,
15132
+ rescanArtifactEvidence,
15133
+ harvestJobArtifacts,
15134
+ jobArtifactRunId,
13434
15135
  applyDepHoldNotices,
13435
15136
  _resetDepHoldNoticesForTests,
13436
15137
  readValidatorGateMs,
13437
15138
  resolveValidatorEstimate,
15139
+ loadValidatorCriteriaContext,
13438
15140
  planJobScope,
13439
15141
  finalizeJobScope,
15142
+ backfillMemoryStats,
15143
+ scheduleMemoryBackfill,
15144
+ cancelMemoryBackfill,
15145
+ MEMORY_BACKFILL_DELAY_MS,
15146
+ heartbeatMemGate,
15147
+ memoryCapFailureReason,
13440
15148
  sampleJobScope,
13441
15149
  readJobCgroupDir,
13442
15150
  normalizeConfig,
@@ -13461,11 +15169,18 @@ module.exports = {
13461
15169
  loadSchedulerState,
13462
15170
  persistSchedulerState,
13463
15171
  getSchedulerStateSnapshot,
15172
+ _getOpenAutoDispatchHoldForTests,
15173
+ _auditHumanPressForTests: auditHumanPress,
15174
+ _forgetOpenAutoDispatchHoldForTests,
13464
15175
  computeDegradedBudget,
15176
+ utilizationReading,
15177
+ usageHoldThreshold,
15178
+ currentUsageHold,
13465
15179
  writeQueue,
13466
15180
  _setPeriodicReverifyEnabledForTests,
13467
15181
  _setLoadGateForTests,
13468
15182
  _setSpawnJobForTests,
15183
+ _setSpawnInvestigationForTests,
13469
15184
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
13470
15185
  reconcile,
13471
15186
  broadcast,
@@ -13484,9 +15199,7 @@ module.exports = {
13484
15199
  pickForProject,
13485
15200
  reapDeadRunningJobs,
13486
15201
  runBranchSweep,
13487
- runEpicStateWatchForTick,
13488
15202
  pollRecoveryClearSource,
13489
- memoryLimitedBatchSize,
13490
15203
  availableForJobs,
13491
15204
  parseMemInfo,
13492
15205
  readMemInfo,
@@ -13535,6 +15248,7 @@ module.exports = {
13535
15248
  applyOrphanOutcome,
13536
15249
  registerAdminRoutes,
13537
15250
  notifyOriginatingTab,
15251
+ drainHeldSchedulerTurns,
13538
15252
  flushDueReviewNotices,
13539
15253
  isNotifiableTerminalStatus,
13540
15254
  armSettleAfterValidatorBudgetKill,
@@ -13550,6 +15264,7 @@ module.exports = {
13550
15264
  resetJobFields,
13551
15265
  resetRefusalMessage,
13552
15266
  executeJob,
15267
+ applyPersonaRefusalPark,
13553
15268
  killOrphanClaudePid,
13554
15269
  prdArchivedSkipResult,
13555
15270
  spawnJob,
@@ -13575,6 +15290,8 @@ module.exports = {
13575
15290
  spawnInvestigation,
13576
15291
  computeLaunchHolds,
13577
15292
  computePreflightHolds,
15293
+ computeInterruptHolds,
15294
+ buildInterruptContinuePreamble,
13578
15295
  runPreflightGate,
13579
15296
  handleLaunchFailure,
13580
15297
  applyLaunchFailure,
@@ -13596,11 +15313,13 @@ module.exports = {
13596
15313
  pickRunDir,
13597
15314
  resolveRateLimitPauseReset,
13598
15315
  billingResetForPause,
15316
+ billingReadingForPause,
13599
15317
  computeEffectiveResumeAt,
13600
15318
  computeResumeDelay,
13601
15319
  FOREIGN_WIP_BLOCK_STREAK_LIMIT,
13602
15320
  validateForeignWipBlockClaim,
13603
15321
  requeueForeignWipBlockedJobs,
15322
+ __test: { bindingWindowPauseThreshold },
13604
15323
  };
13605
15324
 
13606
15325
  // Lazy path getters: resolved from SM_SCHEDULER_HOME at each read, never frozen