claude-code-session-manager 0.141.0 → 0.142.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 (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. 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 } = 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,11 +179,12 @@ 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');
@@ -208,9 +225,10 @@ const { splitFrontmatter, parsePrdFile, serializePrdFile, isArtifactOnlyDeclarat
208
225
  const { applyStructuredPrdPatch } = require('./lib/prd/prdBodyPatch.cjs');
209
226
  const { resolvePersonaDefaultEstimate, DEFAULT_PRD_AGENT_TYPE } = require('./lib/prd/prdAgentType.cjs');
210
227
  const { resolveDepSlug, findNearMatches, bareSlug } = require('./lib/prd/depSlugResolve.cjs');
211
- const { writeJsonAtomic, readJsonOrSync } = require('./lib/util/atomicFs.cjs');
228
+ const { writeJsonAtomic, readJsonOrSync, readJsonOr } = require('./lib/util/atomicFs.cjs');
212
229
  const { writeToolRiskGuardSettingsFile } = require('./lib/epic/guardSpawnSettings.cjs');
213
230
  const toolRiskMarks = require('./lib/claude/toolRiskMarks.cjs');
231
+ const toolClearance = require('./lib/scheduler/toolClearance.cjs');
214
232
  const { computeDispositionRewrite, mintPlanId, resolveInheritedPlanId } = require('./lib/prd/prdDisposition.cjs');
215
233
  const cancelDependents = require('./scheduler/cancelDependents.cjs');
216
234
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
@@ -422,6 +440,82 @@ function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
422
440
  }
423
441
  }
424
442
 
443
+ const ARTIFACT_PLAN_RECORDS_PREFIX = 'session-manager-operations/plan-records/';
444
+
445
+ /**
446
+ * jobArtifactRunId(job, runId) — the staging-folder key for ONE job run. The
447
+ * batch runId (pickRunDir) is shared by every job in a tick, so the job slug
448
+ * is appended; an id the store would refuse falls back to a stable hash.
449
+ */
450
+ function jobArtifactRunId(job, runId) {
451
+ const slug = job && typeof job.slug === 'string' ? job.slug : '';
452
+ const base = [runId, slug].filter((v) => typeof v === 'string' && v).join('-');
453
+ if (base && artifactStore.RUN_ID_RE.test(base)) return base;
454
+ return `job-${require('node:crypto').createHash('sha256').update(base || 'unknown').digest('hex').slice(0, 32)}`;
455
+ }
456
+
457
+ /**
458
+ * harvestJobArtifacts(job, worktreeDir, projectRoot, { runId }) — copy this
459
+ * job's declared artifactPaths (regular files under worktreeDir; plan records
460
+ * excluded — harvestJobPlanRecords owns them) and its SM_ARTIFACTS_DIR staging
461
+ * folder into the project's Artifacts store (artifacts/<epic-id>/, producer
462
+ * prdSlug) before the worktree is removed. Logs, never throws.
463
+ */
464
+ async function harvestJobArtifacts(job, worktreeDir, projectRoot, { runId = job && job.runId } = {}) {
465
+ const slug = job && job.slug;
466
+ try {
467
+ const epicId = job.epicId || job.sourcePromptId;
468
+ if (!epicId || !worktreeDir || !projectRoot) return;
469
+ if (!fs.existsSync(worktreeDir)) {
470
+ console.warn(`[scheduler] ${slug}: artifact harvest skipped — worktree missing: ${worktreeDir}`);
471
+ return;
472
+ }
473
+ const producer = { epicId, prdSlug: slug || null, sessionId: job.sessionId || null };
474
+ const wtBase = path.resolve(worktreeDir);
475
+ let published = 0;
476
+ /** every publish result of this harvest, for the one 'artifact-ready' notice */
477
+ const landed = [];
478
+ const declared = Array.isArray(job.artifactPaths) ? job.artifactPaths : [];
479
+ for (const p of declared) {
480
+ if (typeof p !== 'string' || !p || p.includes('\0')) continue;
481
+ const norm = path.posix.normalize(p.replace(/\\/g, '/'));
482
+ if (norm.startsWith(ARTIFACT_PLAN_RECORDS_PREFIX)) continue;
483
+ const abs = path.resolve(wtBase, p);
484
+ const rel = path.relative(wtBase, abs);
485
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
486
+ console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — outside the worktree`);
487
+ continue;
488
+ }
489
+ let st;
490
+ try { st = fs.lstatSync(abs); } catch { console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — missing`); continue; }
491
+ if (!st.isFile()) { console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — not a regular file`); continue; }
492
+ const res = await artifactStore.publishArtifact({
493
+ projectRoot, epicId, srcPath: abs, producer, allowedRoots: [wtBase],
494
+ });
495
+ if (res.ok) { published += 1; landed.push({ storedPath: res.storedPath, entry: res.entry }); }
496
+ else console.warn(`[scheduler] ${slug}: artifact not harvested: ${p} — ${res.error}`);
497
+ }
498
+ if (runId) {
499
+ let stagingDir = null;
500
+ try { stagingDir = artifactStore.stagingDirFor({ runId: jobArtifactRunId(job, runId) }); } catch (e) {
501
+ console.warn(`[scheduler] ${slug}: artifact staging folder unavailable — ${e && e.message ? e.message : e}`);
502
+ }
503
+ if (stagingDir) {
504
+ const { published: pub, skipped } = await artifactStore.ingestDir({ projectRoot, epicId, srcDir: stagingDir, producer });
505
+ published += pub.length;
506
+ landed.push(...pub);
507
+ for (const sk of skipped) console.warn(`[scheduler] ${slug}: staged artifact not harvested: ${sk.path} — ${sk.reason}`);
508
+ try { fs.rmdirSync(stagingDir); } catch { /* not empty (skipped files) or already gone */ }
509
+ }
510
+ }
511
+ if (published) console.log(`[scheduler] ${slug}: harvested ${published} artifact(s) into ${projectRoot}`);
512
+ // One 'artifact-ready' notice for everything this harvest published (never throws).
513
+ if (landed.length) await postArtifactReadyNotice({ cwd: projectRoot, epicId, entries: landed });
514
+ } catch (e) {
515
+ console.error(`[scheduler] ${slug}: artifact harvest failed`, e);
516
+ }
517
+ }
518
+
425
519
  // Validator jobs only (`--json-schema`): the CLI replaces the result text
426
520
  // with the JSON, so the scheduler reads the verdict from structured output.
427
521
  const FINISH_VALIDATOR_VERDICT_LINE = `
@@ -435,6 +529,10 @@ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPl
435
529
  ${commitStepNum}. COMMIT — stage only the exact paths you created or changed for this PRD,
436
530
  then commit:
437
531
  \`git add <path> [<path>...] && git commit -m "<type>(<scope>): <summary>"\`
532
+ If you found work worth doing outside this PRD's criteria, add one
533
+ \`Follow-up: <one line>\` trailer per item (a second -m), for example:
534
+ \`git commit -m "<type>(<scope>): <summary>" -m "Follow-up: <item>"\`
535
+ Do not do that work.
438
536
  Never stage the whole tree with a wildcard or blanket git add.
439
537
  Why: other jobs may be writing files in this same working tree right now.
440
538
  A blanket add puts their half-done work in your commit and breaks both
@@ -522,14 +620,11 @@ const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
522
620
  const HEARTBEAT_MAX_BYTES = 1024 * 1024;
523
621
  // DEFAULT_PROJECT_CWD imported from lib/scheduler/schedulerBatch.cjs (single source of truth).
524
622
 
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;
623
+ // Per-job memory reservations are MEASURED (lib/scheduler/jobMemoryStats.cjs: p75 for
624
+ // a new job, p50 growth for a running one, one shared spike buffer) and applied by
625
+ // loadGate.measuredMemoryGate in tickBody. The flat 2.5 GB/job rule (raised from 1.5 GB
626
+ // after the 2026-06-16 OOM: 3 concurrent jobs pushed a 24 GB host ~10 GB into swap and
627
+ // the OOM killer took Electron) survives only as jobMemoryStats' too-few-samples fallback.
533
628
 
534
629
  // Absolute headroom kept free for the Electron host (main + renderer + GPU) and
535
630
  // the OS — NEVER lent to jobs. Without it the gate green-lights a job whenever
@@ -621,23 +716,6 @@ function swapLimitedBatchSize(mem, runningCount, batchLen) {
621
716
  return Math.min(batchLen, Math.max(0, 1 - runningCount));
622
717
  }
623
718
 
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
719
  /**
642
720
  * Memory available to LAUNCH jobs with: MemAvailable minus the host reserve,
643
721
  * floored at 0. Keeping the host reserve out of the job budget is what stops the
@@ -678,14 +756,26 @@ const memoryScope = require('./lib/process/memoryScope.cjs');
678
756
  */
679
757
  function planJobScope({ jobSpawn, jobArgs, slug, startedAt, deps = {} }) {
680
758
  // Limits first: with the cap off, never probe systemd.
681
- const limits = (deps.memoryLimitsFor || memoryScope.memoryLimitsFor)({ totalRamMb: Math.floor(os.totalmem() / 1048576) });
759
+ const limits = deps.memoryLimitsFor
760
+ ? deps.memoryLimitsFor({ totalRamMb: Math.floor(os.totalmem() / 1048576) })
761
+ : memoryScope.schedulerJobMemoryLimits();
682
762
  const supported = limits ? (deps.scopeSupported || memoryScope.scopeSupported)() : false;
683
- if (!supported || !limits) return { spawn: jobSpawn, unit: null };
763
+ if (!supported || !limits) return { spawn: jobSpawn, unit: null, memoryMaxMb: null };
684
764
  const unit = `sm-job-${memoryScope.sanitizeUnit(slug)}-${startedAt}`;
685
765
  const wrapped = (deps.wrapInMemoryScope || memoryScope.wrapInMemoryScope)({
686
766
  command: jobSpawn.command, args: jobSpawn.args || jobArgs, unit, limits,
687
767
  });
688
- return { spawn: { ...jobSpawn, command: wrapped.command, args: wrapped.args, argv0: undefined }, unit };
768
+ return { spawn: { ...jobSpawn, command: wrapped.command, args: wrapped.args, argv0: undefined }, unit, memoryMaxMb: limits.memoryMaxMb };
769
+ }
770
+
771
+ /**
772
+ * Failure reason for a job its own scope OOM-killed: the last sampled
773
+ * oom_kill > 0 on a non-zero (or signal) exit. Null otherwise.
774
+ */
775
+ function memoryCapFailureReason(state, exitCode) {
776
+ if (!state || !(Number(state.oomKills) > 0) || exitCode === 0) return null;
777
+ const cap = Number(state.memoryMaxMb) > 0 ? `${Math.round(state.memoryMaxMb / 1024)} GB ` : '';
778
+ return `job hit its ${cap}memory cap (oom_kill=${state.oomKills})`;
689
779
  }
690
780
 
691
781
  /** Reads the job's cgroup dir from /proc/<pid>/cgroup (cgroup v2). Null when unavailable. */
@@ -715,6 +805,78 @@ function sampleJobScope(state, fsImpl = fs) {
715
805
 
716
806
  const JOB_SCOPE_SAMPLE_MS = 30000;
717
807
 
808
+ // Newest run logs the boot backfill reads at most (each read whole; repeats are deduped).
809
+ const MEMORY_BACKFILL_MAX_FILES = 500;
810
+
811
+ /** The heartbeat's view of the last memory-gate decision (deferred or clamped), or null. */
812
+ function heartbeatMemGate(g) {
813
+ if (!g) return null;
814
+ const pick = ['availableMb', 'threshold', 'reservationMb', 'spikeBufferMb', 'runningGrowthMb', 'consumedMb', 'measured', 'deferred', 'clamped', 'at'];
815
+ return Object.fromEntries(pick.filter((k) => g[k] !== undefined).map((k) => [k, g[k]]));
816
+ }
817
+
818
+ /**
819
+ * Seeds the job-memory store from the scheduler runs folder itself
820
+ * (schedulerPaths.runsDir(): <runId>/<slug>.log). jobMemoryStats.backfillFromRunLogs
821
+ * lists at most 2 × MEMORY_BACKFILL_MAX_FILES run folders, reads the newest
822
+ * MEMORY_BACKFILL_MAX_FILES logs in bounded batches, runs only while the store holds
823
+ * fewer than 30 samples, dedupes by run folder + unit, and never rejects. Its store
824
+ * reads, run-log I/O and final store write (atomicFs.writeTextAtomic) are all async;
825
+ * the one synchronous step is re-appending a live recordPeak that landed during that
826
+ * write (see backfillFromRunLogs). `deps.runsDir` defaults to schedulerPaths.runsDir().
827
+ * Resolves to the number of samples added.
828
+ */
829
+ async function backfillMemoryStats(deps = {}) {
830
+ const runsDir = deps.runsDir || schedulerPaths.runsDir();
831
+ const added = await (deps.backfillFromRunLogs || jobMemoryStats.backfillFromRunLogs)(runsDir, { maxFiles: MEMORY_BACKFILL_MAX_FILES });
832
+ if (added > 0) console.log(`[scheduler] memory stats: backfilled ${added} job peak(s) from ${runsDir}`);
833
+ return added;
834
+ }
835
+
836
+ // Delay after scheduler start before the one memory backfill pass (keeps it off the boot path).
837
+ const MEMORY_BACKFILL_DELAY_MS = 60_000;
838
+ let memoryBackfillTimer = null;
839
+ let memoryBackfillPending = null;
840
+ let memoryBackfillSettle = null; // resolves memoryBackfillPending early (cancel)
841
+
842
+ /**
843
+ * Schedules ONE backfillMemoryStats pass MEMORY_BACKFILL_DELAY_MS from now on an
844
+ * unref'd timer, so boot itself never reads run logs. A second call while a pass
845
+ * is pending returns the same promise. Resolves to the samples added (0 on error,
846
+ * 0 when cancelMemoryBackfill() runs first). Scheduling itself does no fs work.
847
+ */
848
+ function scheduleMemoryBackfill(deps = {}) {
849
+ if (memoryBackfillPending) return memoryBackfillPending;
850
+ const delayMs = deps.delayMs ?? MEMORY_BACKFILL_DELAY_MS;
851
+ memoryBackfillPending = new Promise((resolve) => {
852
+ memoryBackfillSettle = resolve;
853
+ memoryBackfillTimer = setTimeout(() => {
854
+ memoryBackfillTimer = null;
855
+ backfillMemoryStats(deps).catch(() => 0).then(resolve);
856
+ }, delayMs);
857
+ if (memoryBackfillTimer.unref) memoryBackfillTimer.unref();
858
+ });
859
+ const pending = memoryBackfillPending.finally(() => {
860
+ if (memoryBackfillPending === pending) { memoryBackfillPending = null; memoryBackfillSettle = null; }
861
+ });
862
+ memoryBackfillPending = pending;
863
+ return pending;
864
+ }
865
+
866
+ /**
867
+ * stop() path: clears a not-yet-fired backfill timer and settles the pending
868
+ * scheduleMemoryBackfill() promise with 0, so no awaiter hangs after stop(). A pass
869
+ * already reading logs is not interrupted (it never rejects and ends on its own);
870
+ * its awaiters still see 0.
871
+ */
872
+ function cancelMemoryBackfill() {
873
+ if (memoryBackfillTimer) { clearTimeout(memoryBackfillTimer); memoryBackfillTimer = null; }
874
+ const settle = memoryBackfillSettle;
875
+ memoryBackfillSettle = null;
876
+ memoryBackfillPending = null;
877
+ if (settle) settle(0);
878
+ }
879
+
718
880
  /** Starts the unref'd 30 s sampler once cgroupDir is known; finalizeJobScope clears it. */
719
881
  function startJobScopeSampling(state, fsImpl = fs) {
720
882
  if (!state || !state.cgroupDir || state.finalized || state.sampler) return;
@@ -723,7 +885,11 @@ function startJobScopeSampling(state, fsImpl = fs) {
723
885
  if (state.sampler.unref) state.sampler.unref();
724
886
  }
725
887
 
726
- /** Logs the last sampled memory.peak + oom_kill to the run log, then stops the scope exactly once. */
888
+ /**
889
+ * Logs the last sampled memory.peak + oom_kill to the run log, records the peak with
890
+ * the job's agentType ('dev-lead' when absent) and run folder (state.runId) through jobMemoryStats.recordPeak (the
891
+ * memory gate's measured reservations), then stops the scope exactly once.
892
+ */
727
893
  function finalizeJobScope(state, safeLog, deps = {}) {
728
894
  if (!state || !state.unit || state.finalized) return;
729
895
  state.finalized = true;
@@ -738,6 +904,13 @@ function finalizeJobScope(state, safeLog, deps = {}) {
738
904
  safeLog(`\n[scheduler] memory scope ${state.unit}: peak=${hasPeak ? `${Math.round(state.peak / 1048576)}MB` : 'n/a'} ` +
739
905
  `oom_kill=${hasOom ? state.oomKills : 'n/a'}\n`);
740
906
  }
907
+ if (hasPeak) {
908
+ const agentType = typeof state.agentType === 'string' && state.agentType ? state.agentType : 'dev-lead';
909
+ (deps.recordPeak || jobMemoryStats.recordPeak)({
910
+ agentType, peakMb: Math.round(state.peak / 1048576), unit: state.unit,
911
+ ...(state.runId ? { runId: state.runId } : {}),
912
+ });
913
+ }
741
914
  } catch { /* stats are best-effort */ }
742
915
  (deps.stopScope || memoryScope.stopScope)(state.unit);
743
916
  }
@@ -885,6 +1058,11 @@ function loadSchedulerState() {
885
1058
  if (typeof s.backoffNextAt === 'number' || s.backoffNextAt === null) backoffNextAt = s.backoffNextAt;
886
1059
  if (typeof s.cachedUtilization === 'number' || s.cachedUtilization === null) cachedUtilization = s.cachedUtilization;
887
1060
  if (typeof s.cachedBindingWindowName === 'string' || s.cachedBindingWindowName === null) cachedBindingWindowName = s.cachedBindingWindowName;
1061
+ // A pre-provenance file has no flag: a restored number was a real reading.
1062
+ cachedUtilizationKnown = typeof s.cachedUtilizationKnown === 'boolean'
1063
+ ? s.cachedUtilizationKnown
1064
+ : typeof cachedUtilization === 'number';
1065
+ restoredUsageWindows = isValidUsageWindowList(s.usageWindows) ? s.usageWindows : null;
888
1066
  } catch { /* first boot or corrupt — start fresh */ }
889
1067
  }
890
1068
 
@@ -893,6 +1071,11 @@ function getSchedulerStateSnapshot() {
893
1071
  return { lastPollOk, lastFailureKind, backoffNextAt, cachedUtilization, cachedBindingWindowName };
894
1072
  }
895
1073
 
1074
+ /** A persisted usageWindows list is trusted only if every entry names a window with a finite percent. */
1075
+ function isValidUsageWindowList(v) {
1076
+ return Array.isArray(v) && v.every((w) => w && typeof w.window === 'string' && Number.isFinite(w.percent));
1077
+ }
1078
+
896
1079
  function persistSchedulerState() {
897
1080
  // Sync write: called from many sync hot paths (clearPause, pollLoop catch
898
1081
  // block) and the sidecar is tiny (<1 KB). Converting to async here would
@@ -929,6 +1112,12 @@ function persistSchedulerState() {
929
1112
  backoffNextAt,
930
1113
  cachedUtilization,
931
1114
  cachedBindingWindowName,
1115
+ // Real reading vs the 100% "no reading ever" placeholder, and every
1116
+ // unscoped window of the last real reading — so a restart during a
1117
+ // non-429 outage (no payload held) still knows weekly_all, not only
1118
+ // the binding session window.
1119
+ cachedUtilizationKnown,
1120
+ usageWindows: utilizationReading().windows,
932
1121
  });
933
1122
  } catch (e) {
934
1123
  console.warn('[scheduler] failed to persist scheduler state', e?.message);
@@ -1241,7 +1430,11 @@ function heartbeatTick(deps = {}) {
1241
1430
  // Which window `utilization` (and nextReset) refer to — a reader of
1242
1431
  // this log can't otherwise tell a 5h hold from a weekly one.
1243
1432
  utilizationWindow: cachedBindingWindowName,
1433
+ utilizationHold,
1244
1434
  consecutiveFailures,
1435
+ // Why a memory-held tick held (PRD 4019): the new job's reservation, the
1436
+ // shared spike buffer and the running jobs' growth term. null = not gated.
1437
+ memGate: heartbeatMemGate(lastMemGate),
1245
1438
  // State/consecutiveFailures/degraded-budget snapshot of the shared
1246
1439
  // usage-meter breaker, so a human reading only the heartbeat log can
1247
1440
  // see the meter's own health apart from the queue's.
@@ -1249,6 +1442,9 @@ function heartbeatTick(deps = {}) {
1249
1442
  state: billing.usageCircuit.state(),
1250
1443
  consecutiveFailures,
1251
1444
  degradedBudget: computeDegradedBudget(),
1445
+ // The cap tickQueue actually applies (degradedBudget above is a
1446
+ // display recompute); null = the full slot pool.
1447
+ appliedConcurrencyCap: degradedConcurrencyCapValue,
1252
1448
  },
1253
1449
  };
1254
1450
  });
@@ -1520,15 +1716,15 @@ async function mutateBody(fn) {
1520
1716
  const parsePrdRaw = prdParser.parsePrdRaw;
1521
1717
  const parsePrd = prdParser.parsePrd;
1522
1718
  // 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.
1719
+ // prdParser caches each dir's listing by its path (validated by that dir's
1720
+ // mtime), so a steady-state pass over N unchanged dirs costs N stats and no
1721
+ // readdir, and two dirs sharing an mtime never see each other's files.
1528
1722
  async function listPrdFiles(skipCwds) {
1529
1723
  ensureDirs();
1530
1724
  const dirs = prdPaths.candidatePrdsDirs();
1531
1725
  const perDir = await Promise.all(dirs.map((dir) => prdParser.listPrdFiles(dir)));
1726
+ // Forget cached folders this pass no longer scans (e.g. a removed Epic's prds/).
1727
+ prdParser.retainPrdDirs(dirs);
1532
1728
  let files = perDir.flat();
1533
1729
  // A quarantined project has no job rows this pass; scanning its PRDs would
1534
1730
  // mint fresh `pending` rows for work that may already be running.
@@ -1544,28 +1740,6 @@ function quarantinedCwdSet(state) {
1544
1740
  return new Set((state?.unreadableCwds ?? []).map((u) => u.cwd));
1545
1741
  }
1546
1742
 
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
1743
  /**
1570
1744
  * Atomically mint a brand-new parallel-group NN for a PRD about to be
1571
1745
  * authored under the given project's own PRDs dir (falls back to
@@ -1971,6 +2145,7 @@ async function reconcilePass(state) {
1971
2145
  deliverable: p.deliverable ?? job.deliverable ?? null,
1972
2146
  artifactPaths: p.artifactPaths ?? job.artifactPaths ?? null,
1973
2147
  effort: p.effort ?? job.effort ?? null,
2148
+ voiceId: p.voiceId ?? job.voiceId ?? null,
1974
2149
  preflight: p.preflight ?? null,
1975
2150
  };
1976
2151
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
@@ -2099,6 +2274,7 @@ async function reconcilePass(state) {
2099
2274
  deliverable: p.deliverable ?? inv.row?.deliverable ?? null,
2100
2275
  artifactPaths: p.artifactPaths ?? inv.row?.artifactPaths ?? null,
2101
2276
  effort: p.effort ?? inv.row?.effort ?? null,
2277
+ voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2102
2278
  preflight: p.preflight ?? null,
2103
2279
  };
2104
2280
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
@@ -2255,6 +2431,7 @@ async function reconcilePass(state) {
2255
2431
  deliverable: p.deliverable ?? null,
2256
2432
  artifactPaths: p.artifactPaths ?? null,
2257
2433
  effort: p.effort ?? null,
2434
+ voiceId: p.voiceId ?? null,
2258
2435
  preflight: p.preflight ?? null,
2259
2436
  status: 'pending',
2260
2437
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
@@ -2344,6 +2521,9 @@ async function reconcilePass(state) {
2344
2521
  }
2345
2522
  } catch { /* stat is best-effort reporting only */ }
2346
2523
  next.push(entry);
2524
+ // The Epic's event log records every queue-row insert (summary only);
2525
+ // fire-and-forget — a failed append is logged, never blocks reconcile.
2526
+ emitJobEvent(entry, { kind: 'job.queued', slug, agentType: entry.agentType ?? null });
2347
2527
  }
2348
2528
  if (uncovered.size > 0) {
2349
2529
  queueStore.bustCwdCache();
@@ -2427,9 +2607,18 @@ async function reconcilePass(state) {
2427
2607
  let cachedNextReset = null; // bare ISO string or null
2428
2608
  let cachedUtilization = null; // binding-window utilization %, 0–100, or null if unknown
2429
2609
  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.
2610
+ // true when cachedUtilization is a real reading (poll, fresh/stale meter cache,
2611
+ // no-meter 0, restored number); false for the 100% "no reading ever" placeholder.
2612
+ let cachedUtilizationKnown = false;
2613
+ // Window list restored from scheduler-state.json — read by utilizationReading()
2614
+ // only while no payload is held (after a restart). Never updated per poll.
2615
+ let restoredUsageWindows = null;
2616
+ // Non-null while tickBody is holding automatic dispatch on the utilization
2617
+ // rule (autoDispatchHold): { window, percent, threshold, resetsAt }. Snapshot-level.
2432
2618
  let utilizationHold = null;
2619
+ // `${reason}|${window}|${percent}` of the hold last logged — the hold line is
2620
+ // written when the hold starts or changes, not on every 30 s tick.
2621
+ let lastAutoDispatchHoldKey = null;
2433
2622
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2434
2623
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2435
2624
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -2487,12 +2676,77 @@ function computeDegradedBudget() {
2487
2676
  */
2488
2677
  function applyDegradedBudget() {
2489
2678
  const budget = computeDegradedBudget();
2490
- cachedUtilization = budget.utilization;
2491
- cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2679
+ if (lastGoodUsagePayload) {
2680
+ cachedUtilization = budget.utilization;
2681
+ cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2682
+ cachedUtilizationKnown = true;
2683
+ } else if (!(cachedUtilizationKnown && Number.isFinite(cachedUtilization))) {
2684
+ // No payload and no real reading ever: the conservative placeholder.
2685
+ cachedUtilization = budget.utilization;
2686
+ cachedBindingWindowName = bindingWindow(lastGoodUsagePayload).name;
2687
+ cachedUtilizationKnown = false;
2688
+ }
2689
+ // else: no payload held (e.g. after a restart) but a known reading was
2690
+ // restored — keep it rather than replacing it with the 100 placeholder.
2492
2691
  degradedConcurrencyCapValue = budget.concurrencyCap;
2493
2692
  return budget;
2494
2693
  }
2495
2694
 
2695
+ /**
2696
+ * The current utilization reading and its provenance. `windows` is derived on
2697
+ * each call: every unscoped window of the held payload, else the list
2698
+ * restored from scheduler-state.json, else null.
2699
+ */
2700
+ /**
2701
+ * The auto-dispatch hold in force right now for `config` (or DEFAULT_CONFIG's
2702
+ * values where config omits them), read over every window of the last real
2703
+ * reading. null = automatic ticks may dispatch.
2704
+ */
2705
+ function currentAutoDispatchHold(config) {
2706
+ const cfg = config || {};
2707
+ return autoDispatchHold.evaluateAutoDispatchHold({
2708
+ firePolicy: cfg.firePolicy ?? DEFAULT_CONFIG.firePolicy,
2709
+ threshold: cfg.utilizationThreshold ?? DEFAULT_CONFIG.utilizationThreshold,
2710
+ reading: utilizationReading(),
2711
+ now: Date.now(),
2712
+ });
2713
+ }
2714
+
2715
+ /**
2716
+ * The auto-fix investigation probe is an automatic `claude -p` too, but it is
2717
+ * launched from spawnJob's failure path and the periodic auto-fix pass, never
2718
+ * through tickBody — so it checks the same hold itself. Returns the hold (and
2719
+ * appends one 'investigation_held' audit event per row per hold) or null.
2720
+ * A deferral stamps nothing on the row: it stays eligible for the periodic
2721
+ * auto-fix pass (selectAutoFixTargets), which launches it once the hold clears.
2722
+ */
2723
+ function investigationHold(slug, config) {
2724
+ const hold = currentAutoDispatchHold(config);
2725
+ if (!hold) {
2726
+ // No hold: the row launches now, so a later hold audits it once again.
2727
+ investigationHeldKeys.delete(slug);
2728
+ return null;
2729
+ }
2730
+ if (noteHeldOnce(investigationHeldKeys, slug, hold)) {
2731
+ console.log(`[scheduler] investigation held for ${slug}: ${hold.reason} — ${hold.detail ?? ''}`);
2732
+ appendAuditEvent('investigation_held', { slug, reason: hold.reason });
2733
+ }
2734
+ return hold;
2735
+ }
2736
+
2737
+ function utilizationReading() {
2738
+ const windows = lastGoodUsagePayload
2739
+ ? usageWindows(lastGoodUsagePayload).map((w) => ({ window: w.name, percent: w.utilization, resetsAt: w.resets_at }))
2740
+ : restoredUsageWindows;
2741
+ return {
2742
+ percent: cachedUtilization,
2743
+ window: cachedBindingWindowName,
2744
+ resetsAt: cachedNextReset,
2745
+ known: cachedUtilizationKnown,
2746
+ windows,
2747
+ };
2748
+ }
2749
+
2496
2750
  /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2497
2751
  async function refreshNextReset() {
2498
2752
  const r = await billing.fetchUsage();
@@ -2506,6 +2760,7 @@ async function refreshNextReset() {
2506
2760
  recordObservedReset(window.resets_at ?? null);
2507
2761
  cachedUtilization = window.utilization;
2508
2762
  cachedBindingWindowName = window.name;
2763
+ cachedUtilizationKnown = true;
2509
2764
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
2510
2765
  return cachedNextReset;
2511
2766
  }
@@ -2784,6 +3039,10 @@ function _setLoadGateForTests(gate) { loadGate = gate; }
2784
3039
  // without forking a real child job (whose completion tick races the next test).
2785
3040
  let dispatchSpawnJob = (...args) => spawnJob(...args);
2786
3041
  function _setSpawnJobForTests(fn) { dispatchSpawnJob = fn || ((...args) => spawnJob(...args)); }
3042
+ // The periodic auto-fix pass launches investigations through this indirection
3043
+ // so a test can record them without forking a real probe child.
3044
+ let dispatchSpawnInvestigation = (...args) => spawnInvestigation(...args);
3045
+ function _setSpawnInvestigationForTests(fn) { dispatchSpawnInvestigation = fn || ((...args) => spawnInvestigation(...args)); }
2787
3046
 
2788
3047
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2789
3048
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2839,26 +3098,15 @@ function applyPauseCleared(wasPaused, token) {
2839
3098
  return token;
2840
3099
  }
2841
3100
 
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
- }
3101
+ // formatLoadGateDetail (the load-deferred tick's lastTick.detail) lives in
3102
+ // lib/scheduler/loadGate.cjs beside the fields it reads.
2856
3103
 
2857
3104
  function loadGateAuditFields(load) {
2858
3105
  return {
2859
3106
  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).
3107
+ // cpuBusy is the decision value: net of the app's own process tree (PRD 3495) and nice-19 processes (PRD 4021).
2861
3108
  cpuBusy: load.cpuBusy, cpuBusyRaw: load.cpuBusyRaw, cpuBusyNet: load.cpuBusyNet, cpuOwnBusy: load.cpuOwnBusy,
3109
+ cpuIdleNice: load.cpuIdleNice,
2862
3110
  cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2863
3111
  };
2864
3112
  }
@@ -2878,7 +3126,12 @@ function attachWindow(w) { mainWindow = w; }
2878
3126
  function buildScheduleStatePayload(state) {
2879
3127
  const payload = {
2880
3128
  config: state.config,
2881
- jobs: state.jobs,
3129
+ // Cancelled rows ship as shallow copies marked `cancelled: true` (the one
3130
+ // rule in lib/scheduler/cancelledRow.cjs) so the renderer never re-derives
3131
+ // it. Copies only — the live rows (and so queue.json) never carry the key.
3132
+ jobs: Array.isArray(state.jobs)
3133
+ ? state.jobs.map((j) => (isCancelledRow(j) ? { ...j, cancelled: true } : j))
3134
+ : state.jobs,
2882
3135
  lastRunAt: state.lastRunAt,
2883
3136
  // Distinct from lastRunAt (only stamped when a batch actually launches):
2884
3137
  // stamped every time tickQueue reaches the picker at all. See
@@ -3216,14 +3469,17 @@ function resetJobFields(job, errorMsg, opts = {}) {
3216
3469
  if ((job.status === 'completed' || job.status === 'skipped') && opts.force !== true) return false;
3217
3470
  // Durable cancel (2026-10-19 git-viewer incident): a human-cancelled row is
3218
3471
  // 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;
3472
+ if (isCancelledRow(job) && opts.source !== 'remote:resetJob' && opts.source !== 'ipc:schedule:reset-job') return false;
3220
3473
  // Reset means "re-check the precondition now": the hold is dropped even
3221
3474
  // when the row is already pending (pending→pending is not a transition).
3222
3475
  delete job.preflightHold;
3223
3476
  if (job.status === 'pending' && typeof job.heldReason === 'string' && job.heldReason.startsWith('waiting on precondition:')) delete job.heldReason;
3477
+ if (job.interrupted && typeof job.heldReason === 'string' && job.heldReason.startsWith('interrupted by a human')) delete job.heldReason;
3224
3478
  if (!transitionJob(job, 'pending', { reason: errorMsg ?? 'reset to pending', source: opts.source ?? 'resetJobFields' })) return false;
3225
3479
  delete job.cancelledAt;
3226
3480
  delete job.cancelledRunId;
3481
+ // A reset restarts from scratch: an interrupted session is not resumed.
3482
+ delete job.interrupted;
3227
3483
  job.runId = null;
3228
3484
  job.startedAt = null;
3229
3485
  job.finishedAt = null;
@@ -3499,6 +3755,31 @@ function applyOrphanOutcomeInner(job, outcome, killNote, confirmedLandedCommit,
3499
3755
  }
3500
3756
  }
3501
3757
 
3758
+ /**
3759
+ * Write the structured outcome record for a just-finalized job and append its
3760
+ * outcome.recorded Epic event (lib/scheduler/prdOutcomeRecord.cjs). Commits =
3761
+ * the landed commit plus any stranded worktree commits; files = the union of
3762
+ * files those commits touch. No Epic id → nothing to record. Never throws.
3763
+ * @param {any} row the finalized job row snapshot
3764
+ * @param {{ verifyResult?: any, landedCommit?: string|null, strandedCommits?: string[], fallbackCwd?: string }} run
3765
+ */
3766
+ async function writeJobOutcomeRecord(row, { verifyResult = null, landedCommit = null, strandedCommits = [], fallbackCwd = DEFAULT_PROJECT_CWD } = {}) {
3767
+ const epicId = row && (row.epicId || row.sourcePromptId);
3768
+ if (!epicId) return;
3769
+ try {
3770
+ const cwd = row.cwd || fallbackCwd;
3771
+ const commits = [...new Set([landedCommit, ...strandedCommits].filter((x) => typeof x === 'string' && x))];
3772
+ const files = await prdOutcomeRecord.listCommitFiles(cwd, commits);
3773
+ const built = prdOutcomeRecord.buildOutcomeFromJob({ job: row, verifyResult, commits, files });
3774
+ await prdOutcomeRecord.writeOutcomeRecord({
3775
+ cwd, epicId, slug: row.slug, ...built,
3776
+ extra: { runId: row.runId ?? null, exitCode: row.exitCode ?? null, terminalReason: row.terminalReason ?? null, finishedAt: row.finishedAt ?? null },
3777
+ });
3778
+ } catch (e) {
3779
+ console.error('[scheduler] outcome record write failed', row && row.slug, e && e.message ? e.message : e);
3780
+ }
3781
+ }
3782
+
3502
3783
  /**
3503
3784
  * isNotifiableTerminalStatus(effectiveStatus) → boolean
3504
3785
  *
@@ -3685,6 +3966,64 @@ async function resolveValidatorEstimate(job, { readGateMs = readValidatorGateMs
3685
3966
  }
3686
3967
  }
3687
3968
 
3969
+ /**
3970
+ * Stored mechanical check results of one judged PRD: the `checks` of its
3971
+ * outcome record (prdOutcomeRecord.cjs), exact slug first, then a bare-slug
3972
+ * match in the Epic's outcomes/ folder. [] when none. Never rejects.
3973
+ */
3974
+ async function readStoredCriteriaChecks(cwd, epicId, slug) {
3975
+ try {
3976
+ const exact = await readJsonOr(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug), null);
3977
+ if (exact && Array.isArray(exact.checks)) return exact.checks;
3978
+ const dir = path.dirname(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug));
3979
+ const want = bareSlug(slug);
3980
+ const names = (await fsp.readdir(dir).catch(() => [])).filter((n) => n.endsWith('.json')).sort().reverse();
3981
+ for (const n of names) {
3982
+ const s = n.slice(0, -'.json'.length);
3983
+ if (s === slug || bareSlug(s) !== want) continue;
3984
+ const rec = await readJsonOr(path.join(dir, n), null);
3985
+ if (rec && Array.isArray(rec.checks)) return rec.checks;
3986
+ }
3987
+ } catch { /* unsafe id / unreadable → no stored checks */ }
3988
+ return [];
3989
+ }
3990
+
3991
+ /**
3992
+ * loadValidatorCriteriaContext(job) → { expected, section } for a validator
3993
+ * job: per judged PRD (job.dependsOn) with frontmatter `criteria`, the
3994
+ * { ids, failedIds } parseValidatorVerdict cross-checks against, and the
3995
+ * prompt section listing each criterion's stored check result. Empty when
3996
+ * nothing is structured. Never rejects.
3997
+ * @param {any} job
3998
+ * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
3999
+ */
4000
+ async function loadValidatorCriteriaContext(job) {
4001
+ /** @type {Record<string, { ids: string[], failedIds: string[] }>} */
4002
+ const expected = {};
4003
+ try {
4004
+ if (!job || job.agentType !== 'validator' || !Array.isArray(job.dependsOn) || !job.dependsOn.length) return { expected, section: '' };
4005
+ const epicId = job.epicId || job.sourcePromptId;
4006
+ if (!job.cwd || !isSafeEpicId(epicId)) return { expected, section: '' };
4007
+ const texts = await prdPaths.readEpicPrdTexts(job.cwd, epicId, job.dependsOn);
4008
+ const prds = [];
4009
+ for (const slug of job.dependsOn) {
4010
+ const text = texts.get(slug);
4011
+ if (typeof text !== 'string') continue;
4012
+ let criteria = null;
4013
+ try { criteria = parsePrdFile(text).frontmatter.criteria; } catch { criteria = null; }
4014
+ if (!Array.isArray(criteria) || !criteria.length) continue;
4015
+ const checks = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4016
+ const exp = expectedFromCriteria(criteria, checks);
4017
+ if (exp) expected[slug] = exp;
4018
+ prds.push({ slug, criteria, checks });
4019
+ }
4020
+ return { expected, section: formatCriteriaChecksSection(prds) };
4021
+ } catch (e) {
4022
+ console.error('[scheduler] loadValidatorCriteriaContext error', job && job.slug, e && e.message ? e.message : e);
4023
+ return { expected, section: '' };
4024
+ }
4025
+ }
4026
+
3688
4027
  function defaultScheduleSettle({ cwd, epicId }) {
3689
4028
  const deps = {
3690
4029
  loadJobs: async () => (await readQueue()).jobs || [],
@@ -3885,6 +4224,7 @@ async function notifyOriginatingTab(job, {
3885
4224
  readStructuredFromLog = extractStructuredOutputFromLog,
3886
4225
  writeVerdictsFile = writeJsonAtomic,
3887
4226
  scheduleSettle = defaultScheduleSettle,
4227
+ loadValidatorCriteria = loadValidatorCriteriaContext,
3888
4228
  } = {}) {
3889
4229
  try {
3890
4230
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -3979,7 +4319,17 @@ async function notifyOriginatingTab(job, {
3979
4319
  } catch (e) {
3980
4320
  console.error('[scheduler] notifyOriginatingTab readStructuredFromLog error', job?.slug, e);
3981
4321
  }
3982
- const checked = parseValidatorVerdict(structured);
4322
+ // Cross-check per-criterion entries against the judged PRDs' frontmatter
4323
+ // criteria + stored check results: a missing id or met-on-failed-check
4324
+ // refuses the whole verdict.
4325
+ let expected = null;
4326
+ try {
4327
+ const ctx = await loadValidatorCriteria(job);
4328
+ if (ctx && ctx.expected && Object.keys(ctx.expected).length) expected = ctx.expected;
4329
+ } catch (e) {
4330
+ console.error('[scheduler] notifyOriginatingTab loadValidatorCriteria error', job?.slug, e);
4331
+ }
4332
+ const checked = parseValidatorVerdict(structured, { expected });
3983
4333
  if (checked.ok) {
3984
4334
  checkedVerdict = checked.value;
3985
4335
  verdicts = verdictRowsFromStructured(checked.value);
@@ -4032,14 +4382,19 @@ async function notifyOriginatingTab(job, {
4032
4382
  } else if (epicId && checkedVerdict && job.cwd) {
4033
4383
  // PRD 3614: keep the checked object beside the Markdown plan record.
4034
4384
  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,
4385
+ // Writes the file, then appends validator.verdict to the Epic's event log.
4386
+ await saveValidatorVerdicts({
4387
+ cwd: job.cwd,
4388
+ epicId,
4389
+ validateSlug: bareSlug(job.slug),
4390
+ write: writeVerdictsFile,
4391
+ record: {
4392
+ validator: job.slug,
4393
+ runId: job.runId || null,
4394
+ at: new Date().toISOString(),
4395
+ schedulerVerdict: checkedVerdict.schedulerVerdict,
4396
+ verdicts: checkedVerdict.verdicts,
4397
+ },
4043
4398
  });
4044
4399
  } catch (e) {
4045
4400
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
@@ -4646,6 +5001,40 @@ async function requeueForeignWipBlockedJobs(jobs, { getDirtyPaths = gitTreeGuard
4646
5001
  * exact paths recorded on the parked job row so the resumed run can verify
4647
5002
  * them on disk before trusting them, rather than re-deriving them itself.
4648
5003
  */
5004
+ /**
5005
+ * Prompt for a session resumed after the owner approved a tool-risk 'confirm'
5006
+ * request (toolClearance.cjs). The session already holds its PRD; this only
5007
+ * says that ONE exact call (same arguments) is now cleared, once.
5008
+ */
5009
+ function buildConfirmationResumePreamble({ tool, summary }) {
5010
+ const what = summary && summary !== tool ? `${tool}: ${summary}` : tool;
5011
+ 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.
5012
+
5013
+ 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).
5014
+ `;
5015
+ }
5016
+
5017
+ /**
5018
+ * Prompt for a session continued after a human interrupt (remote.interruptJob
5019
+ * → remote.continueJob). The session already holds its PRD and everything it
5020
+ * did before the stop; this only says it was paused, not failed.
5021
+ * @param {{ dirtyPaths?: string[], salvagePatch?: string | null, message?: string | null }} args
5022
+ */
5023
+ function buildInterruptContinuePreamble({ dirtyPaths, salvagePatch, message } = {}) {
5024
+ const paths = Array.isArray(dirtyPaths) ? dirtyPaths : [];
5025
+ const pathBlock = paths.length
5026
+ ? `\nThese path(s) were uncommitted when the run stopped:\n${paths.map((p) => `- ${p}`).join('\n')}\n`
5027
+ : '';
5028
+ const salvageLine = salvagePatch
5029
+ ? `A patch of that uncommitted work was saved at: ${salvagePatch} — apply it if any of those paths are missing from the working tree.\n`
5030
+ : '';
5031
+ const note = typeof message === 'string' && message.trim() ? `\nThe owner adds: ${message.trim()}\n` : '';
5032
+ 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.
5033
+ ${pathBlock}${salvageLine}${note}
5034
+ 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).
5035
+ `;
5036
+ }
5037
+
4649
5038
  function buildResumeRecoveryPreamble({ dirtyPaths, salvagePatch }) {
4650
5039
  const pathList = dirtyPaths.map((p) => `- ${p}`).join('\n');
4651
5040
  const salvageLine = salvagePatch
@@ -5094,7 +5483,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5094
5483
  return out;
5095
5484
  }
5096
5485
 
5097
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5486
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5098
5487
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5099
5488
  let riskArgs = [];
5100
5489
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5107,7 +5496,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5107
5496
  '--model', model,
5108
5497
  ...effortArgs(effort),
5109
5498
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5110
- ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
5499
+ // Always strict: exactly the persona's resolved servers (dispatch already
5500
+ // parked any job whose set names an unknown server — capability_unknown).
5501
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers(), declaredServers: mcpServerNames }).args,
5111
5502
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5112
5503
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5113
5504
  ...riskArgs,
@@ -5200,6 +5591,162 @@ function ensureTimeoutShimOnce() {
5200
5591
  return timeoutShimEnsured;
5201
5592
  }
5202
5593
 
5594
+ /**
5595
+ * Resolve the persona a job spawns as, via its AgentSnapshot.
5596
+ * Stamped row (job.agentSnapshotId) → readAgentSnapshot; null (missing or
5597
+ * tampered) → refusal agent_snapshot_missing. Unstamped → buildAgentSnapshot
5598
+ * (persona refusals pass through unchanged), writeAgentSnapshot, and stamp
5599
+ * job.agentSnapshotId in memory (spawnJob's onPid mutate persists it).
5600
+ * A store write failure is logged and the job spawns unpinned. Never throws.
5601
+ * Declared capabilities (ma-persona-declared-capabilities): an unpinned build
5602
+ * records the RESOLVED set in the snapshot — mcpServers = the persona's
5603
+ * `mcpServers:` plus its tool-named servers, packs = the Epic's packs plus the
5604
+ * persona's `packs:` — and every spawn (pinned or not) loads exactly the
5605
+ * snapshot's set.
5606
+ * @param {any} job
5607
+ * @param {string} cwd
5608
+ * @param {string[]|undefined} packs
5609
+ * @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 }>}
5610
+ */
5611
+ async function resolveJobAgentSnapshot(job, cwd, packs) {
5612
+ if (typeof job.agentSnapshotId === 'string' && job.agentSnapshotId) {
5613
+ const snap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
5614
+ if (!snap) {
5615
+ return { refusal: { code: 'agent_snapshot_missing', detail: `pinned agent snapshot ${job.agentSnapshotId} is missing or does not match its id` } };
5616
+ }
5617
+ return {
5618
+ refusal: null,
5619
+ systemPrompt: snap.body || null,
5620
+ model: snap.model || agentModelResolve.FALLBACK_MODEL,
5621
+ tools: Array.isArray(snap.tools) ? snap.tools : null,
5622
+ mcpServers: Array.isArray(snap.mcpServers) ? snap.mcpServers.map(String) : [],
5623
+ packs: Array.isArray(snap.packs) ? snap.packs.map(String) : [],
5624
+ personaPath: null,
5625
+ agentSnapshotId: job.agentSnapshotId,
5626
+ pinned: true,
5627
+ };
5628
+ }
5629
+ let built;
5630
+ try {
5631
+ built = await agentSnapshot.buildAgentSnapshot({ cwd, agentType: job.agentType, packs });
5632
+ } catch (err) {
5633
+ console.error(`[scheduler] agent snapshot build failed for ${job.slug}: ${err?.message ?? err}`);
5634
+ return { refusal: { code: 'persona_invalid', detail: `agent snapshot build failed: ${err?.message ?? err}` } };
5635
+ }
5636
+ if (built.refusal) return { refusal: built.refusal };
5637
+ const declared = readPersonaDeclaredCapabilities(cwd, job.agentType);
5638
+ const resolvedPacks = [];
5639
+ for (const p of [...(Array.isArray(built.snapshot.packs) ? built.snapshot.packs : []), ...declared.packs]) {
5640
+ if (!resolvedPacks.includes(String(p))) resolvedPacks.push(String(p));
5641
+ }
5642
+ const snap = {
5643
+ ...built.snapshot,
5644
+ mcpServers: resolvedMcpServerNames(built.snapshot.tools, [...(built.snapshot.mcpServers || []), ...declared.mcpServers]),
5645
+ packs: resolvedPacks,
5646
+ };
5647
+ let id = null;
5648
+ try {
5649
+ id = (await agentSnapshot.writeAgentSnapshot(cwd, snap)).id;
5650
+ job.agentSnapshotId = id;
5651
+ } catch (err) {
5652
+ console.error(`[scheduler] agent snapshot write failed for ${job.slug} (spawning unpinned): ${err?.message ?? err}`);
5653
+ }
5654
+ return {
5655
+ refusal: null,
5656
+ systemPrompt: snap.body || null,
5657
+ model: snap.model || agentModelResolve.FALLBACK_MODEL,
5658
+ tools: snap.tools,
5659
+ mcpServers: snap.mcpServers,
5660
+ packs: snap.packs,
5661
+ personaPath: null,
5662
+ agentSnapshotId: id,
5663
+ pinned: false,
5664
+ };
5665
+ }
5666
+
5667
+ /**
5668
+ * The persona's declared `mcpServers:` / `packs:` (agentLibrary.cjs's
5669
+ * parseCapabilityList), via the same overlay-aware reader the snapshot uses.
5670
+ * A missing/unreadable persona → both empty (the snapshot build already
5671
+ * refused that case). Never throws.
5672
+ * @param {string} cwd
5673
+ * @param {string|null|undefined} agentType
5674
+ * @returns {{ mcpServers: string[], packs: string[] }}
5675
+ */
5676
+ function readPersonaDeclaredCapabilities(cwd, agentType) {
5677
+ try {
5678
+ const persona = agentModelResolve.readOverlayAwarePersona(agentType || agentModelResolve.DEFAULT_PRD_AGENT_TYPE, { cwd });
5679
+ const fm = (persona && persona.fm) || {};
5680
+ const { parseCapabilityList } = require('./agentLibrary.cjs');
5681
+ return { mcpServers: parseCapabilityList(fm.mcpServers), packs: parseCapabilityList(fm.packs) };
5682
+ } catch {
5683
+ return { mcpServers: [], packs: [] };
5684
+ }
5685
+ }
5686
+
5687
+ /**
5688
+ * The environment profile a job's sandbox is derived from: the persona's
5689
+ * declared `environment:` frontmatter, else jobSandboxPolicy's legacy
5690
+ * persona default (validator → validator-readonly, dev-lead →
5691
+ * headless-default), else null (tool rules). A declared name that does not
5692
+ * resolve is logged and falls back to null — the unpinned snapshot build
5693
+ * already refuses it, so this only matters for pinned rows. Never throws.
5694
+ * @param {string} cwd
5695
+ * @param {string} agentType
5696
+ * @param {(line: string) => void} [log]
5697
+ * @returns {{ id: string, profile: any }|null}
5698
+ */
5699
+ function resolveJobEnvironment(cwd, agentType, log) {
5700
+ let declared = null;
5701
+ try {
5702
+ const persona = agentModelResolve.readOverlayAwarePersona(agentType || agentModelResolve.DEFAULT_PRD_AGENT_TYPE, { cwd });
5703
+ const fm = (persona && persona.fm) || {};
5704
+ if (typeof fm.environment === 'string' && fm.environment.trim()) declared = fm.environment.trim();
5705
+ } catch { /* no persona file → legacy default */ }
5706
+ const name = jobEnvironmentName({ agentType, declared });
5707
+ if (!name) return null;
5708
+ try {
5709
+ const env = loadEnvironment({ cwd, name });
5710
+ if ('code' in env) {
5711
+ if (log) log(`[scheduler] environment ${name}: ${env.code}; sandbox falls back to tool rules\n`);
5712
+ return null;
5713
+ }
5714
+ return { id: env.id, profile: env.profile };
5715
+ } catch (e) {
5716
+ if (log) log(`[scheduler] environment ${name} load failed (${(e && e.message) || e}); tool rules\n`);
5717
+ return null;
5718
+ }
5719
+ }
5720
+
5721
+ /**
5722
+ * Parks one queue row whose persona was refused at dispatch (agentModelResolve.cjs's
5723
+ * resolvePrdPersonaForSpawn `refusal`) — needs_review via transitionJob with
5724
+ * reason '<code>: <detail>'. The job never spawned, so there is no verify
5725
+ * pass, commit guard or transcript. Returns transitionJob's result.
5726
+ * @param {any} row
5727
+ * @param {{ code: string, detail: string }} refusal
5728
+ * @returns {boolean}
5729
+ */
5730
+ function applyPersonaRefusalPark(row, refusal) {
5731
+ const reason = `${refusal.code}: ${refusal.detail}`;
5732
+ if (!transitionJob(row, 'needs_review', { reason, source: 'executeJob:persona-refusal' })) return false;
5733
+ row.finishedAt = new Date().toISOString();
5734
+ row.exitCode = -1;
5735
+ row.error = reason;
5736
+ row.terminalReason = refusal.code;
5737
+ delete row.runtime;
5738
+ return true;
5739
+ }
5740
+
5741
+ /** Persists applyPersonaRefusalPark for `job`'s queue row, then broadcasts. */
5742
+ async function parkPersonaRefusal(job, refusal) {
5743
+ await mutate((s) => {
5744
+ const idx = s.jobs.findIndex((x) => x.slug === job.slug);
5745
+ if (idx >= 0) applyPersonaRefusalPark(s.jobs[idx], refusal);
5746
+ });
5747
+ await broadcast({ flush: true });
5748
+ }
5749
+
5203
5750
  /**
5204
5751
  * Execute a single PRD job. Writes stdout/stderr to a log file and a meta
5205
5752
  * JSON sidecar. Accepts an optional onPid(pid) callback called synchronously
@@ -5285,7 +5832,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5285
5832
  // session already has that in its own conversation history via
5286
5833
  // --resume, and re-embedding it here would just contradict whatever
5287
5834
  // state the session actually left on disk.
5288
- prompt = buildResumeRecoveryPreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch });
5835
+ prompt = resumeTarget.confirmation
5836
+ ? buildConfirmationResumePreamble(resumeTarget.confirmation)
5837
+ : resumeTarget.interrupt
5838
+ ? buildInterruptContinuePreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch, message: resumeTarget.message })
5839
+ : buildResumeRecoveryPreamble({ dirtyPaths: resumeTarget.dirtyPaths, salvagePatch: resumeTarget.salvagePatch });
5289
5840
  } else {
5290
5841
  // Read full PRD body fresh from disk (queue stored only the preview).
5291
5842
  // Resolve through findPrdDirForJob's full candidate search (legacy flat
@@ -5451,6 +6002,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5451
6002
  isArtifactOnly = false;
5452
6003
  }
5453
6004
  }
6005
+ // Validator: list each judged PRD's structured criteria with their stored
6006
+ // mechanical check results, so its per-criterion verdict entries use the
6007
+ // same ids and never mark a failed check met (parseValidatorVerdict refuses that).
6008
+ if (job.agentType === 'validator') {
6009
+ const { section } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6010
+ if (section) prompt = `${prompt}\n\n${section}`;
6011
+ }
5454
6012
  prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
5455
6013
 
5456
6014
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
@@ -5477,10 +6035,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5477
6035
  // PRD agentType → persona + model (PRD 1115): resolved for both fresh and
5478
6036
  // resume dispatches, keyed off job.agentType (persisted on the queue row
5479
6037
  // 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 });
6038
+ // must keep launching as the SAME persona it started as. Never throws.
6039
+ // An absent agentType resolves as 'dev-lead'; a persona that is missing,
6040
+ // unreadable or fails its frontmatter schema is a REFUSAL — the job is
6041
+ // never spawned, and the caller parks it needs_review with the reason.
6042
+ // AgentSnapshot pin (ma-agent-snapshot-pin-dispatch): the persona body,
6043
+ // model and tools come from an immutable, content-addressed snapshot
6044
+ // (agentSnapshot.cjs). A row already stamped with agentSnapshotId (a
6045
+ // resume, or any later dispatch of the same row) re-runs exactly that
6046
+ // snapshot — never the live persona file, which may have been edited since.
6047
+ // An unstamped row builds one (same persona resolution + refusal as
6048
+ // before), writes it once, and stamps job.agentSnapshotId (persisted on the
6049
+ // queue row by spawnJob's onPid mutate). A pinned snapshot that is missing
6050
+ // or tampered (readAgentSnapshot → null) parks agent_snapshot_missing.
6051
+ const packEpicId = job.epicId || job.sourcePromptId;
6052
+ let packEpic = null;
6053
+ try { packEpic = packEpicId ? agentModelResolve.findEpicById(cwd, packEpicId) : null; } catch { packEpic = null; }
6054
+ const personaResolution = await resolveJobAgentSnapshot(job, cwd, packEpic?.packs);
6055
+ if (personaResolution.refusal) {
6056
+ const { code, detail } = personaResolution.refusal;
6057
+ const refusalError = `${code}: ${detail}`;
6058
+ safeLog(`[scheduler] persona refused for ${job.slug} — not spawned: ${refusalError}\n`);
6059
+ closeFd();
6060
+ 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 });
6061
+ return { exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } };
6062
+ }
5484
6063
  if (resumeTarget) {
5485
6064
  try {
5486
6065
  const dir = await prdPaths.findPrdDirForJob(job);
@@ -5510,21 +6089,47 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5510
6089
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5511
6090
  // capped) persona body — the persona cap never applies to laws. Fresh and
5512
6091
  // resume spawns alike; no Epic / no packs / an error = today's argv.
6092
+ // Persona-declared packs (`packs:`, recorded in the snapshot) load with the
6093
+ // Epic's. An unknown persona-declared pack parks the job (below); an
6094
+ // unknown Epic pack keeps being skipped (it was picked by a human at mint).
6095
+ const epicPackIds = Array.isArray(packEpic?.packs) ? packEpic.packs.map(String) : [];
6096
+ const personaPackIds = (personaResolution.packs || []).filter((p) => !epicPackIds.includes(p));
6097
+ const jobPackIds = [...epicPackIds, ...personaPackIds];
5513
6098
  let packArgs = { pluginDirArgs: [], laws: '' };
6099
+ /** @type {string[]|null} null = catalog unavailable (no pack refusal) */
6100
+ let unknownPacks = null;
5514
6101
  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 });
6102
+ const composed = packSpawnArgs.composePackSpawnArgs({ packIds: jobPackIds.length ? jobPackIds : packEpic?.packs });
5518
6103
  if (composed && Array.isArray(composed.pluginDirArgs)) {
5519
6104
  packArgs = { pluginDirArgs: composed.pluginDirArgs, laws: typeof composed.laws === 'string' ? composed.laws : '' };
6105
+ unknownPacks = Array.isArray(composed.unknown) ? composed.unknown.map(String) : [];
5520
6106
  }
5521
6107
  } catch (err) {
5522
6108
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
5523
6109
  }
6110
+ // Declared capabilities, fail-closed: an MCP server (declared or tool-named)
6111
+ // missing from knownMcpServers(), or an unknown persona-declared pack,
6112
+ // parks the job needs_review 'capability_unknown: <name>' — never spawned
6113
+ // with a widened (every-server) config.
6114
+ const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6115
+ mcpServers: knownMcpServers(),
6116
+ declaredServers: personaResolution.mcpServers || [],
6117
+ packs: unknownPacks ? personaPackIds : [],
6118
+ knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6119
+ });
6120
+ if (capabilityCheck.refusal) {
6121
+ const code = capabilityCheck.refusal.code;
6122
+ const detail = capabilityCheck.refusal.name;
6123
+ const refusalError = `${code}: ${detail}`;
6124
+ safeLog(`[scheduler] capability refused for ${job.slug} — not spawned: ${refusalError}\n`);
6125
+ closeFd();
6126
+ 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 });
6127
+ return { exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } };
6128
+ }
5524
6129
  const jobSystemPrompt = packArgs.laws
5525
6130
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
5526
6131
  : 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`);
6132
+ 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
6133
 
5529
6134
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
5530
6135
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -5557,6 +6162,18 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5557
6162
  // `launchEnv` is the launch circuit breaker's degraded-mode env (e.g.
5558
6163
  // MAX_THINKING_TOKENS=0 while an outdated CLI's thinking parameter is
5559
6164
  // being rejected — lib/scheduler/launchFailure.cjs); applied last so it wins.
6165
+ // Wall-clock budget, computed once: the budget watchdog below reads these
6166
+ // same values, and SM_SCHEDULER_JOB_DEADLINE_MS hands the child the epoch
6167
+ // ms at which that watchdog stops the job, so a tool it runs (e.g. a
6168
+ // batch voice render) can stop cleanly first. budgetExempt → no deadline.
6169
+ const budgetEstimate = budget.resolveBudgetEstimate({
6170
+ estimateMinutes: job.estimateMinutes,
6171
+ validatorEstimate,
6172
+ personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
6173
+ });
6174
+ const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
6175
+ const budgetExempt = budget.isJobBudgetExempt(job);
6176
+ const jobVoiceId = (typeof job.voiceId === 'string' && VOICE_ID_RE.test(job.voiceId)) ? job.voiceId : null;
5560
6177
  const childEnv = cleanChildEnv({
5561
6178
  PATH: withTimeoutShimOnPath(pathWithUserBins()),
5562
6179
  SM_PROJECT_ROOT: cwd,
@@ -5564,10 +6181,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5564
6181
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5565
6182
  ...personaToolScopeEnv(personaToolScope),
5566
6183
  SM_SCHEDULER_JOB_RISK_TOOLS: JSON.stringify(jobRiskTools),
6184
+ // Names the Epic a tool-risk 'confirm' request belongs to (guard-tool-risk-policy.cjs).
6185
+ ...((job.epicId || job.sourcePromptId) ? { SM_SCHEDULER_JOB_EPIC_ID: job.epicId || job.sourcePromptId } : {}),
5567
6186
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5568
6187
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
6188
+ ...(budgetExempt ? {} : { SM_SCHEDULER_JOB_DEADLINE_MS: String(Date.now() + jobBudgetMs) }),
6189
+ // The PRD's library voice (frontmatter voiceId) for a voiced tool the job runs; only a valid id, never otherwise.
6190
+ ...(jobVoiceId ? { SM_VOICE_ID: jobVoiceId } : {}),
5569
6191
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
5570
6192
  });
6193
+ // cleanChildEnv inherits process.env; a job without a valid voiceId must never carry one.
6194
+ if (!jobVoiceId) delete childEnv.SM_VOICE_ID;
5571
6195
  // Set AFTER cleanChildEnv returns, never inside the object passed to it:
5572
6196
  // cleanChildEnv strips every CLAUDE_CODE_*-prefixed key from its own
5573
6197
  // merged result (see cleanEnv.cjs), so setting it there would delete its
@@ -5575,6 +6199,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5575
6199
  // it starts has nothing to report back to — same stall as a tool that
5576
6200
  // waits for one.
5577
6201
  childEnv.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = '1';
6202
+ // This run's artifact staging folder; harvestJobArtifacts ingests it
6203
+ // into the Artifacts store before the worktree is removed.
6204
+ try {
6205
+ childEnv.SM_ARTIFACTS_DIR = artifactStore.stagingDirFor({ runId: jobArtifactRunId(job, path.basename(runDir)) });
6206
+ } catch (e) {
6207
+ safeLog(`[scheduler] ${job.slug}: SM_ARTIFACTS_DIR not set — ${e && e.message ? e.message : e}\n`);
6208
+ }
5578
6209
  if (launchEnv && Object.keys(launchEnv).length) {
5579
6210
  safeLog(`[scheduler] launch mitigation env applied: ${Object.entries(launchEnv).map(([k, v]) => `${k}=${v}`).join(' ')}\n`);
5580
6211
  }
@@ -5683,13 +6314,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5683
6314
  // is calibrated against). Only a PRD with an
5684
6315
  // explicit `budgetExempt: true` opts out entirely — logged once here so
5685
6316
  // 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);
6317
+ // budgetEstimate / jobBudgetMs / budgetExempt are computed once above,
6318
+ // before childEnv, so SM_SCHEDULER_JOB_DEADLINE_MS matches this watchdog.
5693
6319
  if (budgetExempt) {
5694
6320
  safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
5695
6321
  `(budgetExempt) — no wall-clock kill ceiling this run\n`);
@@ -5741,9 +6367,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5741
6367
  // never move it under the run directory.
5742
6368
  const sandboxDeps = resolveJobSandboxDeps();
5743
6369
  const sandboxAgentType = job.agentType || 'dev-lead';
6370
+ const jobEnvironment = resolveJobEnvironment(cwd, sandboxAgentType, safeLog);
6371
+ const enforcementMode = environmentEnforcement();
5744
6372
  /** @type {string|null} */
5745
6373
  let sandboxTmpDir = null;
5746
- if (sandboxDeps.available && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, sandboxAgentType)) {
6374
+ if (sandboxDeps.available && jobEnvironment && jobEnvironment.profile.osSandboxRequired) {
5747
6375
  try {
5748
6376
  sandboxTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smj-'));
5749
6377
  } catch (e) {
@@ -5757,16 +6385,50 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5757
6385
  };
5758
6386
  const sandboxPolicy = buildJobSandboxSettings({
5759
6387
  agentType: sandboxAgentType,
6388
+ environment: jobEnvironment,
5760
6389
  worktreeDir: spawnCwd,
5761
6390
  projectRoot: cwd,
5762
6391
  homeDir: os.homedir(),
5763
6392
  tmpDir: sandboxTmpDir || os.tmpdir(),
5764
6393
  deps: sandboxDeps,
6394
+ mode: enforcementMode,
5765
6395
  });
6396
+ // Enforce mode: an environment that needs the OS sandbox and cannot get it
6397
+ // is never downgraded to tool rules — the job is not spawned and
6398
+ // spawnJob parks it needs_review 'environment_unavailable: <missing deps>'
6399
+ // through the personaRefusal path (parkPersonaRefusal → transitionJob).
6400
+ if (sandboxPolicy.refusal) {
6401
+ const { code, detail } = sandboxPolicy.refusal;
6402
+ const refusalError = `${code}: ${detail}`;
6403
+ try {
6404
+ appendAuditEvent('environment_would_block', wouldBlockRecord({
6405
+ slug: job.slug, persona: sandboxAgentType, environment: jobEnvironment ? jobEnvironment.id : null,
6406
+ what: 'os_sandbox_unavailable', detail: sandboxPolicy.summary.reason, mode: enforcementMode,
6407
+ }));
6408
+ } catch { /* audit must not break dispatch */ }
6409
+ safeLog(`[scheduler] environment ${jobEnvironment ? jobEnvironment.id : '(none)'} refused for ${job.slug} — not spawned: ${refusalError}\n`);
6410
+ closeFd();
6411
+ removeSandboxTmp();
6412
+ 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 });
6413
+ resolve({ exitCode: -1, durationMs: 0, error: refusalError, sessionId, personaRefusal: { code, detail } });
6414
+ return;
6415
+ }
5766
6416
  // childEnv was built (and cleanChildEnv already ran) above.
5767
6417
  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'} ` +
6418
+ // guard-tool-risk reads these to deny (enforce) or report (report mode)
6419
+ // the WebFetch/WebSearch calls the environment disallows.
6420
+ Object.assign(childEnv, environmentHookEnv({ environment: jobEnvironment, mode: enforcementMode, agentType: sandboxAgentType }));
6421
+ for (const wb of sandboxPolicy.wouldBlock) {
6422
+ try {
6423
+ appendAuditEvent('environment_would_block', wouldBlockRecord({
6424
+ slug: job.slug, persona: sandboxAgentType, environment: jobEnvironment ? jobEnvironment.id : null,
6425
+ what: wb.what, detail: wb.detail, mode: enforcementMode,
6426
+ }));
6427
+ } catch { /* audit must not break dispatch */ }
6428
+ safeLog(`[scheduler] environment would block (report mode, not blocked): ${wb.what} — ${wb.detail}\n`);
6429
+ }
6430
+ const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir, enforcement: enforcementMode };
6431
+ safeLog(`[scheduler] sandbox: level=${sandboxMeta.level} environment=${sandboxMeta.environment ?? 'none'} profile=${sandboxMeta.profile ?? 'none'} ` +
5770
6432
  `network=${sandboxMeta.network ? (sandboxMeta.network.join(',') || 'none') : 'unrestricted'} reason=${sandboxMeta.reason ?? 'none'} ` +
5771
6433
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
5772
6434
  const jobArgs = buildClaudeSpawnArgs({
@@ -5777,28 +6439,56 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5777
6439
  resume: !!resumeTarget,
5778
6440
  systemPrompt: jobSystemPrompt,
5779
6441
  toolScope: personaToolScope,
6442
+ mcpServerNames: personaResolution.mcpServers || [],
5780
6443
  pluginDirArgs: packArgs.pluginDirArgs,
5781
6444
  jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5782
6445
  riskGuardSettingsPath,
5783
6446
  });
5784
6447
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5785
6448
 
6449
+ // Spawn-time credential assertion: the FINAL env (after every
6450
+ // Object.assign above) must carry no SECRET_KEY_RE key. Refuse, never spawn.
6451
+ try {
6452
+ assertNoCredentials(childEnv, { site: 'scheduler-job' });
6453
+ } catch (credErr) {
6454
+ const errMsg = String((credErr && credErr.message) || credErr);
6455
+ safeLog(`[scheduler] ${errMsg}\n`);
6456
+ closeFd();
6457
+ 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 });
6458
+ removeSandboxTmp();
6459
+ resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'credentials_in_env', sessionId });
6460
+ return;
6461
+ }
6462
+
5786
6463
  // Pre-spawn argv guard: one oversized argument makes spawn throw E2BIG.
5787
6464
  const oversized = launchFailure.findOversizedArg(jobSpawn.args || jobArgs);
5788
6465
  if (oversized) {
5789
6466
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5790
6467
  safeLog(`[scheduler] ${errMsg}\n`);
5791
6468
  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 });
6469
+ 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
6470
  removeSandboxTmp();
5794
6471
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5795
6472
  return;
5796
6473
  }
5797
6474
 
5798
6475
  const scopePlan = planJobScope({ jobSpawn, jobArgs, slug: job.slug, startedAt });
5799
- const scopeState = { unit: scopePlan.unit, pid: null, cgroupDir: null, finalized: false };
6476
+ const scopeState = { unit: scopePlan.unit, runId: path.basename(runDir), pid: null, cgroupDir: null, finalized: false, memoryMaxMb: scopePlan.memoryMaxMb, agentType: job.agentType || 'dev-lead' };
5800
6477
  const launchSpawn = scopePlan.spawn;
5801
6478
 
6479
+ // Epic event log: job.tool_use per tool_use block in the job's stream-json
6480
+ // log (summary only, ≤200 chars, secrets redacted). Polled alongside the
6481
+ // other watchdogs (never fires), flushed once more on exit.
6482
+ const toolUseEmitter = createJobToolUseEmitter({
6483
+ job, logPath, appendEvent: epicEventLog.appendEpicEvent, logError: (msg) => console.error(msg),
6484
+ });
6485
+ const toolUseWatchdog = toolUseEmitter ? {
6486
+ label: 'tool-use-events',
6487
+ intervalMs: RESULT_TAIL_POLL_MS,
6488
+ shouldFire() { try { toolUseEmitter.poll(); } catch { /* never throws */ } return false; },
6489
+ action() {},
6490
+ } : null;
6491
+
5802
6492
  const { child } = withChildAndLog({
5803
6493
  fd,
5804
6494
  logPath,
@@ -5824,8 +6514,9 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5824
6514
  ...detachedSpawnOpts(),
5825
6515
  },
5826
6516
  },
5827
- watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
6517
+ watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog, ...(toolUseWatchdog ? [toolUseWatchdog] : [])],
5828
6518
  onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
6519
+ if (toolUseEmitter) { try { toolUseEmitter.flush(); } catch { /* never breaks the exit path */ } }
5829
6520
  const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
5830
6521
  const durationMs = Date.now() - startedAt;
5831
6522
  finalizeJobScope(scopeState, sl);
@@ -5842,7 +6533,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5842
6533
  sl(`\n[scheduler] ${errMsg}\n`);
5843
6534
  // Sync write: inside a Promise executor callback; must flush meta
5844
6535
  // 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 });
6536
+ 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
6537
  removeSandboxTmp();
5847
6538
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5848
6539
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
@@ -5870,6 +6561,14 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5870
6561
  }
5871
6562
  sl(`\n[scheduler] exit code=${effectiveCode} (raw code=${exitCode} signal=${signal}) ` +
5872
6563
  `duration=${Math.round(durationMs / 1000)}s\n`);
6564
+ // The scope's own OOM killer fired: name the cap instead of a generic exit.
6565
+ const memoryCapReason = memoryCapFailureReason(scopeState, effectiveCode);
6566
+ if (memoryCapReason) sl(`\n[scheduler] ${memoryCapReason}\n`);
6567
+ // Post any tool-risk 'confirm' requests the guard recorded (this job's, and
6568
+ // any a crashed run left behind) as Needs-you items. Fire-and-forget: never throws.
6569
+ needsYouStore.drainConfirmationRequests().then((r) => {
6570
+ if (r.created > 0 && mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {});
6571
+ }, () => {});
5873
6572
  const rateLimited = effectiveCode !== 0 && detectRateLimitInLog(logPath);
5874
6573
  const networkError = effectiveCode !== 0 && !rateLimited && detectNetworkErrorInLog(logPath);
5875
6574
  // Non-run detection (issue #11 lists A1–A3): the harness's `result`
@@ -5906,14 +6605,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5906
6605
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5907
6606
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5908
6607
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6608
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapKill: { oomKills: scopeState.oomKills, memoryMaxMb: scopeState.memoryMaxMb ?? null } } : {}),
5909
6609
  sandbox: sandboxMeta,
5910
6610
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5911
6611
  originSessionId, contextDigestApplied,
6612
+ agentSnapshotId: personaResolution.agentSnapshotId || null,
5912
6613
  });
5913
6614
  removeSandboxTmp();
5914
6615
  resolve({
5915
6616
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5916
6617
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6618
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
5917
6619
  });
5918
6620
  },
5919
6621
  });
@@ -6009,7 +6711,7 @@ function isPromotableOriginal(status) {
6009
6711
  */
6010
6712
  function healTargetForFix(fixSlug, jobs) {
6011
6713
  const originalSlug = fixSlug.replace(/^(\d+)-fix-/, '$1-');
6012
- return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !reviewLadder.isCancelledJob(x)) || null;
6714
+ return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !isCancelledRow(x)) || null;
6013
6715
  }
6014
6716
 
6015
6717
  /**
@@ -6017,7 +6719,7 @@ function healTargetForFix(fixSlug, jobs) {
6017
6719
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
6018
6720
  * spawnInvestigation computes.
6019
6721
  */
6020
- function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild = null, recordPath = null, recordIgnored = true }) {
6722
+ function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, deadChild = null, recordPath = null, recordIgnored = true }) {
6021
6723
  const runtimePaths = RUNTIME_NAMESPACES.map((ns) => `session-manager-operations/${ns}/`).join(', ');
6022
6724
  const recordRule = (recordPath && !recordIgnored)
6023
6725
  ? `- The only allowed record location is ${recordPath}. If the fix plan asks for a record file, it must be exactly this path.
@@ -6133,7 +6835,6 @@ ${logTail}
6133
6835
  ---
6134
6836
  title: Fix: <short summary of the fix>
6135
6837
  cwd: ${cwd}
6136
- parallelGroup: ${group}
6137
6838
  estimateMinutes: <your time estimate>
6138
6839
  isFixPlan: true
6139
6840
  ---
@@ -6146,6 +6847,7 @@ ${logTail}
6146
6847
  not that repo (e.g. a scratch dir like \`/tmp\`), set \`cwd:\` to the correct repo root instead —
6147
6848
  the scheduler's commit guard and post-run verifier read git state from this path, and a
6148
6849
  non-repo cwd parks even a fully green, committed run in \`needs_review\`.
6850
+ 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
6851
  6. The PRD body MUST be self-contained — \`claude -p\` runs it on a fresh Sonnet session with NO conversation context. Include:
6150
6852
  - Root-cause analysis (what went wrong and why)
6151
6853
  - Concrete fix steps (specific files / commands / edits)
@@ -6221,6 +6923,18 @@ function readRunOutcomeSidecars(runDir, slug) {
6221
6923
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
6222
6924
 
6223
6925
  async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {}) {
6926
+ // Auto-dispatch hold first — before anything below can spawn a process
6927
+ // (probeClaudeVersion included). A held needs_review row stays eligible for
6928
+ // the periodic auto-fix pass; a plain 'failed' row (never a
6929
+ // selectAutoFixTargets target) waits in deferredInvestigations, which that
6930
+ // same pass drains once the hold clears.
6931
+ const queueState = await readQueue().catch(() => null);
6932
+ if (investigationHold(failedJob.slug, queueState?.config)) {
6933
+ if (failedJob.status !== 'needs_review' && !deferredInvestigations.has(failedJob.slug)) {
6934
+ deferredInvestigations.set(failedJob.slug, { failedJob, runDir });
6935
+ }
6936
+ return { deferred: true, held: true };
6937
+ }
6224
6938
  // A row waiting on its own red preflight spends nothing on the model
6225
6939
  // ladder: the precondition is the cause, not the work.
6226
6940
  if (reviewLadder.hasActivePreflightHold(failedJob)) {
@@ -6232,7 +6946,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6232
6946
  // B1: probes e4f82da2/d374e6bf died on the same HTTP 400 as the runs
6233
6947
  // they were investigating) there is nothing to diagnose — skip, loudly.
6234
6948
  {
6235
- const state = await readQueue().catch(() => null);
6949
+ const state = queueState;
6236
6950
  const block = state?.launchBlocks?.[INVESTIGATION_LAUNCH_KEY];
6237
6951
  const jobBlock = state?.launchBlocks?.[launchFailure.launchBlockKeyFor(failedJob)];
6238
6952
  const gate = launchFailure.evaluateLaunchGate(block || jobBlock, { now: Date.now(), claudeVersion: await probeClaudeVersion() });
@@ -6318,7 +7032,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6318
7032
  // archived twin (archivedPrdPathForJob) is deliberately NOT used for the
6319
7033
  // write dir, only for reading originalBody below.
6320
7034
  let originalBody = '';
6321
- const { fixPath, fixSlug, group, livePrdDir } = await resolveFixPlanPath(failedJob);
7035
+ const { fixPath, fixSlug, livePrdDir } = await resolveFixPlanPath(failedJob);
6322
7036
  try {
6323
7037
  const originalPath = livePrdDir ? path.join(livePrdDir, `${failedJob.slug}.md`) : prdPaths.archivedPrdPathForJob(failedJob);
6324
7038
  originalBody = (await parsePrd(originalPath)).body;
@@ -6372,7 +7086,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6372
7086
  } catch (err) {
6373
7087
  recordIgnored = !(err && err.code === 1);
6374
7088
  }
6375
- const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild, recordPath, recordIgnored });
7089
+ const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, deadChild, recordPath, recordIgnored });
6376
7090
 
6377
7091
  // Phase 1: open log fd for pre-spawn diagnostics.
6378
7092
  const { fd, safeLog, closeFd } = openLog(investigationLogPath);
@@ -6404,7 +7118,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6404
7118
  await mutate((s) => {
6405
7119
  const j = s.jobs.find((x) => x.slug === failedJob.slug);
6406
7120
  if (!j) return;
6407
- const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !reviewLadder.isCancelledJob(j) && !reviewLadder.hasActivePreflightHold(j);
7121
+ const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !isCancelledRow(j) && !reviewLadder.hasActivePreflightHold(j);
6408
7122
  const transitioned = statusEligible && transitionJob(j, 'investigating', { reason: 'spawning investigation probe', source: 'spawnInvestigation:start' });
6409
7123
  liveCheck = { ok: statusEligible && transitioned, status: j.status };
6410
7124
  });
@@ -6824,6 +7538,9 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6824
7538
  appendAuditEvent('job_cancel_integration_skipped', { slug: job.slug, runId, branch: worktree.branch });
6825
7539
  await pinUnlanded();
6826
7540
  await cleanup({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
7541
+ // An interrupted run is continued later in the same session: record
7542
+ // what it left uncommitted so the continue prompt can name it.
7543
+ await recordInterruptLeftovers(job.slug, runId, { dirtyPaths: worktreeLeftoverDirty, salvagePatch });
6827
7544
  return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead, uncommittedSnapshot };
6828
7545
  }
6829
7546
  if (worktreeHead.action === 'diverged') {
@@ -6879,7 +7596,12 @@ async function isRunCancelled(slug, runId) {
6879
7596
  try {
6880
7597
  const state = await readQueue();
6881
7598
  const row = state.jobs.find((j) => j.slug === slug);
6882
- return !!(row && row.cancelledAt && (row.cancelledRunId ?? null) === (runId ?? null));
7599
+ if (!row) return false;
7600
+ if (row.cancelledAt && (row.cancelledRunId ?? null) === (runId ?? null)) return true;
7601
+ // A human interrupt (remote.interruptJob) stops the run without ending
7602
+ // the job: its work stays on the job branch, never integrated, until
7603
+ // remote.continueJob resumes the same session.
7604
+ return !!(row.interrupted && (row.interrupted.runId ?? null) === (runId ?? null));
6883
7605
  } catch {
6884
7606
  return false;
6885
7607
  }
@@ -6918,6 +7640,42 @@ function guardedTick(fn, label) {
6918
7640
  * (and they never shadow a pickable sibling) while a dependent of a held
6919
7641
  * row still sees it as a blocking dep.
6920
7642
  */
7643
+ /**
7644
+ * Pending rows stopped by a human interrupt (remote.interruptJob) → Map<slug,
7645
+ * heldReason>. They wait for remote.continueJob and are never auto-dispatched
7646
+ * (a fresh dispatch would mint a new session instead of resuming).
7647
+ * @param {any[]} jobs
7648
+ * @returns {Map<string, string>}
7649
+ */
7650
+ function computeInterruptHolds(jobs) {
7651
+ const held = new Map();
7652
+ for (const j of jobs || []) {
7653
+ if (!j || j.status !== 'pending' || !j.interrupted) continue;
7654
+ held.set(j.slug, j.heldReason || 'interrupted by a human — waiting for continue');
7655
+ }
7656
+ return held;
7657
+ }
7658
+
7659
+ /**
7660
+ * Stamps an interrupted run's leftovers onto its row's `interrupted` record.
7661
+ * Only for the same run that was interrupted; never throws.
7662
+ * @param {string} slug
7663
+ * @param {string | null} runId
7664
+ * @param {{ dirtyPaths?: string[], salvagePatch?: string | null }} leftovers
7665
+ */
7666
+ async function recordInterruptLeftovers(slug, runId, { dirtyPaths, salvagePatch }) {
7667
+ try {
7668
+ await mutate((s) => {
7669
+ const row = s.jobs.find((x) => x.slug === slug);
7670
+ if (!row || !row.interrupted || (row.interrupted.runId ?? null) !== (runId ?? null)) return;
7671
+ row.interrupted.dirtyPaths = Array.isArray(dirtyPaths) ? dirtyPaths.slice(0, 200) : [];
7672
+ row.interrupted.salvagePatch = salvagePatch || null;
7673
+ });
7674
+ } catch (e) {
7675
+ console.warn(`[scheduler] ${slug}: could not record interrupt leftovers`, e?.message);
7676
+ }
7677
+ }
7678
+
6921
7679
  function computePreflightHolds(jobs, now = Date.now()) {
6922
7680
  const held = new Map();
6923
7681
  for (const j of jobs || []) {
@@ -7480,6 +8238,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7480
8238
  // shape for the whole run). Named generically (not "worktree...") because
7481
8239
  // an in-place run salvages one too (PRD 1098).
7482
8240
  let salvagePatch = null;
8241
+ // Artifact evidence for a declared artifact-only PRD, captured while the
8242
+ // job worktree still exists (finalizeJobWorktree deletes it before
8243
+ // verifyRun runs). Null for in-place runs and undeclared PRDs.
8244
+ let artifactEvidence = null;
7483
8245
  let uncommittedSnapshot = null;
7484
8246
  // Which foreign-WIP shape applies to THIS run: an isolated worktree only
7485
8247
  // ever needs to disclose carriedPaths (its checkout starts clean apart
@@ -7494,6 +8256,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7494
8256
  const idx = s.jobs.findIndex((x) => x.slug === job.slug);
7495
8257
  if (idx >= 0) {
7496
8258
  s.jobs[idx].sessionId = sessionId;
8259
+ if (job.agentSnapshotId) s.jobs[idx].agentSnapshotId = job.agentSnapshotId;
7497
8260
  s.jobs[idx].runtime = { pid, runId, startedAt: s.jobs[idx].startedAt, sessionId, cwd };
7498
8261
  s.jobs[idx].dispatchPhase = 'spawned';
7499
8262
  s.jobs[idx].dispatchPhaseAt = new Date().toISOString();
@@ -7515,6 +8278,21 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7515
8278
  // them to the main checkout before verify and before the checkout is
7516
8279
  // removed. Never throws (planRecordHarvest.cjs).
7517
8280
  harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8281
+ // Capture artifact evidence before the worktree is removed: a
8282
+ // git-ignored artifact may live only here. Never breaks teardown.
8283
+ try {
8284
+ const evidencePrdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
8285
+ artifactEvidence = captureArtifactEvidence({
8286
+ prdPath: evidencePrdPath,
8287
+ roots: [job.cwd || defaultCwd, worktree.dir],
8288
+ startedAt: dispatchStartedAt,
8289
+ });
8290
+ } catch {
8291
+ artifactEvidence = null;
8292
+ }
8293
+ // Same point for the Artifacts store: declared artifactPaths + the
8294
+ // job's SM_ARTIFACTS_DIR staging folder. Never throws.
8295
+ await harvestJobArtifacts(job, worktree.dir, job.cwd || defaultCwd, { runId });
7518
8296
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
7519
8297
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
7520
8298
  } else {
@@ -7578,6 +8356,14 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7578
8356
  // a sibling); an in-place run on the baseline delta.
7579
8357
  const jobDirt = worktree.ok ? stripAppOwnedChurn(worktreeLeftoverDirty) : newlyDirtyAll;
7580
8358
 
8359
+ // Persona refusal (persona_missing / persona_invalid): executeJob never
8360
+ // spawned. Park needs_review with '<code>: <detail>' — running ->
8361
+ // needs_review is a legal edge — instead of the old silent
8362
+ // 'no persona + sonnet' fallback.
8363
+ if (res.personaRefusal) {
8364
+ await parkPersonaRefusal(job, res.personaRefusal);
8365
+ return;
8366
+ }
7581
8367
  if (res.launchFailure) {
7582
8368
  await handleLaunchFailure({ job, res, runId, runDir, launchKey, launchEnv, claudeVersion: claudeVersionNow });
7583
8369
  return;
@@ -7761,7 +8547,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7761
8547
  priorLandedCommit,
7762
8548
  jobLandedCommitThisRun,
7763
8549
  exitCode: res.exitCode,
7764
- worktreeDir: worktree.ok ? worktree.dir : null,
8550
+ artifactEvidence,
7765
8551
  }).catch((e) => ({
7766
8552
  verdict: 'verify_unavailable',
7767
8553
  reason: `verifier threw: ${e?.message ?? String(e)}`,
@@ -8018,6 +8804,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8018
8804
  let investigationJobSnapshot = null;
8019
8805
  let investigationDeadChildSnapshot = null;
8020
8806
  let needsReviewRcaSnapshot = null;
8807
+ let outcomeRecordSnapshot = null; // every completed/failed/needs_review finalize (prdOutcomeRecord.cjs)
8021
8808
  let resumeRecoveryJob = null;
8022
8809
  let resumeRecoveryTarget = null;
8023
8810
  let quarantineJob = null;
@@ -8233,6 +9020,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8233
9020
  // is ALSO set (e.g. a real exit failure whose branch also failed
8234
9021
  // to integrate must show both, not just the first one).
8235
9022
  : [res.error, worktreeIntegrationFailure ? verifyResult.reason : null].filter(Boolean).join('; ') || null;
9023
+ // A scope OOM kill names the cap on every non-completed outcome
9024
+ // (failed rows already carry it via res.error above).
9025
+ if (res.memoryCapReason && effectiveStatus !== 'completed' && !String(s.jobs[i2].error || '').includes(res.memoryCapReason)) {
9026
+ s.jobs[i2].error = [res.memoryCapReason, s.jobs[i2].error].filter(Boolean).join('; ');
9027
+ }
8236
9028
  // Persist the commit THIS run landed (if HEAD advanced) so a later
8237
9029
  // re-fire of the same slug can prove its own no-op re-run is
8238
9030
  // truthful via the pass_no_commit_prior_run_verified exemption.
@@ -8351,6 +9143,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8351
9143
  // attribute" via its Array.isArray guard, same as an empty array.
8352
9144
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
8353
9145
 
9146
+ if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9147
+ outcomeRecordSnapshot = { ...s.jobs[i2] };
9148
+ }
8354
9149
  if (isNotifiableTerminalStatus(effectiveStatus)) {
8355
9150
  terminalNotifySnapshot = { ...s.jobs[i2] };
8356
9151
  }
@@ -8419,7 +9214,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8419
9214
  const fixSlugExists = (slug) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${slug}.md`)));
8420
9215
  if (
8421
9216
  process.env.SM_AUTOFIX_DISABLE !== '1' &&
8422
- reviewLadder.isEligibleForImmediateAutoFix(s.jobs[i2], s.jobs, fixSlugExists)
9217
+ reviewLadder.isEligibleForImmediateAutoFix(s.jobs[i2], s.jobs, fixSlugExists) &&
9218
+ // Under the auto-dispatch hold: stamp nothing, leave the row
9219
+ // eligible for the periodic auto-fix pass once the hold clears.
9220
+ !investigationHold(s.jobs[i2].slug, s.config)
8423
9221
  ) {
8424
9222
  const isRetryAttempt = s.jobs[i2].autoFixAttempted === true;
8425
9223
  const isDeadFixPlanReopen = reviewLadder.isFixPlanDead(s.jobs[i2], s.jobs);
@@ -8491,6 +9289,17 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8491
9289
  strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
8492
9290
  });
8493
9291
 
9292
+ // Structured per-PRD outcome record + outcome.recorded Epic event
9293
+ // (prdOutcomeRecord.cjs). Never blocks or fails the finalize.
9294
+ if (outcomeRecordSnapshot) {
9295
+ await writeJobOutcomeRecord(outcomeRecordSnapshot, {
9296
+ verifyResult,
9297
+ landedCommit: jobLandedCommitThisRun ?? null,
9298
+ strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
9299
+ fallbackCwd: defaultCwd,
9300
+ });
9301
+ }
9302
+
8494
9303
  if (terminalNotifySnapshot) {
8495
9304
  notifyOriginatingTab(terminalNotifySnapshot).catch((e) => {
8496
9305
  console.error('[scheduler] notifyOriginatingTab error', job.slug, e);
@@ -8754,12 +9563,186 @@ async function reclaimTerminalJobOrphansThrottled(state) {
8754
9563
  * with the 'running' transition).
8755
9564
  */
8756
9565
  async function spawnResumeRecovery(job, resumeTarget) {
8757
- const { runId, dir: runDir } = pickRunDir();
8758
9566
  // No queue rows in scope here (unlike tickQueue's own dispatch loop) — read
8759
9567
  // once, before delegating to spawnJob, so hasDownstreamValidator still
8760
- // never runs inside executeJob itself.
9568
+ // never runs inside executeJob itself. Its config also feeds the hold below.
9569
+ const state = await readQueue().catch(() => ({ jobs: [], config: undefined }));
9570
+ // A `--resume` run is an automatic `claude -p` that never passes through
9571
+ // tickBody, so it obeys the same auto-dispatch hold itself. A deferral
9572
+ // stamps nothing (spawnJob stamps resumeRecoveryAttempted only when it
9573
+ // runs): the row stays needs_review and the periodic reverifyNeedsReview
9574
+ // pass (selectResumeRecoveryBatch) resumes it once the hold clears.
9575
+ // One 'resume_recovery_held' line per row per hold (resumeRecoveryHeldKeys).
9576
+ const hold = currentAutoDispatchHold(state.config);
9577
+ if (hold) {
9578
+ if (noteHeldOnce(resumeRecoveryHeldKeys, job.slug, hold)) {
9579
+ console.log(`[scheduler] resume-recovery held for ${job.slug}: ${hold.reason} — ${hold.detail ?? ''}`);
9580
+ appendAuditEvent('resume_recovery_held', { slug: job.slug, reason: hold.reason });
9581
+ }
9582
+ return;
9583
+ }
9584
+ resumeRecoveryHeldKeys.delete(job.slug);
9585
+ const { runId, dir: runDir } = pickRunDir();
9586
+ const siblingJobs = state.jobs || [];
9587
+ await dispatchSpawnJob(job, runId, runDir, job.cwd || DEFAULT_PROJECT_CWD, resumeTarget, siblingJobs);
9588
+ }
9589
+
9590
+ const CONFIRM_APPROVE = 'Approve';
9591
+ const CONFIRM_BUSY = new Set(['running', 'investigating']);
9592
+ // record key -> hold key (autoDispatchHoldKey) under which its
9593
+ // 'tool_confirmation_resume_held' audit event was already appended (one event
9594
+ // per record per hold). Pruned to the pending records every pass and cleared
9595
+ // when no hold is in force (processToolConfirmationAnswers).
9596
+ const toolConfirmationHeldKeys = new Map();
9597
+ // slug -> hold key under which its 'investigation_held' / 'resume_recovery_held'
9598
+ // audit event was already appended (one event per row per hold). A row's key
9599
+ // is removed when no hold is in force for it (it launches), so a later hold
9600
+ // audits it once again.
9601
+ const investigationHeldKeys = new Map();
9602
+ const resumeRecoveryHeldKeys = new Map();
9603
+
9604
+ /** Identity of one auto-dispatch hold: reason + window + resetsAt. */
9605
+ function autoDispatchHoldKey(hold) {
9606
+ return `${hold.reason}|${hold.window ?? ''}|${hold.resetsAt ?? ''}`;
9607
+ }
9608
+
9609
+ /**
9610
+ * Record `hold` as `slug`'s current hold in `keys`. true = this is a new hold
9611
+ * for the row (audit it); false = already audited under this same hold.
9612
+ */
9613
+ function noteHeldOnce(keys, slug, hold) {
9614
+ const key = autoDispatchHoldKey(hold);
9615
+ if (keys.get(slug) === key) return false;
9616
+ keys.set(slug, key);
9617
+ return true;
9618
+ }
9619
+
9620
+ /**
9621
+ * Apply answered tool-risk confirmation items (needsYouStore app 'tool-risk')
9622
+ * to the jobs that asked, via toolClearance.answerConfirmation:
9623
+ * - Approve → human.tool_confirmation { approved: true }, one clearance bound
9624
+ * to the args digest, and the job is re-dispatched with
9625
+ * `--resume <the same session id>` (in place, like resume recovery).
9626
+ * - Deny (or a withdrawn item) → human.tool_confirmation { approved: false },
9627
+ * the row is parked needs_review with verifierVerdict 'confirmation_denied'.
9628
+ * A record whose job is still running is left for a later tick; a request
9629
+ * recorded after the item was answered is never auto-applied (it waits for a
9630
+ * fresh item). Never throws.
9631
+ * Under the auto-dispatch hold (automatic ticks only) an approval is left
9632
+ * pending — one 'tool_confirmation_resume_held' audit event per record per hold.
9633
+ * @param {{ jobs?: any[], config?: any }} state
9634
+ * @param {{ human?: boolean }} [opts] the running tick's `human` flag
9635
+ */
9636
+ async function processToolConfirmationAnswers(state, { human = false } = {}) {
9637
+ try {
9638
+ const pending = toolClearance.listPendingConfirmations();
9639
+ // Bound the Map by construction: a record that vanished without a take
9640
+ // (deleted, or unreadable so the list skips it) drops its key here.
9641
+ const liveKeys = new Set(pending.map((rec) => rec.key));
9642
+ for (const key of toolConfirmationHeldKeys.keys()) {
9643
+ if (!liveKeys.has(key)) toolConfirmationHeldKeys.delete(key);
9644
+ }
9645
+ // No hold in force: a later hold audits every record once again. A human
9646
+ // tick that bypasses a hold in force does not count as the hold clearing.
9647
+ const rawHold = currentAutoDispatchHold(state.config);
9648
+ if (!rawHold) toolConfirmationHeldKeys.clear();
9649
+ if (!pending.length) return;
9650
+ // Same hold decision as the tick running this pass: an approval starts a
9651
+ // `claude -p --resume`, so an automatic tick under the hold leaves it
9652
+ // pending for a later tick. A denial starts nothing and is applied anyway.
9653
+ const hold = human ? null : rawHold;
9654
+ toolClearance.pruneExpired();
9655
+ const items = await needsYouStore.listNeedsYou({ app: needsYouStore.CONFIRM_APP });
9656
+ const rowOf = (slug) => (state.jobs || []).find((j) => j.slug === slug) || null;
9657
+ for (const rec of pending) {
9658
+ const item = items.find((it) => it.id === needsYouStore.confirmationItemId(rec.tool, rec.argsDigest));
9659
+ if (!item || item.status === 'open') continue;
9660
+ const answeredAtMs = Date.parse(item.answeredAt || item.updatedAt || '') || 0;
9661
+ if (rec.requests.some((r) => CONFIRM_BUSY.has(rowOf(r.jobSlug)?.status) || runningSet.has(r.jobSlug))) continue;
9662
+ const approved = item.status === 'answered' && item.answer === CONFIRM_APPROVE;
9663
+ if (approved && hold) {
9664
+ if (noteHeldOnce(toolConfirmationHeldKeys, rec.key, hold)) {
9665
+ for (const r of rec.requests) appendAuditEvent('tool_confirmation_resume_held', { slug: r.jobSlug, reason: hold.reason });
9666
+ }
9667
+ continue;
9668
+ }
9669
+ if (approved && rec.requests.some((r) => (r.requestedAt || 0) <= answeredAtMs) && sessionSlots.availableFor('job') < 1) continue;
9670
+ const taken = toolClearance.takePendingConfirmation(rec.key);
9671
+ if (!taken) continue;
9672
+ toolConfirmationHeldKeys.delete(rec.key);
9673
+ for (const request of taken.requests) {
9674
+ if ((request.requestedAt || 0) > answeredAtMs) {
9675
+ console.warn(`[scheduler] ${request.jobSlug}: confirmation request for ${request.tool} postdates the answer — not applied`);
9676
+ continue;
9677
+ }
9678
+ await applyToolConfirmationAnswer(request, approved, rowOf(request.jobSlug));
9679
+ }
9680
+ }
9681
+ } catch (e) {
9682
+ console.warn('[scheduler] tool confirmation answers failed', e?.message);
9683
+ }
9684
+ }
9685
+
9686
+ /** One job's answer: emit, then resume (approve) or park (deny). */
9687
+ async function applyToolConfirmationAnswer(request, approved, row) {
9688
+ if (!row) {
9689
+ console.warn(`[scheduler] ${request.jobSlug}: confirmation answered but the job row is gone`);
9690
+ return;
9691
+ }
9692
+ const req = { ...request, sessionId: request.sessionId || row.sessionId || null };
9693
+ const eventTarget = { slug: row.slug, epicId: row.epicId || row.sourcePromptId || req.epicId, cwd: row.cwd || req.cwd };
9694
+ let resume = null;
9695
+ let park = null;
9696
+ toolClearance.answerConfirmation({ request: req, approved }, {
9697
+ emit: (event) => {
9698
+ emitJobEvent(eventTarget, event);
9699
+ appendAuditEvent('tool_confirmation_answered', { slug: row.slug, tool: event.tool, argsDigest: event.argsDigest, approved: event.approved });
9700
+ },
9701
+ resume: (r) => { resume = r; },
9702
+ park: (p) => { park = p; },
9703
+ });
9704
+ if (park) {
9705
+ await mutate((s) => {
9706
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
9707
+ if (!j) return;
9708
+ j.confirmationDenied = { tool: req.tool, argsDigest: req.argsDigest, at: new Date().toISOString(), reason: park.reason };
9709
+ if (j.status === 'failed' || j.status === 'needs_review') {
9710
+ transitionJob(j, 'needs_review', { reason: park.reason, source: 'processToolConfirmationAnswers' });
9711
+ j.verifierVerdict = park.reason;
9712
+ }
9713
+ });
9714
+ await broadcast({ flush: true });
9715
+ return;
9716
+ }
9717
+ if (!resume) return;
9718
+ const priorStatus = row.status;
9719
+ // needs_review and pending dispatch straight to 'running'; a finished row
9720
+ // takes the legal edge back to 'pending' first.
9721
+ if (priorStatus === 'completed' || priorStatus === 'failed' || priorStatus === 'skipped') {
9722
+ await mutate((s) => {
9723
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
9724
+ if (j) transitionJob(j, 'pending', { reason: 'tool confirmation approved: resuming the same session', source: 'processToolConfirmationAnswers' });
9725
+ });
9726
+ }
9727
+ const target = { sessionId: resume.sessionId, confirmation: { tool: req.tool, summary: req.summary || null, argsDigest: req.argsDigest } };
9728
+ const { runId, dir: runDir } = pickRunDir();
8761
9729
  const siblingJobs = (await readQueue().catch(() => ({ jobs: [] }))).jobs || [];
8762
- await spawnJob(job, runId, runDir, job.cwd || DEFAULT_PROJECT_CWD, resumeTarget, siblingJobs);
9730
+ const fresh = siblingJobs.find((x) => x.slug === row.slug) || row;
9731
+ // Not awaited: spawnJob runs the whole job. Its synchronous prefix takes
9732
+ // the session slot and adds the slug to runningSet before returning.
9733
+ Promise.resolve(dispatchSpawnJob(fresh, runId, runDir, fresh.cwd || DEFAULT_PROJECT_CWD, target, siblingJobs))
9734
+ .catch((e) => reportSchedulerError('tool confirmation resume failed', row.slug, e));
9735
+ if (!runningSet.has(row.slug)) {
9736
+ // No slot after all: restore the row and keep the request for a later tick.
9737
+ if (priorStatus === 'completed' || priorStatus === 'failed' || priorStatus === 'skipped') {
9738
+ const back = priorStatus;
9739
+ await mutate((s) => {
9740
+ const j = (s.jobs || []).find((x) => x.slug === row.slug);
9741
+ if (j && j.status === 'pending') transitionJob(j, back, { reason: 'tool confirmation resume deferred: no session slot', source: 'processToolConfirmationAnswers' });
9742
+ });
9743
+ }
9744
+ toolClearance.recordPendingConfirmation(request, { now: request.requestedAt || 0 });
9745
+ }
8763
9746
  }
8764
9747
 
8765
9748
  // Serialized ticker: prevents two concurrent tickQueue() calls from racing
@@ -8814,11 +9797,14 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
8814
9797
  }
8815
9798
  }
8816
9799
 
8817
- function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
9800
+ // `human` is set only by the 'schedule:force-tick' and 'schedule:run-now' IPC
9801
+ // handlers (via runDueJobs): those ticks bypass the auto-dispatch hold. Every
9802
+ // automatic tick — the starvation watchdog included — honors it.
9803
+ function tickQueue({ bypassLoadGate = false, lastResort = false, human = false } = {}) {
8818
9804
  const budgetMs = tickWatchdogMs();
8819
9805
  const next = tickTail.then(() => {
8820
9806
  const gen = tickGeneration;
8821
- return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
9807
+ return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort, human }), budgetMs, () => {
8822
9808
  tickGeneration++; // fence the abandoned body
8823
9809
  console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
8824
9810
  if (!tickWedgeLatched) {
@@ -8841,10 +9827,13 @@ function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
8841
9827
  // The stale sentinel a fenced body returns: never recorded, never acted on.
8842
9828
  const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
8843
9829
 
8844
- async function tickBody(gen, { bypassLoadGate, lastResort }) {
9830
+ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
8845
9831
  const tickStartedAt = Date.now();
8846
9832
  // evaluate() only runs once slots and memory admit a batch, so the CPU sampler
8847
9833
  // needs every tick to keep a reference reading about a minute old.
9834
+ // Leftover chat/aux tool processes (their turn's claude gone) drop to nice 19
9835
+ // first, so the sample sees them as idle-priority load (PRD 4022). Never throws.
9836
+ if (process.platform === 'linux') reniceLeftovers();
8848
9837
  loadGate.observe();
8849
9838
  {
8850
9839
  const stale = () => gen !== tickGeneration;
@@ -8902,12 +9891,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8902
9891
  reclaimTerminalJobOrphansThrottled(state).catch((e) => {
8903
9892
  console.warn('[scheduler] terminal job-worktree orphan reclaim failed', e?.message);
8904
9893
  });
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
- });
9894
+ // Owner answers to tool-risk 'confirm' requests: approve resumes the SAME
9895
+ // session with a single-use clearance, deny parks confirmation_denied.
9896
+ // Awaited (not fire-and-forget) so a resumed row is in runningSet before
9897
+ // the picker below runs; never throws.
9898
+ await processToolConfirmationAnswers(state, { human });
9899
+ if (stale()) return STALE_TICK;
8911
9900
  // Session-Manager's machine-wide slot pool is the ONLY concurrency limit
8912
9901
  // the picker answers to (plus the memory gate below). The scheduler used
8913
9902
  // to also carry a private `concurrencyCap` of 3 — the exact per-consumer
@@ -8919,11 +9908,44 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8919
9908
  // second pool: the row count admitted this tick simply can't exceed the
8920
9909
  // degraded cap minus what's already running.
8921
9910
  runReservationExpiryPass(state.jobs, tickStartedAt);
9911
+ // Auto-dispatch hold (scheduler/utilizationHold.cjs): every automatic
9912
+ // tick — job finish, 30 s loop, freed slot, reaper, billing poll,
9913
+ // watchdog, boot/resume runDueJobs — holds at or above the threshold on
9914
+ // ANY live window of the last real reading, and under firePolicy
9915
+ // 'manual'. Only a human Run now / Fire next batch now passes through.
9916
+ {
9917
+ const hold = currentAutoDispatchHold(state.config);
9918
+ const nextHold = hold && hold.reason === 'utilization-held'
9919
+ ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, resetsAt: hold.resetsAt }
9920
+ : null;
9921
+ const holdKey = hold ? `${hold.reason}|${hold.window ?? ''}|${String(hold.percent)}` : null;
9922
+ const holdChanged = holdKey !== lastAutoDispatchHoldKey;
9923
+ utilizationHold = nextHold;
9924
+ lastAutoDispatchHoldKey = holdKey;
9925
+ if (hold) {
9926
+ const pendingCount = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length;
9927
+ if (human) {
9928
+ console.log(`[scheduler] ${hold.reason}: ${hold.detail} — human run bypassed the hold`);
9929
+ } else {
9930
+ if (holdChanged) {
9931
+ console.log(`[scheduler] ${hold.reason}: ${hold.detail} — holding ${pendingCount} pending job(s)`);
9932
+ await broadcast();
9933
+ if (stale()) return STALE_TICK;
9934
+ }
9935
+ loadGate.endHold();
9936
+ return recordTick({ fired: false, reason: hold.reason, deferredCount: pendingCount }, { detail: hold.detail });
9937
+ }
9938
+ } else if (holdChanged) {
9939
+ await broadcast();
9940
+ if (stale()) return STALE_TICK;
9941
+ }
9942
+ }
8922
9943
  const freeSlots = degradedConcurrencyCapValue != null
8923
9944
  ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8924
9945
  : sessionSlots.availableFor('job');
8925
9946
  const heldSlugs = await computeLaunchHolds(state);
8926
9947
  for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
9948
+ for (const [slug, why] of computeInterruptHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
8927
9949
  if (stale()) return STALE_TICK;
8928
9950
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8929
9951
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -8991,28 +10013,39 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8991
10013
  const jobBudgetMb = availableForJobs(availableMb, RESERVED_HOST_MB);
8992
10014
  // The slot pool already bounded `batch` (it was passed as freeSlots to
8993
10015
  // 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;
10016
+ // Measured reservations (PRD 4019, loadGate.measuredMemoryGate): each running
10017
+ // job keeps only max(0, its agentType's p50 peak − its current RSS) — its RSS
10018
+ // is already out of MemAvailable — each new job reserves its agentType's p75,
10019
+ // plus one shared spike buffer. Too few samples = the old flat 2.5 GB/job rule.
10020
+ // Unknown pid / 0 MB read = no RSS credit.
10021
+ const runningForGate = [];
8997
10022
  if (availableMb !== Infinity) {
8998
10023
  for (const j of state.jobs) {
8999
10024
  if (!runningSet.has(j.slug)) continue;
9000
10025
  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
- );
10026
+ const rssMb = Number.isInteger(pid) && pid > 0 ? processGroupRssMb(pid) : 0;
10027
+ runningForGate.push({ agentType: j.agentType, rssMb });
10028
+ }
10029
+ // A running slug without a queue row still holds memory: count it at 0 RSS.
10030
+ for (let k = runningForGate.length; k < runningSet.size; k++) runningForGate.push({ agentType: null, rssMb: 0 });
10031
+ }
10032
+ const memGate = measuredMemoryGate({ jobBudgetMb, running: runningForGate, batch, stats: jobMemoryStats });
10033
+ const allowed = memGate.allowed;
10034
+ const consumedMb = memGate.consumedMb;
10035
+ const memGateTerms = {
10036
+ reservationMb: memGate.reservationMb,
10037
+ spikeBufferMb: memGate.spikeBufferMb,
10038
+ runningGrowthMb: memGate.growthMb,
10039
+ measured: memGate.measured,
10040
+ };
9009
10041
  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() };
10042
+ const threshold = RESERVED_HOST_MB + memGate.needMb;
10043
+ const detail = formatMemoryGateDetail({ availableMb, threshold, reservedHostMb: RESERVED_HOST_MB, gate: memGate });
10044
+ console.log(`[scheduler] ${detail} — deferring ${batch.length} job(s) (${runningSet.size} running)`);
10045
+ lastMemGate = { availableMb, threshold, consumedMb, ...memGateTerms, deferred: true, at: new Date().toISOString() };
9013
10046
  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 },
10047
+ { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, threshold, consumedMb, ...memGateTerms },
10048
+ { detail, holds },
9016
10049
  );
9017
10050
  }
9018
10051
  const swapAllowed = swapLimitedBatchSize(memInfo, runningSet.size, allowed);
@@ -9032,8 +10065,9 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
9032
10065
  }
9033
10066
  const gatedBatch = batch.slice(0, swapAllowed);
9034
10067
  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() };
10068
+ const threshold = RESERVED_HOST_MB + memGate.needMb;
10069
+ console.log(`[scheduler] memory gate: available=${availableMb} MB — clamped batch ${batch.length} → ${gatedBatch.length} (${formatMemoryGateDetail({ availableMb, threshold, reservedHostMb: RESERVED_HOST_MB, gate: memGate })})`);
10070
+ lastMemGate = { availableMb, threshold, consumedMb, ...memGateTerms, deferred: false, clamped: true, at: new Date().toISOString() };
9037
10071
  } else {
9038
10072
  // Ungated full batch: clear stale gate snapshot so status doesn't show
9039
10073
  // a stale deferral from a previous tick.
@@ -9174,7 +10208,7 @@ function forceTickOutcome(result) {
9174
10208
  }
9175
10209
  }
9176
10210
 
9177
- async function runDueJobs({ bypassLoadGate = false } = {}) {
10211
+ async function runDueJobs({ bypassLoadGate = false, human = false } = {}) {
9178
10212
  const state = await readQueue();
9179
10213
  if (state.unreadable) {
9180
10214
  console.error('[scheduler] runDueJobs skipped: queue.json unreadable');
@@ -9185,31 +10219,21 @@ async function runDueJobs({ bypassLoadGate = false } = {}) {
9185
10219
  return { fired: false, reason: 'paused' };
9186
10220
  }
9187
10221
  cancelToken = { cancelled: false };
9188
- const result = await tickQueue({ bypassLoadGate });
10222
+ const result = await tickQueue({ bypassLoadGate, human });
9189
10223
  await broadcast();
9190
10224
  return result;
9191
10225
  }
9192
10226
 
9193
10227
  // ---------- when-available launch logic ----------
9194
10228
 
10229
+ // The utilization hold lives in tickBody (autoDispatchHold), so this ticks
10230
+ // and the tick itself holds — the same rule for every automatic caller.
9195
10231
  async function maybeLaunchWhenAvailable(state) {
9196
- utilizationHold = null;
9197
10232
  if (state.config.firePolicy !== 'when-available') return;
9198
10233
  if (state.paused) return;
9199
10234
  const pending = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug));
9200
10235
  if (pending.length === 0) return;
9201
10236
  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
10237
  console.log(`[scheduler] when-available: util=${cachedUtilization}%, ${pending.length} pending, ${runningSet.size} running — ticking`);
9214
10238
  tickQueue().catch((e) => console.error('[scheduler] tickQueue error', e));
9215
10239
  }
@@ -9233,6 +10257,9 @@ async function runQueueStarvationWatchdog(state, {
9233
10257
  now = Date.now(), thresholdMs = starvation.QUEUE_STARVATION_MS,
9234
10258
  bootedAtMs = Date.parse(SCHEDULER_BOOTED_AT), pauseClearedAtMs = lastPauseClearedAt,
9235
10259
  } = {}) {
10260
+ // Under the auto-dispatch hold an idle queue is the intended outcome, not
10261
+ // starvation: no warning, no audit, no forced tick.
10262
+ if (currentAutoDispatchHold(state?.config)) return null;
9236
10263
  // The idle clock is launch-keyed (dispatchIdleMs): NOT lastDispatchAttemptAt,
9237
10264
  // which tickQueue stamps before every gate — a queue whose 30 s loop ticks
9238
10265
  // and launches nothing would refresh it forever and the watchdog would
@@ -9397,7 +10424,7 @@ function rootBlockerPhrase(root) {
9397
10424
  * project_starved WARN + audit (each naming the root blocker), then the
9398
10425
  * bounded escalation. A known wait (starveRootFor) is skipped by both.
9399
10426
  */
9400
- function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}) {
10427
+ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}, config = undefined) {
9401
10428
  for (const sp of starvedProjects) {
9402
10429
  const { root, knownWait } = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
9403
10430
  if (knownWait) continue;
@@ -9416,10 +10443,12 @@ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}) {
9416
10443
  // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
9417
10444
  // a subset of the rows already reported above — same verdict, no
9418
10445
  // re-derivation.
9419
- runStarveEscalationSweep(starvedProjects, jobs, launchBlocks);
10446
+ runStarveEscalationSweep(starvedProjects, jobs, launchBlocks, config);
9420
10447
  }
9421
10448
 
9422
- function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
10449
+ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}, config = undefined) {
10450
+ // The auto-dispatch hold is why nothing dispatches — not a starve to escalate.
10451
+ if (currentAutoDispatchHold(config)) return;
9423
10452
  const rootByCwd = new Map();
9424
10453
  const reportable = starvedProjects.filter((sp) => {
9425
10454
  const r = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
@@ -10336,6 +11365,11 @@ async function pollLoop() {
10336
11365
  // YELLOW/RED forever even though nothing is actually degraded.
10337
11366
  if (billing.usageCircuit.state() !== 'closed') billing.usageCircuit.recordSuccess({});
10338
11367
  cachedUtilization = NO_METER_UTILIZATION;
11368
+ cachedUtilizationKnown = true;
11369
+ // A reading left from an earlier consumer login must never hold a
11370
+ // machine that has no meter.
11371
+ lastGoodUsagePayload = null;
11372
+ restoredUsageWindows = null;
10339
11373
  degradedConcurrencyCapValue = null;
10340
11374
  consecutiveFailures = 0;
10341
11375
  backoffMs = 0;
@@ -10400,6 +11434,7 @@ async function pollLoop() {
10400
11434
  recordObservedReset(window.resets_at ?? null);
10401
11435
  cachedUtilization = window.utilization;
10402
11436
  cachedBindingWindowName = window.name;
11437
+ cachedUtilizationKnown = true;
10403
11438
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
10404
11439
  degradedConcurrencyCapValue = null;
10405
11440
  consecutiveFailures = 0;
@@ -10445,8 +11480,12 @@ async function pollLoop() {
10445
11480
  lastGoodUsagePayload = r.cached;
10446
11481
  cachedUtilization = cachedBudget.utilization;
10447
11482
  cachedBindingWindowName = cachedBudget.name;
11483
+ cachedUtilizationKnown = true;
10448
11484
  degradedConcurrencyCapValue = null;
10449
11485
  } else {
11486
+ // A stale cache is still the last real reading: carry it (cap 2)
11487
+ // rather than the 100% placeholder.
11488
+ if (r.cached) lastGoodUsagePayload = r.cached;
10450
11489
  applyDegradedBudget();
10451
11490
  }
10452
11491
  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,7 +11628,7 @@ function selectHistoryJobs(jobs, limit, historyEntries = []) {
10589
11628
  * guard-parked row was never "exhausted auto-fix" and must never claim to be.
10590
11629
  */
10591
11630
  function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10592
- if (!j || j.status !== 'needs_review' || reviewLadder.isCancelledJob(j) || !reviewLadder.isEligibleForNeedsReviewAutoResolve(j, jobsInProject)) return null;
11631
+ if (!j || j.status !== 'needs_review' || isCancelledRow(j) || !reviewLadder.isEligibleForNeedsReviewAutoResolve(j, jobsInProject)) return null;
10593
11632
  if ((j.exhaustedResolveAttempts ?? 0) > reviewLadder.NEEDS_REVIEW_RESOLVE_CAP) return null;
10594
11633
  const originIsGuardParked = !reviewLadder.isExhaustedAutoFix(j) && reviewLadder.isGuardParkedWithoutAutoFix(j);
10595
11634
 
@@ -10640,7 +11679,7 @@ function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10640
11679
  * 'skipped', or null when the race guard rejects it.
10641
11680
  */
10642
11681
  function applyStuckFailedAutoSkip(j, ageMs = 0) {
10643
- if (!j || j.status !== 'failed' || reviewLadder.isCancelledJob(j)) return null;
11682
+ if (!j || j.status !== 'failed' || isCancelledRow(j)) return null;
10644
11683
  if ((j.failedAutoResetAttempts ?? 0) < reviewLadder.FAILED_AUTORESET_CAP) return null;
10645
11684
  const cap = reviewLadder.FAILED_AUTORESET_CAP;
10646
11685
  j.needsReviewAutoResolvedSkip = true;
@@ -10910,6 +11949,20 @@ async function runGateShadow(job) {
10910
11949
  const definitive = headStable && cleanOk && (outcome.status === 'green' || outcome.status === 'red');
10911
11950
  const gateShadow = { ...outcome, head: headBefore, source: gate.source, ranAt: new Date().toISOString(), definitive, ...(mainDeps ? { mainDeps } : {}) };
10912
11951
 
11952
+ // Structured criteria (prdCriteria.cjs): after the gate re-run, run each
11953
+ // criterion's mechanical check in the same tree and keep the observed
11954
+ // results for the run record and the validator. Runs after headAfter/
11955
+ // dirtAfter are taken so a check can never sway the gate's own judgement.
11956
+ let criteriaFm = null;
11957
+ try { criteriaFm = parsePrdFile(prdText).frontmatter.criteria; } catch { criteriaFm = null; }
11958
+ if (Array.isArray(criteriaFm) && criteriaFm.length) {
11959
+ try {
11960
+ gateShadow.criteriaChecks = await runCriteriaChecks({ criteria: criteriaFm, cwd: job.cwd });
11961
+ } catch (e) {
11962
+ console.warn('[scheduler] criteria checks error', job.slug, e && e.message ? e.message : e);
11963
+ }
11964
+ }
11965
+
10913
11966
  // Gate authority: a green re-run may complete the row outright, but only
10914
11967
  // for transcript-noise verdicts with a landed commit — every other park
10915
11968
  // (including no verdict at all) falls through to the plain observe-only
@@ -11002,7 +12055,8 @@ async function runGateShadow(job) {
11002
12055
  if (fs.existsSync(path.dirname(verdictsPath))) {
11003
12056
  let existing = {};
11004
12057
  try { existing = JSON.parse(fs.readFileSync(verdictsPath, 'utf8')) || {}; } catch { /* absent/unparseable → fresh */ }
11005
- try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow }); } catch { /* best-effort */ }
12058
+ const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
12059
+ try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
11006
12060
  }
11007
12061
  }
11008
12062
 
@@ -11603,7 +12657,13 @@ async function reverifyNeedsReview() {
11603
12657
  const targets = reviewLadder.selectAutoFixTargets(queueForResumeAndAutofix.jobs, {
11604
12658
  fixSlugExists: (s) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${s}.md`))),
11605
12659
  }).filter((job) => job.slug !== gateShadowSlug);
12660
+ // Hold clear: start any investigation a hold deferred for a plain
12661
+ // 'failed' row (spawnInvestigation parked it in deferredInvestigations).
12662
+ if (!currentAutoDispatchHold(queueForResumeAndAutofix.config)) drainDeferredInvestigation();
11606
12663
  for (const job of targets) {
12664
+ // Auto-dispatch hold: check BEFORE the attempt stamp below so a held
12665
+ // row is left un-attempted and this pass picks it up once it clears.
12666
+ if (investigationHold(job.slug, queueForResumeAndAutofix.config)) continue;
11607
12667
  const runId = job.runId || reviewLadder.resolveRunId(job);
11608
12668
  const runDir = path.join(schedulerPaths.runsDir(), runId);
11609
12669
  const isRetryAttempt = job.autoFixAttempted === true;
@@ -11630,7 +12690,7 @@ async function reverifyNeedsReview() {
11630
12690
  }
11631
12691
  });
11632
12692
  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) => {
12693
+ dispatchSpawnInvestigation(job, runDir, { deadChild }).catch((e) => {
11634
12694
  console.error('[scheduler] auto-fix spawnInvestigation error', job.slug, e);
11635
12695
  });
11636
12696
  }
@@ -11798,7 +12858,7 @@ function registerScheduleHandlers() {
11798
12858
  // Clears any existing pause first (same semantics as run-now).
11799
12859
  await clearPause('run-now');
11800
12860
  try {
11801
- const result = await runDueJobs({ bypassLoadGate: true });
12861
+ const result = await runDueJobs({ bypassLoadGate: true, human: true });
11802
12862
  return forceTickOutcome(result);
11803
12863
  } catch (e) {
11804
12864
  logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (force-tick)', meta: { error: e?.message } });
@@ -11892,7 +12952,7 @@ function registerScheduleHandlers() {
11892
12952
  ipcMain.handle('schedule:run-now', async () => {
11893
12953
  // Manual run-now overrides any auto-pause. Clear it first.
11894
12954
  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 } }));
12955
+ runDueJobs({ bypassLoadGate: true, human: true }).catch((e) => logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (run-now)', meta: { error: e?.message } }));
11896
12956
  return { ok: true };
11897
12957
  });
11898
12958
 
@@ -12057,6 +13117,7 @@ function stopDispatchLoop() {
12057
13117
  /** Shutdown path: stop the timers this module owns. */
12058
13118
  function stop() {
12059
13119
  stopDispatchLoop();
13120
+ cancelMemoryBackfill();
12060
13121
  }
12061
13122
 
12062
13123
  // Body of the 10-minute maintenance interval (self-heal, escalations, restores).
@@ -12168,7 +13229,7 @@ function rescheduleIntervalTick() {
12168
13229
  // Escalation only, same shape as the quarantine/overrun warnings above.
12169
13230
  const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
12170
13231
  // Each event names the root blocker; a known preflight wait is skipped.
12171
- reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks);
13232
+ reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks, s.config);
12172
13233
 
12173
13234
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
12174
13235
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -12205,7 +13266,7 @@ function rescheduleIntervalTick() {
12205
13266
  mutate(async (ms) => {
12206
13267
  for (const target of autoResetTargets) {
12207
13268
  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
13269
+ if (!j || j.status !== 'failed' || isCancelledRow(j) || (j.failedAutoResetAttempts ?? 0) >= reviewLadder.FAILED_AUTORESET_CAP) continue; // race guard
12209
13270
  const attempt = (j.failedAutoResetAttempts ?? 0) + 1;
12210
13271
  j.failedAutoResetAttempts = attempt;
12211
13272
  const reason = `auto-reset after ${Math.round(reviewLadder.FAILED_AUTORESET_MS / 60_000)}m failed (attempt ${attempt}/${reviewLadder.FAILED_AUTORESET_CAP})`;
@@ -12306,6 +13367,9 @@ async function init() {
12306
13367
  // Hydrate cached state from the sidecar before any scheduling decisions.
12307
13368
  loadSchedulerState();
12308
13369
  bootedAt = Date.now();
13370
+ // Seed the measured memory reservations from the runs folder ~60 s after start,
13371
+ // off the boot path (async batched reads; no-op at ≥ 30 samples).
13372
+ scheduleMemoryBackfill();
12309
13373
 
12310
13374
  // Boot reconciliation: finalize any job that was 'running' when the app died.
12311
13375
  // Check the run log first — a job that emitted result/success before the crash
@@ -12564,6 +13628,9 @@ function toCompactPrdEntry(entry) {
12564
13628
  // Only when set, so the compact page stays small.
12565
13629
  if (entry.heldReason) out.heldReason = entry.heldReason;
12566
13630
  if (entry.waitingOn) out.waitingOn = entry.waitingOn;
13631
+ // A human-cancelled row keeps status failed/needs_review; the marker is
13632
+ // what tells it apart from a real failure (lib/scheduler/cancelledRow.cjs).
13633
+ if (entry.cancelled === true) out.cancelled = true;
12567
13634
  return out;
12568
13635
  }
12569
13636
 
@@ -12636,6 +13703,7 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12636
13703
  deliverable: parsed.deliverable ?? null,
12637
13704
  artifactPaths: parsed.artifactPaths ?? null,
12638
13705
  effort: parsed.effort ?? null,
13706
+ voiceId: parsed.voiceId ?? null,
12639
13707
  disposition: parsed.disposition ?? null,
12640
13708
  planId: parsed.planId ?? null,
12641
13709
  mtimeMs: stat.mtimeMs,
@@ -12719,6 +13787,9 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12719
13787
  entry.archivedStatus = flatString(prdPaths.resolveArchivedPrdStatus(entry.slug, liveStatusBySlug, histBySlug));
12720
13788
  entry.status = entry.archivedStatus;
12721
13789
  }
13790
+ // Cancelled marker from the shared predicate — only when true, so a real
13791
+ // failure carries no cancelled key at all. No new status.
13792
+ if (isCancelledRow(liveRowBySlug.get(entry.slug))) entry.cancelled = true;
12722
13793
  }
12723
13794
 
12724
13795
  out.sort((a, b) => a.slug.localeCompare(b.slug, undefined, { numeric: true }));
@@ -12934,9 +14005,20 @@ const remote = {
12934
14005
  agentType: j.agentType ?? null,
12935
14006
  epicId: j.epicId ?? null,
12936
14007
  sourcePromptId: j.sourcePromptId ?? null,
14008
+ phase: phaseOfJob(j),
14009
+ ...(isCancelledRow(j) ? { cancelled: true } : {}),
12937
14010
  }));
12938
14011
  },
12939
14012
 
14013
+ // Full queue rows for computeEpicOutsideState (lib/epic/epicOutsideState.cjs
14014
+ // reads cancelledAt, statusHistory, error, finishedAt, reviewNotice). GET
14015
+ // /admin/epic(s) must read the same rows as the tick (full state.jobs), or a cancelled row paints an Epic
14016
+ // 'blocked'. Deep copy, never the live objects — and never project here.
14017
+ async listJobRows() {
14018
+ const state = await readQueue();
14019
+ return JSON.parse(JSON.stringify(Array.isArray(state?.jobs) ? state.jobs : []));
14020
+ },
14021
+
12940
14022
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
12941
14023
  // the admin GET /admin/scheduler/prds?slug= route (PRD 1024).
12942
14024
  async getJob(slug) {
@@ -13150,9 +14232,11 @@ const remote = {
13150
14232
  let newBody = body !== undefined ? body : origBody;
13151
14233
  let patchWarnings = [];
13152
14234
  if (hasStructured) {
13153
- const patched = applyStructuredPrdPatch(origBody, structured);
14235
+ const patched = applyStructuredPrdPatch(origBody, { ...structured, previousCriteria: fm.criteria });
13154
14236
  if (!patched.ok) return { ok: false, error: patched.error };
13155
14237
  newBody = patched.body;
14238
+ // Structured criteria (prdCriteria.cjs): frontmatter `criteria` follows the re-rendered list.
14239
+ if (patched.criteria) fm.criteria = patched.criteria;
13156
14240
  patchWarnings = patched.warnings || [];
13157
14241
  }
13158
14242
  const newRaw = serializePrdFile(fm, newBody);
@@ -13224,6 +14308,9 @@ const remote = {
13224
14308
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
13225
14309
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
13226
14310
  }
14311
+ // `interrupt: true` asks for a stop that keeps the session resumable
14312
+ // (human.interrupt) instead of a terminal cancel.
14313
+ if (opts.interrupt === true && job.status === 'running') return this.interruptJob(slug, opts);
13227
14314
  // Dependents choice (PRD 3499): cancelling a row that pending PRDs depend
13228
14315
  // on would strand them behind a dead row (Self stall, 2026-11-22). Refuse
13229
14316
  // unless the caller says what happens to them; apply that choice BEFORE
@@ -13315,6 +14402,8 @@ const remote = {
13315
14402
  j.error = cancelReason;
13316
14403
  j.cancelledAt = cancelledAt;
13317
14404
  if (wasRunning) j.cancelledRunId = job.runId ?? null;
14405
+ // A cancel ends an interrupted row for good: it is no longer continuable.
14406
+ delete j.interrupted;
13318
14407
  j.finishedAt = new Date().toISOString();
13319
14408
  j.exitCode = j.exitCode ?? null;
13320
14409
  if (confirmedLandedCommit) j.verifierVerdict = 'cancelled_with_landed_commit';
@@ -13357,6 +14446,107 @@ const remote = {
13357
14446
  return result;
13358
14447
  },
13359
14448
 
14449
+ // Human interrupt (Managed Agents `human.interrupt`): stops a RUNNING job's
14450
+ // process but does not end the job. The row goes back to 'pending' (phase
14451
+ // idle) with an `interrupted` record holding the run's own CLI session id
14452
+ // (row.sessionId — not row.claudeSessionId, which is the ORIGIN Epic's
14453
+ // session), and is held off the picker (computeInterruptHolds) until
14454
+ // continueJob resumes that same session with `--resume <id>`. The run's
14455
+ // worktree work stays on its job branch, never integrated (isRunCancelled).
14456
+ async interruptJob(slug, opts = {}) {
14457
+ if (!SCHEDULE_SLUG_RE.test(slug)) return { ok: false, error: 'invalid slug' };
14458
+ const state = await readQueue();
14459
+ const job = state.jobs.find((j) => j.slug === slug && (!opts.cwd || j.cwd === opts.cwd));
14460
+ if (!job) return { ok: false, error: `unknown slug "${slug}": no queued job with that name${opts.cwd ? ` in cwd ${opts.cwd}` : ''}` };
14461
+ if (job.status !== 'running') {
14462
+ 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)` };
14463
+ }
14464
+ const sessionId = job.runtime?.sessionId || job.sessionId || null;
14465
+ if (!sessionId) return { ok: false, error: 'job has no session id yet (still launching) — try again in a moment, or cancel it' };
14466
+ const pid = job.runtime?.pid;
14467
+ const runId = job.runId ?? null;
14468
+ const interruptedAt = new Date().toISOString();
14469
+ const reason = 'interrupted by a human — waiting for continue';
14470
+ let applied = false;
14471
+ await mutate((s) => {
14472
+ const j = s.jobs.find((x) => x.slug === slug && x.cwd === job.cwd);
14473
+ if (!j || j.status !== 'running' || (j.runId ?? null) !== runId) return;
14474
+ if (!transitionJob(j, 'pending', { reason, source: 'remote:interruptJob' })) return;
14475
+ j.sessionId = sessionId;
14476
+ j.interrupted = { at: interruptedAt, runId, sessionId };
14477
+ j.heldReason = reason;
14478
+ delete j.runtime;
14479
+ applied = true;
14480
+ });
14481
+ if (!applied) return { ok: false, error: 'job changed state while interrupting — re-read it and try again' };
14482
+ // Stamped before SIGTERM so finalizeJobWorktree (run on executor exit)
14483
+ // keeps the work on the job branch instead of integrating it.
14484
+ if (pid) killOrphanClaudePid(pid);
14485
+ emitJobEvent({ ...job, epicId: job.epicId || job.sourcePromptId }, {
14486
+ kind: 'human.interrupt',
14487
+ slug,
14488
+ runId,
14489
+ sessionId,
14490
+ source: typeof opts.source === 'string' ? opts.source : 'scheduler',
14491
+ });
14492
+ appendAuditEvent('job_interrupted', { slug, cwd: job.cwd ?? null, runId, sessionId });
14493
+ await broadcast({ flush: true });
14494
+ return { ok: true, slug, status: 'pending', phase: 'idle', sessionId, interruptedAt, cwd: job.cwd ?? null };
14495
+ },
14496
+
14497
+ // Continue an interrupted job: dispatch the SAME session via
14498
+ // `--resume <interrupted.sessionId>` (spawnJob with a resumeTarget, like
14499
+ // resume recovery and tool-confirmation resumes). Refused while the old
14500
+ // process is still exiting, when no session slot is free, or while the
14501
+ // auto-dispatch hold (usage threshold / firePolicy 'manual') is in force.
14502
+ // No human bypass: the only caller is the loopback admin route, which any
14503
+ // local process holding the admin token can hit, so it cannot prove a
14504
+ // human pressed anything. A refusal leaves the row interrupted, so the same
14505
+ // call succeeds once the hold clears.
14506
+ async continueJob(slug, opts = {}) {
14507
+ if (!SCHEDULE_SLUG_RE.test(slug)) return { ok: false, error: 'invalid slug' };
14508
+ const state = await readQueue();
14509
+ const job = state.jobs.find((j) => j.slug === slug && (!opts.cwd || j.cwd === opts.cwd));
14510
+ if (!job) return { ok: false, error: `unknown slug "${slug}": no queued job with that name${opts.cwd ? ` in cwd ${opts.cwd}` : ''}` };
14511
+ if (job.status !== 'pending' || !job.interrupted) {
14512
+ return { ok: false, error: `job is not interrupted (status: "${job.status}") — nothing to continue` };
14513
+ }
14514
+ const sessionId = job.interrupted.sessionId || job.sessionId || null;
14515
+ if (!sessionId) return { ok: false, error: 'interrupted job has no session id to resume' };
14516
+ if (runningSet.has(slug)) return { ok: false, error: 'the interrupted run is still shutting down — try again in a moment' };
14517
+ if (sessionSlots.availableFor('job') < 1) return { ok: false, error: 'no session slot free right now — try again when a job finishes' };
14518
+ const hold = currentAutoDispatchHold(state.config);
14519
+ if (hold) {
14520
+ appendAuditEvent('job_continue_held', { slug, reason: hold.reason });
14521
+ return {
14522
+ ok: false,
14523
+ error: `usage hold in force: ${hold.detail} - continue again once it clears`,
14524
+ hold: { reason: hold.reason, window: hold.window, percent: hold.percent, threshold: hold.threshold, resetsAt: hold.resetsAt },
14525
+ };
14526
+ }
14527
+ const target = {
14528
+ sessionId,
14529
+ interrupt: true,
14530
+ dirtyPaths: Array.isArray(job.interrupted.dirtyPaths) ? job.interrupted.dirtyPaths : [],
14531
+ salvagePatch: job.interrupted.salvagePatch || null,
14532
+ message: typeof opts.message === 'string' ? opts.message : null,
14533
+ };
14534
+ await mutate((s) => {
14535
+ const j = s.jobs.find((x) => x.slug === slug && x.cwd === job.cwd);
14536
+ if (!j) return;
14537
+ delete j.interrupted;
14538
+ delete j.heldReason;
14539
+ });
14540
+ appendAuditEvent('job_continued', { slug, cwd: job.cwd ?? null, sessionId });
14541
+ const { runId, dir: runDir } = pickRunDir();
14542
+ const siblingJobs = (await readQueue().catch(() => ({ jobs: [] }))).jobs || [];
14543
+ const fresh = siblingJobs.find((x) => x.slug === slug && x.cwd === job.cwd) || job;
14544
+ // Not awaited: spawnJob runs the whole job (same as tool-confirmation resumes).
14545
+ Promise.resolve(dispatchSpawnJob(fresh, runId, runDir, fresh.cwd || DEFAULT_PROJECT_CWD, target, siblingJobs))
14546
+ .catch((e) => reportSchedulerError('continue after interrupt failed', slug, e));
14547
+ return { ok: true, slug, sessionId, resume: true };
14548
+ },
14549
+
13360
14550
  // Exposes the module-level allocateParallelGroup (PRD 548) to callers that
13361
14551
  // only hold the `remote` object (lib/prd/prdCreate.cjs's create-prd route) —
13362
14552
  // reuses the same allocator the file-based /develop authoring path relies
@@ -13417,6 +14607,29 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
13417
14607
  const result = await remoteObj.resetJob(slug, { force, cwd });
13418
14608
  sendJson(res, 200, result);
13419
14609
  });
14610
+
14611
+ // Interrupt / continue (human.interrupt): stop a running job keeping its
14612
+ // session, then resume that same session with --resume.
14613
+ for (const [route, method] of [['/admin/scheduler/interrupt-job', 'interruptJob'], ['/admin/scheduler/continue-job', 'continueJob']]) {
14614
+ adminHttp.registerRoute('POST', route, async (req, res) => {
14615
+ const raw = await readBody(req);
14616
+ let parsed;
14617
+ try {
14618
+ parsed = raw ? JSON.parse(raw) : {};
14619
+ } catch {
14620
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
14621
+ return;
14622
+ }
14623
+ const slug = parsed && typeof parsed.slug === 'string' ? parsed.slug : null;
14624
+ if (!slug) {
14625
+ sendJson(res, 400, { ok: false, error: 'missing slug' });
14626
+ return;
14627
+ }
14628
+ const cwd = typeof parsed.cwd === 'string' ? parsed.cwd : undefined;
14629
+ const message = typeof parsed.message === 'string' ? parsed.message : undefined;
14630
+ sendJson(res, 200, await remoteObj[method](slug, { cwd, message, source: 'admin-api' }));
14631
+ });
14632
+ }
13420
14633
  }
13421
14634
 
13422
14635
  // queueOps.dismissCancelled needs the serialized queue writer; queueOps
@@ -13431,12 +14644,21 @@ queueOps.bindQueueAccess({
13431
14644
 
13432
14645
  module.exports = {
13433
14646
  PARK_ERRORS,
14647
+ harvestJobArtifacts,
14648
+ jobArtifactRunId,
13434
14649
  applyDepHoldNotices,
13435
14650
  _resetDepHoldNoticesForTests,
13436
14651
  readValidatorGateMs,
13437
14652
  resolveValidatorEstimate,
14653
+ loadValidatorCriteriaContext,
13438
14654
  planJobScope,
13439
14655
  finalizeJobScope,
14656
+ backfillMemoryStats,
14657
+ scheduleMemoryBackfill,
14658
+ cancelMemoryBackfill,
14659
+ MEMORY_BACKFILL_DELAY_MS,
14660
+ heartbeatMemGate,
14661
+ memoryCapFailureReason,
13440
14662
  sampleJobScope,
13441
14663
  readJobCgroupDir,
13442
14664
  normalizeConfig,
@@ -13462,10 +14684,12 @@ module.exports = {
13462
14684
  persistSchedulerState,
13463
14685
  getSchedulerStateSnapshot,
13464
14686
  computeDegradedBudget,
14687
+ utilizationReading,
13465
14688
  writeQueue,
13466
14689
  _setPeriodicReverifyEnabledForTests,
13467
14690
  _setLoadGateForTests,
13468
14691
  _setSpawnJobForTests,
14692
+ _setSpawnInvestigationForTests,
13469
14693
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
13470
14694
  reconcile,
13471
14695
  broadcast,
@@ -13484,9 +14708,7 @@ module.exports = {
13484
14708
  pickForProject,
13485
14709
  reapDeadRunningJobs,
13486
14710
  runBranchSweep,
13487
- runEpicStateWatchForTick,
13488
14711
  pollRecoveryClearSource,
13489
- memoryLimitedBatchSize,
13490
14712
  availableForJobs,
13491
14713
  parseMemInfo,
13492
14714
  readMemInfo,
@@ -13550,6 +14772,7 @@ module.exports = {
13550
14772
  resetJobFields,
13551
14773
  resetRefusalMessage,
13552
14774
  executeJob,
14775
+ applyPersonaRefusalPark,
13553
14776
  killOrphanClaudePid,
13554
14777
  prdArchivedSkipResult,
13555
14778
  spawnJob,
@@ -13575,6 +14798,8 @@ module.exports = {
13575
14798
  spawnInvestigation,
13576
14799
  computeLaunchHolds,
13577
14800
  computePreflightHolds,
14801
+ computeInterruptHolds,
14802
+ buildInterruptContinuePreamble,
13578
14803
  runPreflightGate,
13579
14804
  handleLaunchFailure,
13580
14805
  applyLaunchFailure,