claude-code-session-manager 0.140.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 (204) 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--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.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/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. 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');
118
- const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFromEnv } = require('./lib/scheduler/reviewNotice.cjs');
128
+ const { postArtifactReadyNotice } = require('./lib/epic/artifactNotice.cjs');
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,14 +179,16 @@ const queueOps = require('./queueOps.cjs');
163
179
  const { listEpicPrdDirs, listArchivedPrdDirs, deriveProjectCwdFromPrdPath, isSafeEpicId } = require('./lib/prd/prdLocations.cjs');
164
180
  const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/epic/epicMint.cjs');
165
181
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
182
+ const agentSnapshot = require('./lib/claude/agentSnapshot.cjs');
166
183
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
167
- const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv } = require('./lib/claude/personaToolScope.cjs');
168
- const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured } = require('./lib/scheduler/validatorVerdictSchema.cjs');
184
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames } = require('./lib/claude/personaToolScope.cjs');
185
+ const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured, expectedFromCriteria, formatCriteriaChecksSection } = require('./lib/scheduler/validatorVerdictSchema.cjs');
169
186
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
170
- const { transitionJob, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
187
+ const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
171
188
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
172
189
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
173
190
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
191
+ const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
174
192
  const needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
175
193
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
176
194
 
@@ -207,9 +225,10 @@ const { splitFrontmatter, parsePrdFile, serializePrdFile, isArtifactOnlyDeclarat
207
225
  const { applyStructuredPrdPatch } = require('./lib/prd/prdBodyPatch.cjs');
208
226
  const { resolvePersonaDefaultEstimate, DEFAULT_PRD_AGENT_TYPE } = require('./lib/prd/prdAgentType.cjs');
209
227
  const { resolveDepSlug, findNearMatches, bareSlug } = require('./lib/prd/depSlugResolve.cjs');
210
- const { writeJsonAtomic, readJsonOrSync } = require('./lib/util/atomicFs.cjs');
228
+ const { writeJsonAtomic, readJsonOrSync, readJsonOr } = require('./lib/util/atomicFs.cjs');
211
229
  const { writeToolRiskGuardSettingsFile } = require('./lib/epic/guardSpawnSettings.cjs');
212
230
  const toolRiskMarks = require('./lib/claude/toolRiskMarks.cjs');
231
+ const toolClearance = require('./lib/scheduler/toolClearance.cjs');
213
232
  const { computeDispositionRewrite, mintPlanId, resolveInheritedPlanId } = require('./lib/prd/prdDisposition.cjs');
214
233
  const cancelDependents = require('./scheduler/cancelDependents.cjs');
215
234
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
@@ -421,6 +440,82 @@ function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
421
440
  }
422
441
  }
423
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
+
424
519
  // Validator jobs only (`--json-schema`): the CLI replaces the result text
425
520
  // with the JSON, so the scheduler reads the verdict from structured output.
426
521
  const FINISH_VALIDATOR_VERDICT_LINE = `
@@ -434,6 +529,10 @@ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPl
434
529
  ${commitStepNum}. COMMIT — stage only the exact paths you created or changed for this PRD,
435
530
  then commit:
436
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.
437
536
  Never stage the whole tree with a wildcard or blanket git add.
438
537
  Why: other jobs may be writing files in this same working tree right now.
439
538
  A blanket add puts their half-done work in your commit and breaks both
@@ -521,14 +620,11 @@ const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
521
620
  const HEARTBEAT_MAX_BYTES = 1024 * 1024;
522
621
  // DEFAULT_PROJECT_CWD imported from lib/scheduler/schedulerBatch.cjs (single source of truth).
523
622
 
524
- // Each headless claude -p job can shell out to tsc/vite/pytest and grow well
525
- // past 1 GB at peak; reserve 2.5 GB of PEAK headroom per running+pending slot.
526
- // A running job's already-resident memory is credited back (consumedMb in
527
- // memoryLimitedBatchSize) because MemAvailable is already net of it. Raised from 1.5 GB
528
- // after the 2026-06-16 OOM: 3 concurrent cross-project jobs + their build
529
- // subprocesses pushed a 24 GB host ~10 GB into swap and the OOM killer took
530
- // Electron — every pty got SIGHUP (code=0 signal=1).
531
- 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.
532
628
 
533
629
  // Absolute headroom kept free for the Electron host (main + renderer + GPU) and
534
630
  // the OS — NEVER lent to jobs. Without it the gate green-lights a job whenever
@@ -620,23 +716,6 @@ function swapLimitedBatchSize(mem, runningCount, batchLen) {
620
716
  return Math.min(batchLen, Math.max(0, 1 - runningCount));
621
717
  }
622
718
 
623
- /**
624
- * Pure helper: clamp a batch down so launching `toLaunch` more jobs doesn't
625
- * drop available memory below MIN_FREE_MB_PER_JOB per active slot.
626
- * Exported for unit tests.
627
- */
628
- function memoryLimitedBatchSize(availableMb, minPerJob, runningCount, batchLen, consumedMb = 0) {
629
- if (availableMb === Infinity) return batchLen;
630
- // Credit is bounded by the running jobs' own reservations: never negative,
631
- // never more permissive than a 0-running machine.
632
- const credit = Math.min(Math.max(Number(consumedMb) || 0, 0), minPerJob * runningCount);
633
- let allowed = batchLen;
634
- while (allowed > 0 && availableMb < minPerJob * (runningCount + allowed) - credit) {
635
- allowed--;
636
- }
637
- return allowed;
638
- }
639
-
640
719
  /**
641
720
  * Memory available to LAUNCH jobs with: MemAvailable minus the host reserve,
642
721
  * floored at 0. Keeping the host reserve out of the job budget is what stops the
@@ -677,14 +756,26 @@ const memoryScope = require('./lib/process/memoryScope.cjs');
677
756
  */
678
757
  function planJobScope({ jobSpawn, jobArgs, slug, startedAt, deps = {} }) {
679
758
  // Limits first: with the cap off, never probe systemd.
680
- 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();
681
762
  const supported = limits ? (deps.scopeSupported || memoryScope.scopeSupported)() : false;
682
- if (!supported || !limits) return { spawn: jobSpawn, unit: null };
763
+ if (!supported || !limits) return { spawn: jobSpawn, unit: null, memoryMaxMb: null };
683
764
  const unit = `sm-job-${memoryScope.sanitizeUnit(slug)}-${startedAt}`;
684
765
  const wrapped = (deps.wrapInMemoryScope || memoryScope.wrapInMemoryScope)({
685
766
  command: jobSpawn.command, args: jobSpawn.args || jobArgs, unit, limits,
686
767
  });
687
- 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})`;
688
779
  }
689
780
 
690
781
  /** Reads the job's cgroup dir from /proc/<pid>/cgroup (cgroup v2). Null when unavailable. */
@@ -714,6 +805,78 @@ function sampleJobScope(state, fsImpl = fs) {
714
805
 
715
806
  const JOB_SCOPE_SAMPLE_MS = 30000;
716
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
+
717
880
  /** Starts the unref'd 30 s sampler once cgroupDir is known; finalizeJobScope clears it. */
718
881
  function startJobScopeSampling(state, fsImpl = fs) {
719
882
  if (!state || !state.cgroupDir || state.finalized || state.sampler) return;
@@ -722,7 +885,11 @@ function startJobScopeSampling(state, fsImpl = fs) {
722
885
  if (state.sampler.unref) state.sampler.unref();
723
886
  }
724
887
 
725
- /** 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
+ */
726
893
  function finalizeJobScope(state, safeLog, deps = {}) {
727
894
  if (!state || !state.unit || state.finalized) return;
728
895
  state.finalized = true;
@@ -737,6 +904,13 @@ function finalizeJobScope(state, safeLog, deps = {}) {
737
904
  safeLog(`\n[scheduler] memory scope ${state.unit}: peak=${hasPeak ? `${Math.round(state.peak / 1048576)}MB` : 'n/a'} ` +
738
905
  `oom_kill=${hasOom ? state.oomKills : 'n/a'}\n`);
739
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
+ }
740
914
  } catch { /* stats are best-effort */ }
741
915
  (deps.stopScope || memoryScope.stopScope)(state.unit);
742
916
  }
@@ -884,6 +1058,11 @@ function loadSchedulerState() {
884
1058
  if (typeof s.backoffNextAt === 'number' || s.backoffNextAt === null) backoffNextAt = s.backoffNextAt;
885
1059
  if (typeof s.cachedUtilization === 'number' || s.cachedUtilization === null) cachedUtilization = s.cachedUtilization;
886
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;
887
1066
  } catch { /* first boot or corrupt — start fresh */ }
888
1067
  }
889
1068
 
@@ -892,6 +1071,11 @@ function getSchedulerStateSnapshot() {
892
1071
  return { lastPollOk, lastFailureKind, backoffNextAt, cachedUtilization, cachedBindingWindowName };
893
1072
  }
894
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
+
895
1079
  function persistSchedulerState() {
896
1080
  // Sync write: called from many sync hot paths (clearPause, pollLoop catch
897
1081
  // block) and the sidecar is tiny (<1 KB). Converting to async here would
@@ -928,6 +1112,12 @@ function persistSchedulerState() {
928
1112
  backoffNextAt,
929
1113
  cachedUtilization,
930
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,
931
1121
  });
932
1122
  } catch (e) {
933
1123
  console.warn('[scheduler] failed to persist scheduler state', e?.message);
@@ -1177,8 +1367,9 @@ function heartbeatTick(deps = {}) {
1177
1367
  projects: toAlert, total: summary.total, byProject: summary.byProject, heldByDependency,
1178
1368
  });
1179
1369
  if (mainWindow && !mainWindow.isDestroyed()) {
1370
+ const rootPhrases = toAlert.map((cwd) => rootBlockerPhrase(starveRootFor(projectRowsFor(s.jobs, cwd)).root)).join('');
1180
1371
  sendIfAlive(mainWindow, 'schedule:stall', {
1181
- message: `Scheduler stall in ${toAlert.length} project(s): ${toAlert.join(', ')}. Check the Scheduler tab.`,
1372
+ message: `Scheduler stall in ${toAlert.length} project(s): ${toAlert.join(', ')}.${rootPhrases} Check the Scheduler tab.`,
1182
1373
  projects: toAlert,
1183
1374
  total: summary.total,
1184
1375
  byProject: summary.byProject,
@@ -1239,7 +1430,11 @@ function heartbeatTick(deps = {}) {
1239
1430
  // Which window `utilization` (and nextReset) refer to — a reader of
1240
1431
  // this log can't otherwise tell a 5h hold from a weekly one.
1241
1432
  utilizationWindow: cachedBindingWindowName,
1433
+ utilizationHold,
1242
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),
1243
1438
  // State/consecutiveFailures/degraded-budget snapshot of the shared
1244
1439
  // usage-meter breaker, so a human reading only the heartbeat log can
1245
1440
  // see the meter's own health apart from the queue's.
@@ -1247,6 +1442,9 @@ function heartbeatTick(deps = {}) {
1247
1442
  state: billing.usageCircuit.state(),
1248
1443
  consecutiveFailures,
1249
1444
  degradedBudget: computeDegradedBudget(),
1445
+ // The cap tickQueue actually applies (degradedBudget above is a
1446
+ // display recompute); null = the full slot pool.
1447
+ appliedConcurrencyCap: degradedConcurrencyCapValue,
1250
1448
  },
1251
1449
  };
1252
1450
  });
@@ -1518,15 +1716,15 @@ async function mutateBody(fn) {
1518
1716
  const parsePrdRaw = prdParser.parsePrdRaw;
1519
1717
  const parsePrd = prdParser.parsePrd;
1520
1718
  // Aggregates every candidate PRD dir's files into one flat, sorted list.
1521
- // prdParser's dir-mtime cache is keyed per-dir internally by its own single
1522
- // mtime var, so scanning N dirs here costs N stat+readdir passes rather than
1523
- // one — acceptable: PRD counts per project are bounded (hundreds, not
1524
- // millions), and correctness across multiple project dirs matters more than
1525
- // 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.
1526
1722
  async function listPrdFiles(skipCwds) {
1527
1723
  ensureDirs();
1528
1724
  const dirs = prdPaths.candidatePrdsDirs();
1529
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);
1530
1728
  let files = perDir.flat();
1531
1729
  // A quarantined project has no job rows this pass; scanning its PRDs would
1532
1730
  // mint fresh `pending` rows for work that may already be running.
@@ -1542,28 +1740,6 @@ function quarantinedCwdSet(state) {
1542
1740
  return new Set((state?.unreadableCwds ?? []).map((u) => u.cwd));
1543
1741
  }
1544
1742
 
1545
- /**
1546
- * Best-effort epic_state_changed emission for the tick (lib/epic/epicStateWatcher.cjs).
1547
- * Watches every known project cwd except quarantined shards. Never rejects:
1548
- * any failure is logged as a warning so it can never hold up dispatch.
1549
- * SM_EPIC_STATE_WATCH_DISABLE=1 turns it off. `deps` is a test seam.
1550
- * @param {any} state
1551
- * @param {{ watch?: (o: { cwds: string[], jobs: any }) => Promise<unknown>, listCwds?: () => string[] }} [deps]
1552
- * @returns {Promise<void>}
1553
- */
1554
- async function runEpicStateWatchForTick(state, deps = {}) {
1555
- if (process.env.SM_EPIC_STATE_WATCH_DISABLE === '1') return;
1556
- try {
1557
- const watch = deps.watch ?? require('./lib/epic/epicStateWatcher.cjs').runEpicStateWatch;
1558
- const listCwds = deps.listCwds ?? allProjectCwds;
1559
- const quarantined = quarantinedCwdSet(state);
1560
- const cwds = listCwds().filter((c) => !quarantined.has(c));
1561
- await watch({ cwds, jobs: state?.jobs });
1562
- } catch (e) {
1563
- console.warn('[scheduler] epic state watch failed', /** @type {any} */ (e)?.message);
1564
- }
1565
- }
1566
-
1567
1743
  /**
1568
1744
  * Atomically mint a brand-new parallel-group NN for a PRD about to be
1569
1745
  * authored under the given project's own PRDs dir (falls back to
@@ -1969,6 +2145,8 @@ async function reconcilePass(state) {
1969
2145
  deliverable: p.deliverable ?? job.deliverable ?? null,
1970
2146
  artifactPaths: p.artifactPaths ?? job.artifactPaths ?? null,
1971
2147
  effort: p.effort ?? job.effort ?? null,
2148
+ voiceId: p.voiceId ?? job.voiceId ?? null,
2149
+ preflight: p.preflight ?? null,
1972
2150
  };
1973
2151
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
1974
2152
  // discovered) whose PRD file now carries a stamp — written via the
@@ -2096,6 +2274,8 @@ async function reconcilePass(state) {
2096
2274
  deliverable: p.deliverable ?? inv.row?.deliverable ?? null,
2097
2275
  artifactPaths: p.artifactPaths ?? inv.row?.artifactPaths ?? null,
2098
2276
  effort: p.effort ?? inv.row?.effort ?? null,
2277
+ voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2278
+ preflight: p.preflight ?? null,
2099
2279
  };
2100
2280
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
2101
2281
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -2251,6 +2431,8 @@ async function reconcilePass(state) {
2251
2431
  deliverable: p.deliverable ?? null,
2252
2432
  artifactPaths: p.artifactPaths ?? null,
2253
2433
  effort: p.effort ?? null,
2434
+ voiceId: p.voiceId ?? null,
2435
+ preflight: p.preflight ?? null,
2254
2436
  status: 'pending',
2255
2437
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
2256
2438
  // the starvation escalation both need a provable age for a pending row;
@@ -2339,6 +2521,9 @@ async function reconcilePass(state) {
2339
2521
  }
2340
2522
  } catch { /* stat is best-effort reporting only */ }
2341
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 });
2342
2527
  }
2343
2528
  if (uncovered.size > 0) {
2344
2529
  queueStore.bustCwdCache();
@@ -2422,9 +2607,18 @@ async function reconcilePass(state) {
2422
2607
  let cachedNextReset = null; // bare ISO string or null
2423
2608
  let cachedUtilization = null; // binding-window utilization %, 0–100, or null if unknown
2424
2609
  let cachedBindingWindowName = null; // name/kind of the window cachedUtilization reads (e.g. 'five_hour', 'weekly_all')
2425
- // Non-null while maybeLaunchWhenAvailable is holding the queue on the
2426
- // 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.
2427
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;
2428
2622
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2429
2623
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2430
2624
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -2482,12 +2676,77 @@ function computeDegradedBudget() {
2482
2676
  */
2483
2677
  function applyDegradedBudget() {
2484
2678
  const budget = computeDegradedBudget();
2485
- cachedUtilization = budget.utilization;
2486
- 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.
2487
2691
  degradedConcurrencyCapValue = budget.concurrencyCap;
2488
2692
  return budget;
2489
2693
  }
2490
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
+
2491
2750
  /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2492
2751
  async function refreshNextReset() {
2493
2752
  const r = await billing.fetchUsage();
@@ -2501,6 +2760,7 @@ async function refreshNextReset() {
2501
2760
  recordObservedReset(window.resets_at ?? null);
2502
2761
  cachedUtilization = window.utilization;
2503
2762
  cachedBindingWindowName = window.name;
2763
+ cachedUtilizationKnown = true;
2504
2764
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
2505
2765
  return cachedNextReset;
2506
2766
  }
@@ -2775,6 +3035,14 @@ let lastMemGate = null;
2775
3035
  // predicate after pool → project cap → memory. Withholds launches only.
2776
3036
  let loadGate = createLoadGate();
2777
3037
  function _setLoadGateForTests(gate) { loadGate = gate; }
3038
+ // tickBody's dispatch goes through this indirection so a test can record launches
3039
+ // without forking a real child job (whose completion tick races the next test).
3040
+ let dispatchSpawnJob = (...args) => spawnJob(...args);
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)); }
2778
3046
 
2779
3047
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2780
3048
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2830,26 +3098,15 @@ function applyPauseCleared(wasPaused, token) {
2830
3098
  return token;
2831
3099
  }
2832
3100
 
2833
- /**
2834
- * Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
2835
- * to the renderer via lastTick.detail. Names the gate, the measured ratio,
2836
- * the threshold and how long this gate itself has held a batch that slots and
2837
- * memory admitted (heldMs). Pure so it's unit-testable without driving tickQueue's full
2838
- * fs/worktree machinery.
2839
- */
2840
- function formatLoadGateDetail(load) {
2841
- const heldMinutes = Math.round(load.heldMs / 60_000);
2842
- const cpu = load.cpuBusy == null
2843
- ? 'no CPU sample yet'
2844
- : `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
2845
- return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
2846
- }
3101
+ // formatLoadGateDetail (the load-deferred tick's lastTick.detail) lives in
3102
+ // lib/scheduler/loadGate.cjs beside the fields it reads.
2847
3103
 
2848
3104
  function loadGateAuditFields(load) {
2849
3105
  return {
2850
3106
  loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2851
- // 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).
2852
3108
  cpuBusy: load.cpuBusy, cpuBusyRaw: load.cpuBusyRaw, cpuBusyNet: load.cpuBusyNet, cpuOwnBusy: load.cpuOwnBusy,
3109
+ cpuIdleNice: load.cpuIdleNice,
2853
3110
  cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2854
3111
  };
2855
3112
  }
@@ -2869,7 +3126,12 @@ function attachWindow(w) { mainWindow = w; }
2869
3126
  function buildScheduleStatePayload(state) {
2870
3127
  const payload = {
2871
3128
  config: state.config,
2872
- 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,
2873
3135
  lastRunAt: state.lastRunAt,
2874
3136
  // Distinct from lastRunAt (only stamped when a batch actually launches):
2875
3137
  // stamped every time tickQueue reaches the picker at all. See
@@ -3207,10 +3469,17 @@ function resetJobFields(job, errorMsg, opts = {}) {
3207
3469
  if ((job.status === 'completed' || job.status === 'skipped') && opts.force !== true) return false;
3208
3470
  // Durable cancel (2026-10-19 git-viewer incident): a human-cancelled row is
3209
3471
  // revived only by an explicit human reset, never by an automated pass.
3210
- 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;
3473
+ // Reset means "re-check the precondition now": the hold is dropped even
3474
+ // when the row is already pending (pending→pending is not a transition).
3475
+ delete job.preflightHold;
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;
3211
3478
  if (!transitionJob(job, 'pending', { reason: errorMsg ?? 'reset to pending', source: opts.source ?? 'resetJobFields' })) return false;
3212
3479
  delete job.cancelledAt;
3213
3480
  delete job.cancelledRunId;
3481
+ // A reset restarts from scratch: an interrupted session is not resumed.
3482
+ delete job.interrupted;
3214
3483
  job.runId = null;
3215
3484
  job.startedAt = null;
3216
3485
  job.finishedAt = null;
@@ -3486,6 +3755,31 @@ function applyOrphanOutcomeInner(job, outcome, killNote, confirmedLandedCommit,
3486
3755
  }
3487
3756
  }
3488
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
+
3489
3783
  /**
3490
3784
  * isNotifiableTerminalStatus(effectiveStatus) → boolean
3491
3785
  *
@@ -3672,6 +3966,64 @@ async function resolveValidatorEstimate(job, { readGateMs = readValidatorGateMs
3672
3966
  }
3673
3967
  }
3674
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
+
3675
4027
  function defaultScheduleSettle({ cwd, epicId }) {
3676
4028
  const deps = {
3677
4029
  loadJobs: async () => (await readQueue()).jobs || [],
@@ -3872,6 +4224,7 @@ async function notifyOriginatingTab(job, {
3872
4224
  readStructuredFromLog = extractStructuredOutputFromLog,
3873
4225
  writeVerdictsFile = writeJsonAtomic,
3874
4226
  scheduleSettle = defaultScheduleSettle,
4227
+ loadValidatorCriteria = loadValidatorCriteriaContext,
3875
4228
  } = {}) {
3876
4229
  try {
3877
4230
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -3966,7 +4319,17 @@ async function notifyOriginatingTab(job, {
3966
4319
  } catch (e) {
3967
4320
  console.error('[scheduler] notifyOriginatingTab readStructuredFromLog error', job?.slug, e);
3968
4321
  }
3969
- 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 });
3970
4333
  if (checked.ok) {
3971
4334
  checkedVerdict = checked.value;
3972
4335
  verdicts = verdictRowsFromStructured(checked.value);
@@ -4019,14 +4382,19 @@ async function notifyOriginatingTab(job, {
4019
4382
  } else if (epicId && checkedVerdict && job.cwd) {
4020
4383
  // PRD 3614: keep the checked object beside the Markdown plan record.
4021
4384
  try {
4022
- const file = opsPath(job.cwd, 'plan-records', epicId, `${bareSlug(job.slug)}.verdicts.json`);
4023
- assertOpsWrite(file, 'scheduler');
4024
- await writeVerdictsFile(file, {
4025
- validator: job.slug,
4026
- runId: job.runId || null,
4027
- at: new Date().toISOString(),
4028
- schedulerVerdict: checkedVerdict.schedulerVerdict,
4029
- 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
+ },
4030
4398
  });
4031
4399
  } catch (e) {
4032
4400
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
@@ -4633,6 +5001,40 @@ async function requeueForeignWipBlockedJobs(jobs, { getDirtyPaths = gitTreeGuard
4633
5001
  * exact paths recorded on the parked job row so the resumed run can verify
4634
5002
  * them on disk before trusting them, rather than re-deriving them itself.
4635
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
+
4636
5038
  function buildResumeRecoveryPreamble({ dirtyPaths, salvagePatch }) {
4637
5039
  const pathList = dirtyPaths.map((p) => `- ${p}`).join('\n');
4638
5040
  const salvageLine = salvagePatch
@@ -5081,7 +5483,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5081
5483
  return out;
5082
5484
  }
5083
5485
 
5084
- 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 }) {
5085
5487
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5086
5488
  let riskArgs = [];
5087
5489
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5094,7 +5496,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5094
5496
  '--model', model,
5095
5497
  ...effortArgs(effort),
5096
5498
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5097
- ...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,
5098
5502
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5099
5503
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5100
5504
  ...riskArgs,
@@ -5187,6 +5591,162 @@ function ensureTimeoutShimOnce() {
5187
5591
  return timeoutShimEnsured;
5188
5592
  }
5189
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
+
5190
5750
  /**
5191
5751
  * Execute a single PRD job. Writes stdout/stderr to a log file and a meta
5192
5752
  * JSON sidecar. Accepts an optional onPid(pid) callback called synchronously
@@ -5272,7 +5832,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5272
5832
  // session already has that in its own conversation history via
5273
5833
  // --resume, and re-embedding it here would just contradict whatever
5274
5834
  // state the session actually left on disk.
5275
- 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 });
5276
5840
  } else {
5277
5841
  // Read full PRD body fresh from disk (queue stored only the preview).
5278
5842
  // Resolve through findPrdDirForJob's full candidate search (legacy flat
@@ -5438,6 +6002,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5438
6002
  isArtifactOnly = false;
5439
6003
  }
5440
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
+ }
5441
6012
  prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
5442
6013
 
5443
6014
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
@@ -5464,10 +6035,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5464
6035
  // PRD agentType → persona + model (PRD 1115): resolved for both fresh and
5465
6036
  // resume dispatches, keyed off job.agentType (persisted on the queue row
5466
6037
  // by reconcile()) rather than re-reading the PRD file — a resumed session
5467
- // must keep launching as the SAME persona it started as. Never throws;
5468
- // a dangling/absent agentType falls back to no persona + FALLBACK_MODEL
5469
- // and is logged once by resolvePrdPersonaForSpawn itself.
5470
- 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
+ }
5471
6063
  if (resumeTarget) {
5472
6064
  try {
5473
6065
  const dir = await prdPaths.findPrdDirForJob(job);
@@ -5497,21 +6089,47 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5497
6089
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5498
6090
  // capped) persona body — the persona cap never applies to laws. Fresh and
5499
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];
5500
6098
  let packArgs = { pluginDirArgs: [], laws: '' };
6099
+ /** @type {string[]|null} null = catalog unavailable (no pack refusal) */
6100
+ let unknownPacks = null;
5501
6101
  try {
5502
- const packEpicId = job.epicId || job.sourcePromptId;
5503
- const packEpic = packEpicId ? agentModelResolve.findEpicById(cwd, packEpicId) : null;
5504
- const composed = packSpawnArgs.composePackSpawnArgs({ packIds: packEpic?.packs });
6102
+ const composed = packSpawnArgs.composePackSpawnArgs({ packIds: jobPackIds.length ? jobPackIds : packEpic?.packs });
5505
6103
  if (composed && Array.isArray(composed.pluginDirArgs)) {
5506
6104
  packArgs = { pluginDirArgs: composed.pluginDirArgs, laws: typeof composed.laws === 'string' ? composed.laws : '' };
6105
+ unknownPacks = Array.isArray(composed.unknown) ? composed.unknown.map(String) : [];
5507
6106
  }
5508
6107
  } catch (err) {
5509
6108
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
5510
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
+ }
5511
6129
  const jobSystemPrompt = packArgs.laws
5512
6130
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
5513
6131
  : personaResolution.systemPrompt;
5514
- 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`);
5515
6133
 
5516
6134
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
5517
6135
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -5544,6 +6162,18 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5544
6162
  // `launchEnv` is the launch circuit breaker's degraded-mode env (e.g.
5545
6163
  // MAX_THINKING_TOKENS=0 while an outdated CLI's thinking parameter is
5546
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;
5547
6177
  const childEnv = cleanChildEnv({
5548
6178
  PATH: withTimeoutShimOnPath(pathWithUserBins()),
5549
6179
  SM_PROJECT_ROOT: cwd,
@@ -5551,10 +6181,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5551
6181
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5552
6182
  ...personaToolScopeEnv(personaToolScope),
5553
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 } : {}),
5554
6186
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5555
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 } : {}),
5556
6191
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
5557
6192
  });
6193
+ // cleanChildEnv inherits process.env; a job without a valid voiceId must never carry one.
6194
+ if (!jobVoiceId) delete childEnv.SM_VOICE_ID;
5558
6195
  // Set AFTER cleanChildEnv returns, never inside the object passed to it:
5559
6196
  // cleanChildEnv strips every CLAUDE_CODE_*-prefixed key from its own
5560
6197
  // merged result (see cleanEnv.cjs), so setting it there would delete its
@@ -5562,6 +6199,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5562
6199
  // it starts has nothing to report back to — same stall as a tool that
5563
6200
  // waits for one.
5564
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
+ }
5565
6209
  if (launchEnv && Object.keys(launchEnv).length) {
5566
6210
  safeLog(`[scheduler] launch mitigation env applied: ${Object.entries(launchEnv).map(([k, v]) => `${k}=${v}`).join(' ')}\n`);
5567
6211
  }
@@ -5670,13 +6314,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5670
6314
  // is calibrated against). Only a PRD with an
5671
6315
  // explicit `budgetExempt: true` opts out entirely — logged once here so
5672
6316
  // an unbounded job is never silently unbounded.
5673
- const budgetEstimate = budget.resolveBudgetEstimate({
5674
- estimateMinutes: job.estimateMinutes,
5675
- validatorEstimate,
5676
- personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
5677
- });
5678
- const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
5679
- 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.
5680
6319
  if (budgetExempt) {
5681
6320
  safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
5682
6321
  `(budgetExempt) — no wall-clock kill ceiling this run\n`);
@@ -5728,9 +6367,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5728
6367
  // never move it under the run directory.
5729
6368
  const sandboxDeps = resolveJobSandboxDeps();
5730
6369
  const sandboxAgentType = job.agentType || 'dev-lead';
6370
+ const jobEnvironment = resolveJobEnvironment(cwd, sandboxAgentType, safeLog);
6371
+ const enforcementMode = environmentEnforcement();
5731
6372
  /** @type {string|null} */
5732
6373
  let sandboxTmpDir = null;
5733
- if (sandboxDeps.available && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, sandboxAgentType)) {
6374
+ if (sandboxDeps.available && jobEnvironment && jobEnvironment.profile.osSandboxRequired) {
5734
6375
  try {
5735
6376
  sandboxTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smj-'));
5736
6377
  } catch (e) {
@@ -5744,16 +6385,50 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5744
6385
  };
5745
6386
  const sandboxPolicy = buildJobSandboxSettings({
5746
6387
  agentType: sandboxAgentType,
6388
+ environment: jobEnvironment,
5747
6389
  worktreeDir: spawnCwd,
5748
6390
  projectRoot: cwd,
5749
6391
  homeDir: os.homedir(),
5750
6392
  tmpDir: sandboxTmpDir || os.tmpdir(),
5751
6393
  deps: sandboxDeps,
6394
+ mode: enforcementMode,
5752
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
+ }
5753
6416
  // childEnv was built (and cleanChildEnv already ran) above.
5754
6417
  Object.assign(childEnv, sandboxChildEnv(sandboxPolicy, sandboxTmpDir || os.tmpdir()));
5755
- const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir };
5756
- 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'} ` +
5757
6432
  `network=${sandboxMeta.network ? (sandboxMeta.network.join(',') || 'none') : 'unrestricted'} reason=${sandboxMeta.reason ?? 'none'} ` +
5758
6433
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
5759
6434
  const jobArgs = buildClaudeSpawnArgs({
@@ -5764,28 +6439,56 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5764
6439
  resume: !!resumeTarget,
5765
6440
  systemPrompt: jobSystemPrompt,
5766
6441
  toolScope: personaToolScope,
6442
+ mcpServerNames: personaResolution.mcpServers || [],
5767
6443
  pluginDirArgs: packArgs.pluginDirArgs,
5768
6444
  jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5769
6445
  riskGuardSettingsPath,
5770
6446
  });
5771
6447
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5772
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
+
5773
6463
  // Pre-spawn argv guard: one oversized argument makes spawn throw E2BIG.
5774
6464
  const oversized = launchFailure.findOversizedArg(jobSpawn.args || jobArgs);
5775
6465
  if (oversized) {
5776
6466
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5777
6467
  safeLog(`[scheduler] ${errMsg}\n`);
5778
6468
  closeFd();
5779
- 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 });
5780
6470
  removeSandboxTmp();
5781
6471
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5782
6472
  return;
5783
6473
  }
5784
6474
 
5785
6475
  const scopePlan = planJobScope({ jobSpawn, jobArgs, slug: job.slug, startedAt });
5786
- 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' };
5787
6477
  const launchSpawn = scopePlan.spawn;
5788
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
+
5789
6492
  const { child } = withChildAndLog({
5790
6493
  fd,
5791
6494
  logPath,
@@ -5811,8 +6514,9 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5811
6514
  ...detachedSpawnOpts(),
5812
6515
  },
5813
6516
  },
5814
- watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
6517
+ watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog, ...(toolUseWatchdog ? [toolUseWatchdog] : [])],
5815
6518
  onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
6519
+ if (toolUseEmitter) { try { toolUseEmitter.flush(); } catch { /* never breaks the exit path */ } }
5816
6520
  const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
5817
6521
  const durationMs = Date.now() - startedAt;
5818
6522
  finalizeJobScope(scopeState, sl);
@@ -5829,7 +6533,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5829
6533
  sl(`\n[scheduler] ${errMsg}\n`);
5830
6534
  // Sync write: inside a Promise executor callback; must flush meta
5831
6535
  // before resolve() so the spawnJob mutate() that follows sees it.
5832
- 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 });
5833
6537
  removeSandboxTmp();
5834
6538
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5835
6539
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
@@ -5857,6 +6561,14 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5857
6561
  }
5858
6562
  sl(`\n[scheduler] exit code=${effectiveCode} (raw code=${exitCode} signal=${signal}) ` +
5859
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
+ }, () => {});
5860
6572
  const rateLimited = effectiveCode !== 0 && detectRateLimitInLog(logPath);
5861
6573
  const networkError = effectiveCode !== 0 && !rateLimited && detectNetworkErrorInLog(logPath);
5862
6574
  // Non-run detection (issue #11 lists A1–A3): the harness's `result`
@@ -5893,14 +6605,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5893
6605
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5894
6606
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5895
6607
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6608
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapKill: { oomKills: scopeState.oomKills, memoryMaxMb: scopeState.memoryMaxMb ?? null } } : {}),
5896
6609
  sandbox: sandboxMeta,
5897
6610
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5898
6611
  originSessionId, contextDigestApplied,
6612
+ agentSnapshotId: personaResolution.agentSnapshotId || null,
5899
6613
  });
5900
6614
  removeSandboxTmp();
5901
6615
  resolve({
5902
6616
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5903
6617
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6618
+ ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
5904
6619
  });
5905
6620
  },
5906
6621
  });
@@ -5996,7 +6711,7 @@ function isPromotableOriginal(status) {
5996
6711
  */
5997
6712
  function healTargetForFix(fixSlug, jobs) {
5998
6713
  const originalSlug = fixSlug.replace(/^(\d+)-fix-/, '$1-');
5999
- 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;
6000
6715
  }
6001
6716
 
6002
6717
  /**
@@ -6004,7 +6719,7 @@ function healTargetForFix(fixSlug, jobs) {
6004
6719
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
6005
6720
  * spawnInvestigation computes.
6006
6721
  */
6007
- 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 }) {
6008
6723
  const runtimePaths = RUNTIME_NAMESPACES.map((ns) => `session-manager-operations/${ns}/`).join(', ');
6009
6724
  const recordRule = (recordPath && !recordIgnored)
6010
6725
  ? `- The only allowed record location is ${recordPath}. If the fix plan asks for a record file, it must be exactly this path.
@@ -6120,7 +6835,6 @@ ${logTail}
6120
6835
  ---
6121
6836
  title: Fix: <short summary of the fix>
6122
6837
  cwd: ${cwd}
6123
- parallelGroup: ${group}
6124
6838
  estimateMinutes: <your time estimate>
6125
6839
  isFixPlan: true
6126
6840
  ---
@@ -6133,6 +6847,7 @@ ${logTail}
6133
6847
  not that repo (e.g. a scratch dir like \`/tmp\`), set \`cwd:\` to the correct repo root instead —
6134
6848
  the scheduler's commit guard and post-run verifier read git state from this path, and a
6135
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.
6136
6851
  6. The PRD body MUST be self-contained — \`claude -p\` runs it on a fresh Sonnet session with NO conversation context. Include:
6137
6852
  - Root-cause analysis (what went wrong and why)
6138
6853
  - Concrete fix steps (specific files / commands / edits)
@@ -6208,12 +6923,30 @@ function readRunOutcomeSidecars(runDir, slug) {
6208
6923
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
6209
6924
 
6210
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
+ }
6938
+ // A row waiting on its own red preflight spends nothing on the model
6939
+ // ladder: the precondition is the cause, not the work.
6940
+ if (reviewLadder.hasActivePreflightHold(failedJob)) {
6941
+ console.log(`[scheduler] skip investigation: ${failedJob.slug} is held on its preflight`);
6942
+ return { deferred: false };
6943
+ }
6211
6944
  // The probe launches with the same CLI as the job it diagnoses. While
6212
6945
  // that CLI cannot launch at all (launch circuit breaker, issue #11 list
6213
6946
  // B1: probes e4f82da2/d374e6bf died on the same HTTP 400 as the runs
6214
6947
  // they were investigating) there is nothing to diagnose — skip, loudly.
6215
6948
  {
6216
- const state = await readQueue().catch(() => null);
6949
+ const state = queueState;
6217
6950
  const block = state?.launchBlocks?.[INVESTIGATION_LAUNCH_KEY];
6218
6951
  const jobBlock = state?.launchBlocks?.[launchFailure.launchBlockKeyFor(failedJob)];
6219
6952
  const gate = launchFailure.evaluateLaunchGate(block || jobBlock, { now: Date.now(), claudeVersion: await probeClaudeVersion() });
@@ -6299,7 +7032,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6299
7032
  // archived twin (archivedPrdPathForJob) is deliberately NOT used for the
6300
7033
  // write dir, only for reading originalBody below.
6301
7034
  let originalBody = '';
6302
- const { fixPath, fixSlug, group, livePrdDir } = await resolveFixPlanPath(failedJob);
7035
+ const { fixPath, fixSlug, livePrdDir } = await resolveFixPlanPath(failedJob);
6303
7036
  try {
6304
7037
  const originalPath = livePrdDir ? path.join(livePrdDir, `${failedJob.slug}.md`) : prdPaths.archivedPrdPathForJob(failedJob);
6305
7038
  originalBody = (await parsePrd(originalPath)).body;
@@ -6353,7 +7086,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6353
7086
  } catch (err) {
6354
7087
  recordIgnored = !(err && err.code === 1);
6355
7088
  }
6356
- 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 });
6357
7090
 
6358
7091
  // Phase 1: open log fd for pre-spawn diagnostics.
6359
7092
  const { fd, safeLog, closeFd } = openLog(investigationLogPath);
@@ -6385,7 +7118,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6385
7118
  await mutate((s) => {
6386
7119
  const j = s.jobs.find((x) => x.slug === failedJob.slug);
6387
7120
  if (!j) return;
6388
- const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !reviewLadder.isCancelledJob(j);
7121
+ const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !isCancelledRow(j) && !reviewLadder.hasActivePreflightHold(j);
6389
7122
  const transitioned = statusEligible && transitionJob(j, 'investigating', { reason: 'spawning investigation probe', source: 'spawnInvestigation:start' });
6390
7123
  liveCheck = { ok: statusEligible && transitioned, status: j.status };
6391
7124
  });
@@ -6529,7 +7262,9 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6529
7262
  // status here) is otherwise reset-refused by design.
6530
7263
  if (deadChild) {
6531
7264
  const child = s.jobs.find((x) => x.slug === deadChild.slug);
6532
- if (child) {
7265
+ // A child held on its own red preflight is left alone — the
7266
+ // reset would drop the hold and re-fire it into the same wall.
7267
+ if (child && !reviewLadder.hasActivePreflightHold(child)) {
6533
7268
  resetJobFields(child, 'reset by dead-fix-plan reopen: parent investigation authored a new plan', {
6534
7269
  force: true, source: 'spawnInvestigation:dead-fix-plan-reopen',
6535
7270
  });
@@ -6803,6 +7538,9 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6803
7538
  appendAuditEvent('job_cancel_integration_skipped', { slug: job.slug, runId, branch: worktree.branch });
6804
7539
  await pinUnlanded();
6805
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 });
6806
7544
  return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead, uncommittedSnapshot };
6807
7545
  }
6808
7546
  if (worktreeHead.action === 'diverged') {
@@ -6858,7 +7596,12 @@ async function isRunCancelled(slug, runId) {
6858
7596
  try {
6859
7597
  const state = await readQueue();
6860
7598
  const row = state.jobs.find((j) => j.slug === slug);
6861
- 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));
6862
7605
  } catch {
6863
7606
  return false;
6864
7607
  }
@@ -6891,6 +7634,187 @@ function guardedTick(fn, label) {
6891
7634
  }
6892
7635
  }
6893
7636
 
7637
+ /**
7638
+ * Pending rows whose preflight hold is not yet due → Map<slug, heldReason>,
7639
+ * in the same shape computeLaunchHolds returns, so the picker skips them
7640
+ * (and they never shadow a pickable sibling) while a dependent of a held
7641
+ * row still sees it as a blocking dep.
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
+
7679
+ function computePreflightHolds(jobs, now = Date.now()) {
7680
+ const held = new Map();
7681
+ for (const j of jobs || []) {
7682
+ if (!j || j.status !== 'pending' || !j.preflightHold) continue;
7683
+ const next = Date.parse(j.preflightHold.nextAt ?? '');
7684
+ if (Number.isFinite(next) && next > now) {
7685
+ held.set(j.slug, j.heldReason || `waiting on precondition: ${j.preflight} — re-check at ${j.preflightHold.nextAt}`);
7686
+ }
7687
+ }
7688
+ return held;
7689
+ }
7690
+
7691
+ /**
7692
+ * Run job.preflight (cwd = the job's project cwd, no shell) and record the
7693
+ * outcome on the queue row. Returns 'held' when the job must not launch
7694
+ * (check failed, or the hold is not yet due), else 'pass'.
7695
+ */
7696
+ async function runPreflightGate(job, defaultCwd, { now = Date.now } = {}) {
7697
+ const command = job.preflight.trim();
7698
+ const prevHold = job.preflightHold || null;
7699
+ const dueAt = prevHold ? Date.parse(prevHold.nextAt ?? '') : NaN;
7700
+ if (Number.isFinite(dueAt) && dueAt > now()) return 'held';
7701
+ const result = await preflightCheck.runPreflight({ command, cwd: job.cwd || defaultCwd });
7702
+ if (result.ok) {
7703
+ const attempts = prevHold && Number.isFinite(prevHold.attempts) ? prevHold.attempts : 0;
7704
+ await mutate((s) => {
7705
+ const row = s.jobs.find((x) => x.slug === job.slug);
7706
+ if (!row) return;
7707
+ delete row.preflightHold;
7708
+ delete row.heldReason;
7709
+ });
7710
+ delete job.preflightHold;
7711
+ delete job.heldReason;
7712
+ try { appendAuditEvent('preflight_pass', { slug: job.slug, attempts }); } catch { /* audit must not break dispatch */ }
7713
+ return 'pass';
7714
+ }
7715
+ const heldAt = now();
7716
+ let hold = null;
7717
+ let projectRows = [];
7718
+ await mutate((s) => {
7719
+ const row = s.jobs.find((x) => x.slug === job.slug);
7720
+ hold = armPreflightHoldOnRow(row, prevHold, result, command, heldAt, `make \`${command}\` exit 0`);
7721
+ projectRows = snapshotProjectRows(s.jobs, row || job);
7722
+ });
7723
+ job.preflightHold = hold;
7724
+ auditPreflightHold(job.slug, command, result, hold);
7725
+ await broadcast({ flush: true });
7726
+ await sendPreflightHoldNotice(job, hold, projectRows);
7727
+ return 'held';
7728
+ }
7729
+
7730
+ /** Shallow copies of `job`'s project rows (for heldSlugs) — safe outside mutate(). */
7731
+ function snapshotProjectRows(jobs, job) {
7732
+ const cwd = job?.cwd || DEFAULT_PROJECT_CWD;
7733
+ return projectRowsFor(jobs, cwd).map((j) => ({ ...j }));
7734
+ }
7735
+
7736
+ // Preflight hold notices already sent this process, by preflightHoldNoticeKey.
7737
+ const preflightHoldNoticesSent = new Set();
7738
+ let preflightHoldNoticeSender = null;
7739
+ function _setPreflightHoldNoticeSenderForTests(fn) { preflightHoldNoticeSender = fn || null; }
7740
+ function _resetPreflightHoldNoticesForTests() { preflightHoldNoticesSent.clear(); }
7741
+
7742
+ /**
7743
+ * sendPreflightHoldNotice(job, hold, projectRows) → Promise<boolean>
7744
+ *
7745
+ * The ONE informational Epic notice for a preflight hold, sent the moment it
7746
+ * first arms (hold.attempts === 1) — not behind SM_REVIEW_NOTICE_HOLD_MINUTES.
7747
+ * Same Epic delivery as the grouped needs_review notice
7748
+ * (appendResponseEventWithReason, allowInactive), tagged notice:
7749
+ * 'preflight-hold' with no outcome, so it never asks for input. Deduped by
7750
+ * preflightHoldNoticeKey(slug, hold.since); a re-check failure (attempts > 1)
7751
+ * sends nothing. heldSlugs = the row itself plus every pending row whose root
7752
+ * blocker it is. Never throws.
7753
+ */
7754
+ async function sendPreflightHoldNotice(job, hold, projectRows = []) {
7755
+ try {
7756
+ if (!job || !hold || hold.attempts !== 1) return false;
7757
+ const key = preflightHoldNoticeKey(job.slug, hold.since);
7758
+ if (preflightHoldNoticesSent.has(key)) return false;
7759
+ preflightHoldNoticesSent.add(key);
7760
+ const cwd = job.cwd || DEFAULT_PROJECT_CWD;
7761
+ const epicId = job.sourcePromptId || job.epicId || null;
7762
+ if (!epicId || !cwd) {
7763
+ console.log(`[scheduler] ${job.slug}: preflight hold notice — no authoring Epic, report only`);
7764
+ return false;
7765
+ }
7766
+ const roots = starvation.rootBlockersForProject(Array.isArray(projectRows) ? projectRows : []);
7767
+ const mine = roots.find((r) => r.slug === job.slug);
7768
+ const heldSlugs = [job.slug, ...(mine ? mine.heldSlugs.filter((x) => x !== job.slug) : [])];
7769
+ const text = buildPreflightHoldNotice({
7770
+ slug: job.slug,
7771
+ failText: hold.failText,
7772
+ preflight: typeof job.preflight === 'string' ? job.preflight.trim() : '',
7773
+ heldSlugs,
7774
+ nextAt: hold.nextAt,
7775
+ });
7776
+ const send = preflightHoldNoticeSender || appendResponseEventWithReason;
7777
+ const result = await send(cwd, epicId, text, {
7778
+ prdSlug: job.slug,
7779
+ validation: 'unvalidated',
7780
+ notice: 'preflight-hold',
7781
+ digestKey: key,
7782
+ allowInactive: true,
7783
+ });
7784
+ const ok = typeof result === 'boolean' ? result : !!result?.ok;
7785
+ if (!ok) console.warn(`[scheduler] ${job.slug}: preflight hold notice not delivered (${result?.reason ?? 'refused'})`);
7786
+ return ok;
7787
+ } catch (e) {
7788
+ console.error('[scheduler] sendPreflightHoldNotice error', job?.slug, e);
7789
+ return false;
7790
+ }
7791
+ }
7792
+
7793
+ /**
7794
+ * Arm (or climb) the preflight hold on a queue row from a red runPreflight
7795
+ * result. Sync — call inside mutate(). Shared by the dispatch gate and the
7796
+ * sentinel_fail park reroute so both write the same hold + heldReason shape.
7797
+ * Returns the hold (also when `row` is null, from `prevHold`).
7798
+ */
7799
+ function armPreflightHoldOnRow(row, prevHold, result, command, heldAt, failText) {
7800
+ const code = result.exitCode ?? (result.timedOut ? 'timeout' : 'null');
7801
+ const base = row ? (row.preflightHold || null) : (prevHold || null);
7802
+ const hold = preflightCheck.armPreflightHold(base, result, heldAt, failText);
7803
+ if (row) {
7804
+ row.preflightHold = hold;
7805
+ row.heldReason = `waiting on precondition: ${command} exited ${code} — re-check at ${hold.nextAt}`;
7806
+ }
7807
+ return hold;
7808
+ }
7809
+
7810
+ function auditPreflightHold(slug, command, result, hold, extra = {}) {
7811
+ const code = result.exitCode ?? (result.timedOut ? 'timeout' : 'null');
7812
+ console.log(`[scheduler] ${slug}: preflight hold — ${command} exited ${code}; re-check at ${hold.nextAt}`);
7813
+ try {
7814
+ appendAuditEvent('preflight_hold', { slug, attempts: hold.attempts, nextAt: hold.nextAt, exitCode: result.exitCode, ...extra });
7815
+ } catch { /* audit must not break dispatch */ }
7816
+ }
7817
+
6894
7818
  async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
6895
7819
  // PRD 1408: the queue rows in scope at dispatch (tickQueue's own
6896
7820
  // state.jobs, threaded straight down — never re-read here or inside
@@ -6920,6 +7844,17 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6920
7844
  // silently.
6921
7845
  const quietLeaseAcquired = job.quietMachine === true && quietMachineLease.acquire(job.slug);
6922
7846
  try {
7847
+ // Preflight hold (preflightCheck.cjs): a PRD whose work needs an external
7848
+ // precondition a person controls declares one cheap command. Checked
7849
+ // BEFORE the worktree is created and before the 'running' transition, so
7850
+ // a red precondition costs no claude -p run and no checkout — the row
7851
+ // stays 'pending' with a preflightHold and is re-checked on the
7852
+ // 10/20/40/60-min-then-hourly backoff. Exit 0 clears the hold and
7853
+ // dispatch continues unchanged, so dependents flow with no manual reset.
7854
+ if (!resumeTarget && typeof job.preflight === 'string' && job.preflight.trim()) {
7855
+ const gate = await runPreflightGate(job, defaultCwd);
7856
+ if (gate === 'held') return;
7857
+ }
6923
7858
  // Worktree isolation cap check (PRD 1112) — probed BEFORE the job is
6924
7859
  // marked 'running', so a job that can't get isolation right now is a
6925
7860
  // DEFERRAL, not a fallback: it stays 'pending' and is retried on the
@@ -7303,6 +8238,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7303
8238
  // shape for the whole run). Named generically (not "worktree...") because
7304
8239
  // an in-place run salvages one too (PRD 1098).
7305
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;
7306
8245
  let uncommittedSnapshot = null;
7307
8246
  // Which foreign-WIP shape applies to THIS run: an isolated worktree only
7308
8247
  // ever needs to disclose carriedPaths (its checkout starts clean apart
@@ -7317,6 +8256,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7317
8256
  const idx = s.jobs.findIndex((x) => x.slug === job.slug);
7318
8257
  if (idx >= 0) {
7319
8258
  s.jobs[idx].sessionId = sessionId;
8259
+ if (job.agentSnapshotId) s.jobs[idx].agentSnapshotId = job.agentSnapshotId;
7320
8260
  s.jobs[idx].runtime = { pid, runId, startedAt: s.jobs[idx].startedAt, sessionId, cwd };
7321
8261
  s.jobs[idx].dispatchPhase = 'spawned';
7322
8262
  s.jobs[idx].dispatchPhaseAt = new Date().toISOString();
@@ -7338,6 +8278,21 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7338
8278
  // them to the main checkout before verify and before the checkout is
7339
8279
  // removed. Never throws (planRecordHarvest.cjs).
7340
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 });
7341
8296
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
7342
8297
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
7343
8298
  } else {
@@ -7401,6 +8356,14 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7401
8356
  // a sibling); an in-place run on the baseline delta.
7402
8357
  const jobDirt = worktree.ok ? stripAppOwnedChurn(worktreeLeftoverDirty) : newlyDirtyAll;
7403
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
+ }
7404
8367
  if (res.launchFailure) {
7405
8368
  await handleLaunchFailure({ job, res, runId, runDir, launchKey, launchEnv, claudeVersion: claudeVersionNow });
7406
8369
  return;
@@ -7584,7 +8547,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7584
8547
  priorLandedCommit,
7585
8548
  jobLandedCommitThisRun,
7586
8549
  exitCode: res.exitCode,
7587
- worktreeDir: worktree.ok ? worktree.dir : null,
8550
+ artifactEvidence,
7588
8551
  }).catch((e) => ({
7589
8552
  verdict: 'verify_unavailable',
7590
8553
  reason: `verifier threw: ${e?.message ?? String(e)}`,
@@ -7816,12 +8779,32 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7816
8779
  }
7817
8780
  }
7818
8781
 
8782
+ // Preflight park reroute: a run with a `preflight` that ended in an
8783
+ // executor SCHEDULER_VERDICT: FAIL re-checks its precondition once. Red →
8784
+ // the precondition is the cause; the row goes back to pending with a
8785
+ // preflightHold (below, inside mutate) and spends nothing on the model
8786
+ // ladder. Green or check error → the ordinary park runs unchanged.
8787
+ // I/O here, outside mutate(), like every other pre-finalize check.
8788
+ let preflightRerouteResult = null;
8789
+ const preflightRerouteCmd = typeof job.preflight === 'string' ? job.preflight.trim() : '';
8790
+ if (preflightRerouteCmd && res.exitCode === 0 && !res.rateLimited && verifyResult?.verdict === 'sentinel_fail') {
8791
+ try {
8792
+ const r = await preflightCheck.runPreflight({ command: preflightRerouteCmd, cwd: job.cwd || defaultCwd });
8793
+ if (r && r.ok === false) preflightRerouteResult = r;
8794
+ } catch (e) {
8795
+ reportSchedulerError('preflight park re-check failed', job.slug, e);
8796
+ }
8797
+ }
8798
+ let preflightRerouteHold = null;
8799
+ let preflightRerouteRows = [];
8800
+
7819
8801
  let actuallyFailed = false;
7820
8802
  let failedJobSnapshot = null;
7821
8803
  let needsInvestigationNow = false;
7822
8804
  let investigationJobSnapshot = null;
7823
8805
  let investigationDeadChildSnapshot = null;
7824
8806
  let needsReviewRcaSnapshot = null;
8807
+ let outcomeRecordSnapshot = null; // every completed/failed/needs_review finalize (prdOutcomeRecord.cjs)
7825
8808
  let resumeRecoveryJob = null;
7826
8809
  let resumeRecoveryTarget = null;
7827
8810
  let quarantineJob = null;
@@ -7996,6 +8979,23 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7996
8979
  effectiveStatus = 'needs_review';
7997
8980
  }
7998
8981
 
8982
+ if (
8983
+ preflightRerouteResult
8984
+ && effectiveStatus === 'needs_review'
8985
+ && !sigtermOverrideReason
8986
+ && !capParkVerdict
8987
+ && verifyResult?.verdict === 'sentinel_fail'
8988
+ ) {
8989
+ const row = s.jobs[i2];
8990
+ const failText = String(verifyResult.reason || '').replace(/^executor reported\s+/, '') || 'SCHEDULER_VERDICT: FAIL';
8991
+ if (jobLandedCommitThisRun) row.landedCommit = jobLandedCommitThisRun;
8992
+ if (resetJobFields(row, `preflight red after SCHEDULER_VERDICT: FAIL — ${failText}`, { source: 'scheduler:preflight-hold' })) {
8993
+ preflightRerouteHold = armPreflightHoldOnRow(row, null, preflightRerouteResult, preflightRerouteCmd, Date.now(), failText);
8994
+ preflightRerouteRows = snapshotProjectRows(s.jobs, row);
8995
+ return; // row is pending + held; no park, no ladder
8996
+ }
8997
+ }
8998
+
7999
8999
  // already_satisfied_on_main names the satisfying sha in its own
8000
9000
  // reason — surface that on the completed row's statusHistory
8001
9001
  // instead of the generic "run finished with exit 0" every other
@@ -8020,6 +9020,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8020
9020
  // is ALSO set (e.g. a real exit failure whose branch also failed
8021
9021
  // to integrate must show both, not just the first one).
8022
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
+ }
8023
9028
  // Persist the commit THIS run landed (if HEAD advanced) so a later
8024
9029
  // re-fire of the same slug can prove its own no-op re-run is
8025
9030
  // truthful via the pass_no_commit_prior_run_verified exemption.
@@ -8138,6 +9143,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8138
9143
  // attribute" via its Array.isArray guard, same as an empty array.
8139
9144
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
8140
9145
 
9146
+ if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9147
+ outcomeRecordSnapshot = { ...s.jobs[i2] };
9148
+ }
8141
9149
  if (isNotifiableTerminalStatus(effectiveStatus)) {
8142
9150
  terminalNotifySnapshot = { ...s.jobs[i2] };
8143
9151
  }
@@ -8206,7 +9214,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8206
9214
  const fixSlugExists = (slug) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${slug}.md`)));
8207
9215
  if (
8208
9216
  process.env.SM_AUTOFIX_DISABLE !== '1' &&
8209
- 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)
8210
9221
  ) {
8211
9222
  const isRetryAttempt = s.jobs[i2].autoFixAttempted === true;
8212
9223
  const isDeadFixPlanReopen = reviewLadder.isFixPlanDead(s.jobs[i2], s.jobs);
@@ -8253,7 +9264,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8253
9264
  for (const { slug, cwd } of newlyCompletedPrds) {
8254
9265
  await prdPaths.archiveCompletedPrd(slug, cwd);
8255
9266
  }
9267
+ if (preflightRerouteHold) auditPreflightHold(job.slug, preflightRerouteCmd, preflightRerouteResult, preflightRerouteHold, { after: 'sentinel_fail' });
8256
9268
  await broadcast({ flush: true });
9269
+ if (preflightRerouteHold) await sendPreflightHoldNotice(job, preflightRerouteHold, preflightRerouteRows);
8257
9270
 
8258
9271
  // Per-run outcome sidecar (issue #11 list B5): turns/tokens/verdict in one
8259
9272
  // small JSON next to the log so fleet health never needs a transcript parse.
@@ -8276,6 +9289,17 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8276
9289
  strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
8277
9290
  });
8278
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
+
8279
9303
  if (terminalNotifySnapshot) {
8280
9304
  notifyOriginatingTab(terminalNotifySnapshot).catch((e) => {
8281
9305
  console.error('[scheduler] notifyOriginatingTab error', job.slug, e);
@@ -8539,12 +9563,186 @@ async function reclaimTerminalJobOrphansThrottled(state) {
8539
9563
  * with the 'running' transition).
8540
9564
  */
8541
9565
  async function spawnResumeRecovery(job, resumeTarget) {
8542
- const { runId, dir: runDir } = pickRunDir();
8543
9566
  // No queue rows in scope here (unlike tickQueue's own dispatch loop) — read
8544
9567
  // once, before delegating to spawnJob, so hasDownstreamValidator still
8545
- // 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();
8546
9729
  const siblingJobs = (await readQueue().catch(() => ({ jobs: [] }))).jobs || [];
8547
- 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
+ }
8548
9746
  }
8549
9747
 
8550
9748
  // Serialized ticker: prevents two concurrent tickQueue() calls from racing
@@ -8599,11 +9797,14 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
8599
9797
  }
8600
9798
  }
8601
9799
 
8602
- 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 } = {}) {
8603
9804
  const budgetMs = tickWatchdogMs();
8604
9805
  const next = tickTail.then(() => {
8605
9806
  const gen = tickGeneration;
8606
- return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
9807
+ return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort, human }), budgetMs, () => {
8607
9808
  tickGeneration++; // fence the abandoned body
8608
9809
  console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
8609
9810
  if (!tickWedgeLatched) {
@@ -8626,10 +9827,13 @@ function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
8626
9827
  // The stale sentinel a fenced body returns: never recorded, never acted on.
8627
9828
  const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
8628
9829
 
8629
- async function tickBody(gen, { bypassLoadGate, lastResort }) {
9830
+ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
8630
9831
  const tickStartedAt = Date.now();
8631
9832
  // evaluate() only runs once slots and memory admit a batch, so the CPU sampler
8632
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();
8633
9837
  loadGate.observe();
8634
9838
  {
8635
9839
  const stale = () => gen !== tickGeneration;
@@ -8687,12 +9891,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8687
9891
  reclaimTerminalJobOrphansThrottled(state).catch((e) => {
8688
9892
  console.warn('[scheduler] terminal job-worktree orphan reclaim failed', e?.message);
8689
9893
  });
8690
- // Emit epic_state_changed audit rows for Epics whose outside-facing state
8691
- // moved since the last tick. Best-effort and fire-and-forget: never awaited,
8692
- // must never hold up dispatch.
8693
- runEpicStateWatchForTick(state).catch((e) => {
8694
- console.warn('[scheduler] epic state watch failed', e?.message);
8695
- });
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;
8696
9900
  // Session-Manager's machine-wide slot pool is the ONLY concurrency limit
8697
9901
  // the picker answers to (plus the memory gate below). The scheduler used
8698
9902
  // to also carry a private `concurrencyCap` of 3 — the exact per-consumer
@@ -8704,10 +9908,44 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8704
9908
  // second pool: the row count admitted this tick simply can't exceed the
8705
9909
  // degraded cap minus what's already running.
8706
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
+ }
8707
9943
  const freeSlots = degradedConcurrencyCapValue != null
8708
9944
  ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8709
9945
  : sessionSlots.availableFor('job');
8710
9946
  const heldSlugs = await computeLaunchHolds(state);
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);
8711
9949
  if (stale()) return STALE_TICK;
8712
9950
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8713
9951
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -8775,28 +10013,39 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8775
10013
  const jobBudgetMb = availableForJobs(availableMb, RESERVED_HOST_MB);
8776
10014
  // The slot pool already bounded `batch` (it was passed as freeSlots to
8777
10015
  // pickNextBatch above), so only the memory gate can narrow it further.
8778
- // Credit each running job's already-resident RSS (capped at its reservation)
8779
- // — MemAvailable is already net of it. Unknown pid / 0 MB read = no credit.
8780
- 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 = [];
8781
10022
  if (availableMb !== Infinity) {
8782
10023
  for (const j of state.jobs) {
8783
10024
  if (!runningSet.has(j.slug)) continue;
8784
10025
  const pid = j.runtime?.pid ?? j.pid;
8785
- if (!Number.isInteger(pid) || pid <= 0) continue;
8786
- consumedMb += Math.min(processGroupRssMb(pid), MIN_FREE_MB_PER_JOB);
8787
- }
8788
- consumedMb = Math.min(consumedMb, MIN_FREE_MB_PER_JOB * runningSet.size);
8789
- }
8790
- const allowed = memoryLimitedBatchSize(
8791
- jobBudgetMb, MIN_FREE_MB_PER_JOB, runningSet.size, batch.length, consumedMb,
8792
- );
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
+ };
8793
10041
  if (allowed === 0) {
8794
- const threshold = RESERVED_HOST_MB + MIN_FREE_MB_PER_JOB * (runningSet.size + 1) - consumedMb;
8795
- 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)`);
8796
- 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() };
8797
10046
  return recordTick(
8798
- { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, threshold, consumedMb },
8799
- { 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 },
8800
10049
  );
8801
10050
  }
8802
10051
  const swapAllowed = swapLimitedBatchSize(memInfo, runningSet.size, allowed);
@@ -8816,8 +10065,9 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8816
10065
  }
8817
10066
  const gatedBatch = batch.slice(0, swapAllowed);
8818
10067
  if (gatedBatch.length < batch.length) {
8819
- 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)`);
8820
- 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() };
8821
10071
  } else {
8822
10072
  // Ungated full batch: clear stale gate snapshot so status doesn't show
8823
10073
  // a stale deferral from a previous tick.
@@ -8897,7 +10147,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8897
10147
  // state.jobs is the queue's rows in scope at THIS dispatch (PRD 1408) —
8898
10148
  // threaded straight through so spawnJob's hasDownstreamValidator check
8899
10149
  // never re-reads the queue itself.
8900
- spawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
10150
+ dispatchSpawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
8901
10151
  issued += 1;
8902
10152
  }
8903
10153
  if (issued > 0) {
@@ -8958,7 +10208,7 @@ function forceTickOutcome(result) {
8958
10208
  }
8959
10209
  }
8960
10210
 
8961
- async function runDueJobs({ bypassLoadGate = false } = {}) {
10211
+ async function runDueJobs({ bypassLoadGate = false, human = false } = {}) {
8962
10212
  const state = await readQueue();
8963
10213
  if (state.unreadable) {
8964
10214
  console.error('[scheduler] runDueJobs skipped: queue.json unreadable');
@@ -8969,31 +10219,21 @@ async function runDueJobs({ bypassLoadGate = false } = {}) {
8969
10219
  return { fired: false, reason: 'paused' };
8970
10220
  }
8971
10221
  cancelToken = { cancelled: false };
8972
- const result = await tickQueue({ bypassLoadGate });
10222
+ const result = await tickQueue({ bypassLoadGate, human });
8973
10223
  await broadcast();
8974
10224
  return result;
8975
10225
  }
8976
10226
 
8977
10227
  // ---------- when-available launch logic ----------
8978
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.
8979
10231
  async function maybeLaunchWhenAvailable(state) {
8980
- utilizationHold = null;
8981
10232
  if (state.config.firePolicy !== 'when-available') return;
8982
10233
  if (state.paused) return;
8983
10234
  const pending = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug));
8984
10235
  if (pending.length === 0) return;
8985
10236
  if (cachedUtilization === null || cachedUtilization === undefined) return;
8986
- if (cachedUtilization >= state.config.utilizationThreshold) {
8987
- utilizationHold = {
8988
- window: cachedBindingWindowName,
8989
- percent: cachedUtilization,
8990
- threshold: state.config.utilizationThreshold,
8991
- resetsAt: cachedNextReset,
8992
- };
8993
- console.log(`[scheduler] when-available: utilization-held — ${cachedBindingWindowName ?? 'unknown'} window at ${cachedUtilization}% ≥ ${state.config.utilizationThreshold}%, resets ${cachedNextReset ?? 'unknown'}, ${pending.length} pending — holding, not ticking`);
8994
- await broadcast();
8995
- return;
8996
- }
8997
10237
  console.log(`[scheduler] when-available: util=${cachedUtilization}%, ${pending.length} pending, ${runningSet.size} running — ticking`);
8998
10238
  tickQueue().catch((e) => console.error('[scheduler] tickQueue error', e));
8999
10239
  }
@@ -9017,6 +10257,9 @@ async function runQueueStarvationWatchdog(state, {
9017
10257
  now = Date.now(), thresholdMs = starvation.QUEUE_STARVATION_MS,
9018
10258
  bootedAtMs = Date.parse(SCHEDULER_BOOTED_AT), pauseClearedAtMs = lastPauseClearedAt,
9019
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;
9020
10263
  // The idle clock is launch-keyed (dispatchIdleMs): NOT lastDispatchAttemptAt,
9021
10264
  // which tickQueue stamps before every gate — a queue whose 30 s loop ticks
9022
10265
  // and launches nothing would refresh it forever and the watchdog would
@@ -9137,12 +10380,87 @@ const starveEscalated = new Set();
9137
10380
  * gate. Exported for direct unit testing (attach a fake window via
9138
10381
  * attachWindow() first to assert the toast send).
9139
10382
  */
9140
- function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
9141
- const { toEscalate, toClear } = starvation.selectStarveEscalations(starvedProjects, starveEscalated, STARVE_ESCALATION_MS);
10383
+ function projectRowsFor(jobs, cwd) {
10384
+ return (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === cwd);
10385
+ }
10386
+
10387
+ /**
10388
+ * starveRootFor(projectRows, oldestPendingSlug) → { root, knownWait }
10389
+ *
10390
+ * `root`: the root blocker (starvation.rootBlockersForProject) holding the
10391
+ * oldest pending row, else the first one found, else null. `knownWait`: every
10392
+ * pending row is either itself preflight-held or waits on a preflight-held
10393
+ * root — the scheduler re-checks those on its own backoff, so the project is
10394
+ * waiting on a precondition, not starved.
10395
+ */
10396
+ function starveRootFor(projectRows, oldestPendingSlug = null) {
10397
+ const roots = starvation.rootBlockersForProject(projectRows);
10398
+ const root = roots.find((r) => r.heldSlugs.includes(oldestPendingSlug)) ?? roots[0] ?? null;
10399
+ let knownWait = false;
10400
+ if (roots.length > 0 && roots.every((r) => r.preflightHeld)) {
10401
+ const waiting = new Set(roots.flatMap((r) => r.heldSlugs));
10402
+ for (const r of roots) waiting.add(r.slug);
10403
+ knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
10404
+ }
10405
+ return { root, knownWait };
10406
+ }
10407
+
10408
+ function rootBlockingFields(root) {
10409
+ return {
10410
+ rootBlockingSlug: root?.slug ?? null,
10411
+ rootBlockingStatus: root?.status ?? null,
10412
+ rootBlockingReason: root?.reason ?? null,
10413
+ };
10414
+ }
10415
+
10416
+ /** Toast/log phrase naming the root blocker, or '' when there is none. */
10417
+ function rootBlockerPhrase(root) {
10418
+ if (!root) return '';
10419
+ return ` Waiting on ${root.slug} (${root.status}${root.reason ? `: ${root.reason}` : ''}).`;
10420
+ }
10421
+
10422
+ /**
10423
+ * reportStarvedProjects(starvedProjects, jobs, launchBlocks) — the per-sweep
10424
+ * project_starved WARN + audit (each naming the root blocker), then the
10425
+ * bounded escalation. A known wait (starveRootFor) is skipped by both.
10426
+ */
10427
+ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}, config = undefined) {
10428
+ for (const sp of starvedProjects) {
10429
+ const { root, knownWait } = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
10430
+ if (knownWait) continue;
10431
+ console.warn(
10432
+ `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
10433
+ + `waiting=${Math.round(sp.ageMs / 60_000)}m (>= ${Math.round(STARVATION_ESCALATE_MS / 60_000)}m threshold) `
10434
+ + `while other projects are running${root ? ` — root blocker ${root.slug} (${root.status}${root.reason ? `: ${root.reason}` : ''})` : ' — check the cross-project fairness rule in pickNextBatch'}`,
10435
+ );
10436
+ appendAuditEvent('project_starved', {
10437
+ cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, ...rootBlockingFields(root),
10438
+ });
10439
+ }
10440
+ // Bounded, automated consequence for a starve that outlives the WARN
10441
+ // above (PRD: the 2026-09-12 19h Bilko starve had ~115 identical
10442
+ // project_starved rows and zero consequence). STARVE_ESCALATION_MS is
10443
+ // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
10444
+ // a subset of the rows already reported above — same verdict, no
10445
+ // re-derivation.
10446
+ runStarveEscalationSweep(starvedProjects, jobs, launchBlocks, config);
10447
+ }
10448
+
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;
10452
+ const rootByCwd = new Map();
10453
+ const reportable = starvedProjects.filter((sp) => {
10454
+ const r = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
10455
+ rootByCwd.set(sp.cwd, r.root);
10456
+ return !r.knownWait;
10457
+ });
10458
+ const { toEscalate, toClear } = starvation.selectStarveEscalations(reportable, starveEscalated, STARVE_ESCALATION_MS);
9142
10459
  for (const cwd of toClear) starveEscalated.delete(cwd);
9143
10460
  for (const sp of toEscalate) {
9144
10461
  starveEscalated.add(sp.cwd);
9145
- const projectRows = (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === sp.cwd);
10462
+ const projectRows = projectRowsFor(jobs, sp.cwd);
10463
+ const root = rootByCwd.get(sp.cwd) ?? null;
9146
10464
  const holdReason = starvation.describeStarveHold({ projectRows, launchBlocks, lastTick, lastHoldTick });
9147
10465
  const mins = Math.round(sp.ageMs / 60_000);
9148
10466
  console.error(
@@ -9151,11 +10469,11 @@ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {})
9151
10469
  + 'a bounded escalation only; nothing was auto-reset, cancelled, or dispatched',
9152
10470
  );
9153
10471
  appendAuditEvent('project_starve_escalated', {
9154
- cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason,
10472
+ cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason, ...rootBlockingFields(root),
9155
10473
  });
9156
10474
  sendIfAlive(mainWindow, 'schedule:stall', {
9157
10475
  message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), no dispatch for ~${mins}m `
9158
- + `(hold reason: ${holdReason}) — check the Scheduler tab.`,
10476
+ + `(hold reason: ${holdReason}).${rootBlockerPhrase(root)} Check the Scheduler tab.`,
9159
10477
  total: sp.pendingCount,
9160
10478
  byProject: { [sp.cwd]: { starved: sp.pendingCount } },
9161
10479
  });
@@ -10047,6 +11365,11 @@ async function pollLoop() {
10047
11365
  // YELLOW/RED forever even though nothing is actually degraded.
10048
11366
  if (billing.usageCircuit.state() !== 'closed') billing.usageCircuit.recordSuccess({});
10049
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;
10050
11373
  degradedConcurrencyCapValue = null;
10051
11374
  consecutiveFailures = 0;
10052
11375
  backoffMs = 0;
@@ -10111,6 +11434,7 @@ async function pollLoop() {
10111
11434
  recordObservedReset(window.resets_at ?? null);
10112
11435
  cachedUtilization = window.utilization;
10113
11436
  cachedBindingWindowName = window.name;
11437
+ cachedUtilizationKnown = true;
10114
11438
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
10115
11439
  degradedConcurrencyCapValue = null;
10116
11440
  consecutiveFailures = 0;
@@ -10156,8 +11480,12 @@ async function pollLoop() {
10156
11480
  lastGoodUsagePayload = r.cached;
10157
11481
  cachedUtilization = cachedBudget.utilization;
10158
11482
  cachedBindingWindowName = cachedBudget.name;
11483
+ cachedUtilizationKnown = true;
10159
11484
  degradedConcurrencyCapValue = null;
10160
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;
10161
11489
  applyDegradedBudget();
10162
11490
  }
10163
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`);
@@ -10300,7 +11628,7 @@ function selectHistoryJobs(jobs, limit, historyEntries = []) {
10300
11628
  * guard-parked row was never "exhausted auto-fix" and must never claim to be.
10301
11629
  */
10302
11630
  function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10303
- 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;
10304
11632
  if ((j.exhaustedResolveAttempts ?? 0) > reviewLadder.NEEDS_REVIEW_RESOLVE_CAP) return null;
10305
11633
  const originIsGuardParked = !reviewLadder.isExhaustedAutoFix(j) && reviewLadder.isGuardParkedWithoutAutoFix(j);
10306
11634
 
@@ -10351,7 +11679,7 @@ function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
10351
11679
  * 'skipped', or null when the race guard rejects it.
10352
11680
  */
10353
11681
  function applyStuckFailedAutoSkip(j, ageMs = 0) {
10354
- if (!j || j.status !== 'failed' || reviewLadder.isCancelledJob(j)) return null;
11682
+ if (!j || j.status !== 'failed' || isCancelledRow(j)) return null;
10355
11683
  if ((j.failedAutoResetAttempts ?? 0) < reviewLadder.FAILED_AUTORESET_CAP) return null;
10356
11684
  const cap = reviewLadder.FAILED_AUTORESET_CAP;
10357
11685
  j.needsReviewAutoResolvedSkip = true;
@@ -10621,6 +11949,20 @@ async function runGateShadow(job) {
10621
11949
  const definitive = headStable && cleanOk && (outcome.status === 'green' || outcome.status === 'red');
10622
11950
  const gateShadow = { ...outcome, head: headBefore, source: gate.source, ranAt: new Date().toISOString(), definitive, ...(mainDeps ? { mainDeps } : {}) };
10623
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
+
10624
11966
  // Gate authority: a green re-run may complete the row outright, but only
10625
11967
  // for transcript-noise verdicts with a landed commit — every other park
10626
11968
  // (including no verdict at all) falls through to the plain observe-only
@@ -10713,7 +12055,8 @@ async function runGateShadow(job) {
10713
12055
  if (fs.existsSync(path.dirname(verdictsPath))) {
10714
12056
  let existing = {};
10715
12057
  try { existing = JSON.parse(fs.readFileSync(verdictsPath, 'utf8')) || {}; } catch { /* absent/unparseable → fresh */ }
10716
- 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 */ }
10717
12060
  }
10718
12061
  }
10719
12062
 
@@ -11314,7 +12657,13 @@ async function reverifyNeedsReview() {
11314
12657
  const targets = reviewLadder.selectAutoFixTargets(queueForResumeAndAutofix.jobs, {
11315
12658
  fixSlugExists: (s) => prdPaths.candidatePrdsDirs().some((dir) => fs.existsSync(path.join(dir, `${s}.md`))),
11316
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();
11317
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;
11318
12667
  const runId = job.runId || reviewLadder.resolveRunId(job);
11319
12668
  const runDir = path.join(schedulerPaths.runsDir(), runId);
11320
12669
  const isRetryAttempt = job.autoFixAttempted === true;
@@ -11341,7 +12690,7 @@ async function reverifyNeedsReview() {
11341
12690
  }
11342
12691
  });
11343
12692
  console.log(`[scheduler] auto-fix: needs_review ${job.slug} → authoring fix-plan (${isRetryAttempt ? 'retry' : '1/1'}${isDeadFixPlanReopen ? ', dead fix-plan child reopen' : ''})`);
11344
- spawnInvestigation(job, runDir, { deadChild }).catch((e) => {
12693
+ dispatchSpawnInvestigation(job, runDir, { deadChild }).catch((e) => {
11345
12694
  console.error('[scheduler] auto-fix spawnInvestigation error', job.slug, e);
11346
12695
  });
11347
12696
  }
@@ -11509,7 +12858,7 @@ function registerScheduleHandlers() {
11509
12858
  // Clears any existing pause first (same semantics as run-now).
11510
12859
  await clearPause('run-now');
11511
12860
  try {
11512
- const result = await runDueJobs({ bypassLoadGate: true });
12861
+ const result = await runDueJobs({ bypassLoadGate: true, human: true });
11513
12862
  return forceTickOutcome(result);
11514
12863
  } catch (e) {
11515
12864
  logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (force-tick)', meta: { error: e?.message } });
@@ -11603,7 +12952,7 @@ function registerScheduleHandlers() {
11603
12952
  ipcMain.handle('schedule:run-now', async () => {
11604
12953
  // Manual run-now overrides any auto-pause. Clear it first.
11605
12954
  await clearPause('run-now');
11606
- 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 } }));
11607
12956
  return { ok: true };
11608
12957
  });
11609
12958
 
@@ -11768,6 +13117,7 @@ function stopDispatchLoop() {
11768
13117
  /** Shutdown path: stop the timers this module owns. */
11769
13118
  function stop() {
11770
13119
  stopDispatchLoop();
13120
+ cancelMemoryBackfill();
11771
13121
  }
11772
13122
 
11773
13123
  // Body of the 10-minute maintenance interval (self-heal, escalations, restores).
@@ -11878,21 +13228,8 @@ function rescheduleIntervalTick() {
11878
13228
  // started" — the 2026-09-01 NN-ordering starvation ran 3.5 h unnoticed.
11879
13229
  // Escalation only, same shape as the quarantine/overrun warnings above.
11880
13230
  const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
11881
- for (const sp of starvedProjects) {
11882
- console.warn(
11883
- `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
11884
- + `waiting=${Math.round(sp.ageMs / 60_000)}m (>= ${Math.round(STARVATION_ESCALATE_MS / 60_000)}m threshold) `
11885
- + `while other projects are running — check the cross-project fairness rule in pickNextBatch`,
11886
- );
11887
- appendAuditEvent('project_starved', { cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs });
11888
- }
11889
- // Bounded, automated consequence for a starve that outlives the WARN
11890
- // above (PRD: the 2026-09-12 19h Bilko starve had ~115 identical
11891
- // project_starved rows and zero consequence). STARVE_ESCALATION_MS is
11892
- // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
11893
- // a subset of the rows already reported above — same verdict, no
11894
- // re-derivation.
11895
- runStarveEscalationSweep(starvedProjects, s.jobs, s.launchBlocks);
13231
+ // Each event names the root blocker; a known preflight wait is skipped.
13232
+ reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks, s.config);
11896
13233
 
11897
13234
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
11898
13235
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -11929,7 +13266,7 @@ function rescheduleIntervalTick() {
11929
13266
  mutate(async (ms) => {
11930
13267
  for (const target of autoResetTargets) {
11931
13268
  const j = ms.jobs.find((x) => x.slug === target.slug);
11932
- 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
11933
13270
  const attempt = (j.failedAutoResetAttempts ?? 0) + 1;
11934
13271
  j.failedAutoResetAttempts = attempt;
11935
13272
  const reason = `auto-reset after ${Math.round(reviewLadder.FAILED_AUTORESET_MS / 60_000)}m failed (attempt ${attempt}/${reviewLadder.FAILED_AUTORESET_CAP})`;
@@ -12030,6 +13367,9 @@ async function init() {
12030
13367
  // Hydrate cached state from the sidecar before any scheduling decisions.
12031
13368
  loadSchedulerState();
12032
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();
12033
13373
 
12034
13374
  // Boot reconciliation: finalize any job that was 'running' when the app died.
12035
13375
  // Check the run log first — a job that emitted result/success before the crash
@@ -12284,7 +13624,14 @@ async function init() {
12284
13624
  // archivedStatus); `fields=full` restores them.
12285
13625
  function toCompactPrdEntry(entry) {
12286
13626
  const { slug, title, cwd, mtimeMs, archived, status, agentType } = entry;
12287
- return { slug, title, cwd, mtimeMs, archived, status, agentType };
13627
+ const out = { slug, title, cwd, mtimeMs, archived, status, agentType };
13628
+ // Only when set, so the compact page stays small.
13629
+ if (entry.heldReason) out.heldReason = entry.heldReason;
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;
13634
+ return out;
12288
13635
  }
12289
13636
 
12290
13637
  /**
@@ -12356,6 +13703,7 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12356
13703
  deliverable: parsed.deliverable ?? null,
12357
13704
  artifactPaths: parsed.artifactPaths ?? null,
12358
13705
  effort: parsed.effort ?? null,
13706
+ voiceId: parsed.voiceId ?? null,
12359
13707
  disposition: parsed.disposition ?? null,
12360
13708
  planId: parsed.planId ?? null,
12361
13709
  mtimeMs: stat.mtimeMs,
@@ -12403,6 +13751,29 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12403
13751
  queueHistory.historyTerminalBySlug().catch(() => new Map()),
12404
13752
  ]);
12405
13753
  const liveStatusBySlug = new Map(state.jobs.map((j) => [j.slug, j.status]));
13754
+ // heldReason (the live row's own) + waitingOn (the root blocker slug of a
13755
+ // dependency-blocked pending row, starvation.rootBlockersForProject).
13756
+ const liveRowBySlug = new Map(state.jobs.map((j) => [j.slug, j]));
13757
+ const waitingOnBySlug = new Map();
13758
+ const jobsByCwd = new Map();
13759
+ for (const j of state.jobs) {
13760
+ if (!j) continue;
13761
+ const key = j.cwd || DEFAULT_PROJECT_CWD;
13762
+ if (!jobsByCwd.has(key)) jobsByCwd.set(key, []);
13763
+ jobsByCwd.get(key).push(j);
13764
+ }
13765
+ for (const rows of jobsByCwd.values()) {
13766
+ if (!rows.some((j) => j.status === 'pending' && Array.isArray(j.dependsOn) && j.dependsOn.length > 0)) continue;
13767
+ for (const r of starvation.rootBlockersForProject(rows)) {
13768
+ for (const held of r.heldSlugs) waitingOnBySlug.set(held, r.slug);
13769
+ }
13770
+ }
13771
+ for (let i = 0; i < archivedStart; i++) {
13772
+ const entry = out[i];
13773
+ const live = liveRowBySlug.get(entry.slug);
13774
+ entry.heldReason = live && typeof live.heldReason === 'string' && live.heldReason ? flatString(live.heldReason) : null;
13775
+ entry.waitingOn = waitingOnBySlug.get(entry.slug) ?? null;
13776
+ }
12406
13777
  for (let i = 0; i < out.length; i++) {
12407
13778
  const entry = out[i];
12408
13779
  // `entry` is a freshly-synthesized PRD-listing row, not a persisted
@@ -12416,6 +13787,9 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
12416
13787
  entry.archivedStatus = flatString(prdPaths.resolveArchivedPrdStatus(entry.slug, liveStatusBySlug, histBySlug));
12417
13788
  entry.status = entry.archivedStatus;
12418
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;
12419
13793
  }
12420
13794
 
12421
13795
  out.sort((a, b) => a.slug.localeCompare(b.slug, undefined, { numeric: true }));
@@ -12631,9 +14005,20 @@ const remote = {
12631
14005
  agentType: j.agentType ?? null,
12632
14006
  epicId: j.epicId ?? null,
12633
14007
  sourcePromptId: j.sourcePromptId ?? null,
14008
+ phase: phaseOfJob(j),
14009
+ ...(isCancelledRow(j) ? { cancelled: true } : {}),
12634
14010
  }));
12635
14011
  },
12636
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
+
12637
14022
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
12638
14023
  // the admin GET /admin/scheduler/prds?slug= route (PRD 1024).
12639
14024
  async getJob(slug) {
@@ -12847,9 +14232,11 @@ const remote = {
12847
14232
  let newBody = body !== undefined ? body : origBody;
12848
14233
  let patchWarnings = [];
12849
14234
  if (hasStructured) {
12850
- const patched = applyStructuredPrdPatch(origBody, structured);
14235
+ const patched = applyStructuredPrdPatch(origBody, { ...structured, previousCriteria: fm.criteria });
12851
14236
  if (!patched.ok) return { ok: false, error: patched.error };
12852
14237
  newBody = patched.body;
14238
+ // Structured criteria (prdCriteria.cjs): frontmatter `criteria` follows the re-rendered list.
14239
+ if (patched.criteria) fm.criteria = patched.criteria;
12853
14240
  patchWarnings = patched.warnings || [];
12854
14241
  }
12855
14242
  const newRaw = serializePrdFile(fm, newBody);
@@ -12921,6 +14308,9 @@ const remote = {
12921
14308
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
12922
14309
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
12923
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);
12924
14314
  // Dependents choice (PRD 3499): cancelling a row that pending PRDs depend
12925
14315
  // on would strand them behind a dead row (Self stall, 2026-11-22). Refuse
12926
14316
  // unless the caller says what happens to them; apply that choice BEFORE
@@ -13012,6 +14402,8 @@ const remote = {
13012
14402
  j.error = cancelReason;
13013
14403
  j.cancelledAt = cancelledAt;
13014
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;
13015
14407
  j.finishedAt = new Date().toISOString();
13016
14408
  j.exitCode = j.exitCode ?? null;
13017
14409
  if (confirmedLandedCommit) j.verifierVerdict = 'cancelled_with_landed_commit';
@@ -13054,6 +14446,107 @@ const remote = {
13054
14446
  return result;
13055
14447
  },
13056
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
+
13057
14550
  // Exposes the module-level allocateParallelGroup (PRD 548) to callers that
13058
14551
  // only hold the `remote` object (lib/prd/prdCreate.cjs's create-prd route) —
13059
14552
  // reuses the same allocator the file-based /develop authoring path relies
@@ -13114,6 +14607,29 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
13114
14607
  const result = await remoteObj.resetJob(slug, { force, cwd });
13115
14608
  sendJson(res, 200, result);
13116
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
+ }
13117
14633
  }
13118
14634
 
13119
14635
  // queueOps.dismissCancelled needs the serialized queue writer; queueOps
@@ -13128,12 +14644,21 @@ queueOps.bindQueueAccess({
13128
14644
 
13129
14645
  module.exports = {
13130
14646
  PARK_ERRORS,
14647
+ harvestJobArtifacts,
14648
+ jobArtifactRunId,
13131
14649
  applyDepHoldNotices,
13132
14650
  _resetDepHoldNoticesForTests,
13133
14651
  readValidatorGateMs,
13134
14652
  resolveValidatorEstimate,
14653
+ loadValidatorCriteriaContext,
13135
14654
  planJobScope,
13136
14655
  finalizeJobScope,
14656
+ backfillMemoryStats,
14657
+ scheduleMemoryBackfill,
14658
+ cancelMemoryBackfill,
14659
+ MEMORY_BACKFILL_DELAY_MS,
14660
+ heartbeatMemGate,
14661
+ memoryCapFailureReason,
13137
14662
  sampleJobScope,
13138
14663
  readJobCgroupDir,
13139
14664
  normalizeConfig,
@@ -13145,6 +14670,10 @@ module.exports = {
13145
14670
  rescheduleIntervalTick,
13146
14671
  runQueueStarvationWatchdog,
13147
14672
  runStarveEscalationSweep,
14673
+ reportStarvedProjects,
14674
+ sendPreflightHoldNotice,
14675
+ _setPreflightHoldNoticeSenderForTests,
14676
+ _resetPreflightHoldNoticesForTests,
13148
14677
  runJobLeftoverSweep,
13149
14678
  stripAppOwnedChurn,
13150
14679
  BUDGET_WARNING_FRACTION,
@@ -13155,9 +14684,12 @@ module.exports = {
13155
14684
  persistSchedulerState,
13156
14685
  getSchedulerStateSnapshot,
13157
14686
  computeDegradedBudget,
14687
+ utilizationReading,
13158
14688
  writeQueue,
13159
14689
  _setPeriodicReverifyEnabledForTests,
13160
14690
  _setLoadGateForTests,
14691
+ _setSpawnJobForTests,
14692
+ _setSpawnInvestigationForTests,
13161
14693
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
13162
14694
  reconcile,
13163
14695
  broadcast,
@@ -13176,9 +14708,7 @@ module.exports = {
13176
14708
  pickForProject,
13177
14709
  reapDeadRunningJobs,
13178
14710
  runBranchSweep,
13179
- runEpicStateWatchForTick,
13180
14711
  pollRecoveryClearSource,
13181
- memoryLimitedBatchSize,
13182
14712
  availableForJobs,
13183
14713
  parseMemInfo,
13184
14714
  readMemInfo,
@@ -13242,6 +14772,7 @@ module.exports = {
13242
14772
  resetJobFields,
13243
14773
  resetRefusalMessage,
13244
14774
  executeJob,
14775
+ applyPersonaRefusalPark,
13245
14776
  killOrphanClaudePid,
13246
14777
  prdArchivedSkipResult,
13247
14778
  spawnJob,
@@ -13266,6 +14797,10 @@ module.exports = {
13266
14797
  performLeftoverQuarantine,
13267
14798
  spawnInvestigation,
13268
14799
  computeLaunchHolds,
14800
+ computePreflightHolds,
14801
+ computeInterruptHolds,
14802
+ buildInterruptContinuePreamble,
14803
+ runPreflightGate,
13269
14804
  handleLaunchFailure,
13270
14805
  applyLaunchFailure,
13271
14806
  setPaused,